context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/*
| Version 10.1.84
| Copyright 2013 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.Collections.Generic;
using System.Diagnostics;
using ESRI.ArcLogistics.DomainObjects;
namespace ESRI.ArcLogistics.Routing
{
/// <summary>
/// BuildRoutesOperation class.
/// </summary>
internal class BuildRoutesOperation : VrpOperation
{
#region constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public BuildRoutesOperation(SolverContext context,
Schedule schedule,
SolveOptions options,
BuildRoutesParameters inputParams)
: base(context, schedule, options)
{
Debug.Assert(inputParams != null);
_inputParams = inputParams;
}
public BuildRoutesOperation(SolverContext context,
Schedule schedule,
SolveOptions options,
SolveRequestData reqData,
List<Violation> violations,
BuildRoutesParameters inputParams)
: base(context, schedule, options)
{
Debug.Assert(reqData != null);
Debug.Assert(violations != null);
Debug.Assert(inputParams != null);
_reqData = reqData;
_violations = violations;
_inputParams = inputParams;
}
#endregion constructors
#region public overrides
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
public override SolveOperationType OperationType
{
get { return SolveOperationType.BuildRoutes; }
}
public override Object InputParams
{
get { return _inputParams; }
}
public override bool CanGetResultWithoutSolve
{
get
{
return AssignOrdersOperationHelper.CanGetResultWithoutSolve(
SolverContext,
Schedule);
}
}
public override SolveResult CreateResultWithoutSolve()
{
return AssignOrdersOperationHelper.CreateResultWithoutSolve(
SolverContext,
this.RequestData,
_violations);
}
#endregion public overrides
#region protected overrides
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
protected override SolveRequestData RequestData
{
get
{
if (_reqData == null)
_reqData = _BuildRequestData();
return _reqData;
}
}
protected override SolveRequestOptions RequestOptions
{
get
{
SolveRequestOptions opt = base.RequestOptions;
opt.ConvertUnassignedOrders = true;
return opt;
}
}
protected override VrpRequestBuilder RequestBuilder
{
get
{
return new BuildRoutesReqBuilder(SolverContext);
}
}
protected override List<Violation> GetViolations(VrpResult vrpResult)
{
List<Violation> violations = base.GetViolations(vrpResult);
if (_violations != null)
violations.AddRange(_violations);
return violations;
}
protected override VrpOperation CreateOperation(SolveRequestData reqData,
List<Violation> violations)
{
return new BuildRoutesOperation(base.SolverContext, base.Schedule,
base.Options,
reqData,
violations,
_inputParams);
}
protected override bool CanConvertResult(int solveHR)
{
return ComHelper.IsHRSucceeded(solveHR) ||
solveHR == (int)NAError.E_NA_VRP_SOLVER_PREASSIGNED_INFEASIBLE_ROUTES ||
solveHR == (int)NAError.E_NA_VRP_SOLVER_NO_SOLUTION;
}
#endregion protected overrides
#region private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private SolveRequestData _BuildRequestData()
{
// exclude ungeocoded orders
List<Order> orders = new List<Order>();
foreach (Order order in _inputParams.OrdersToAssign)
{
if (order.IsGeocoded)
orders.Add(order);
else
{
var violation = new Violation()
{
ViolationType = ViolationType.Ungeocoded,
AssociatedObject = order
};
_violations.Add(violation);
}
}
// get barriers planned on schedule's date
DateTime day = (DateTime)Schedule.PlannedDate;
ICollection<Barrier> barriers = SolverContext.Project.Barriers.Search(day);
SolveRequestData reqData = new SolveRequestData();
reqData.Routes = _inputParams.TargetRoutes;
reqData.Orders = orders;
reqData.Barriers = barriers;
return reqData;
}
#endregion private methods
#region private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
private SolveRequestData _reqData;
private List<Violation> _violations = new List<Violation>();
/// <summary>
/// Build routes operation parameters.
/// </summary>
BuildRoutesParameters _inputParams;
#endregion private fields
}
}
| |
#region Copyright
/*Copyright (C) 2015 Wosad 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.
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Wosad.WebApi.Areas.HelpPage.ModelDescriptions;
using Wosad.WebApi.Areas.HelpPage.Models;
namespace Wosad.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Redis;
using Microsoft.Azure.Management.Redis.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Redis
{
/// <summary>
/// Operations for managing the redis cache.
/// </summary>
internal partial class RedisOperations : IServiceOperations<RedisManagementClient>, IRedisOperations
{
/// <summary>
/// Initializes a new instance of the RedisOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RedisOperations(RedisManagementClient client)
{
this._client = client;
}
private RedisManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Redis.RedisManagementClient.
/// </summary>
public RedisManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create a redis cache, or replace (overwrite/recreate, with
/// potential downtime) an existing cache
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Parameters supplied to the CreateOrUpdate redis operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of CreateOrUpdate redis operation.
/// </returns>
public async Task<RedisCreateOrUpdateResponse> CreateOrUpdateAsync(string resourceGroupName, string name, RedisCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Location == null)
{
throw new ArgumentNullException("parameters.Location");
}
if (parameters.Properties == null)
{
throw new ArgumentNullException("parameters.Properties");
}
if (parameters.Properties.RedisVersion == null)
{
throw new ArgumentNullException("parameters.Properties.RedisVersion");
}
if (parameters.Properties.Sku == null)
{
throw new ArgumentNullException("parameters.Properties.Sku");
}
if (parameters.Properties.Sku.Family == null)
{
throw new ArgumentNullException("parameters.Properties.Sku.Family");
}
if (parameters.Properties.Sku.Name == null)
{
throw new ArgumentNullException("parameters.Properties.Sku.Name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Cache";
url = url + "/Redis/";
url = url + Uri.EscapeDataString(name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
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.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject redisCreateOrUpdateParametersValue = new JObject();
requestDoc = redisCreateOrUpdateParametersValue;
redisCreateOrUpdateParametersValue["location"] = parameters.Location;
JObject propertiesValue = new JObject();
redisCreateOrUpdateParametersValue["properties"] = propertiesValue;
propertiesValue["redisVersion"] = parameters.Properties.RedisVersion;
JObject skuValue = new JObject();
propertiesValue["sku"] = skuValue;
skuValue["name"] = parameters.Properties.Sku.Name;
skuValue["family"] = parameters.Properties.Sku.Family;
skuValue["capacity"] = parameters.Properties.Sku.Capacity;
if (parameters.Properties.MaxMemoryPolicy != null)
{
propertiesValue["maxMemoryPolicy"] = parameters.Properties.MaxMemoryPolicy;
}
propertiesValue["enableNonSslPort"] = parameters.Properties.EnableNonSslPort;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// 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 && statusCode != HttpStatusCode.Created)
{
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
RedisCreateOrUpdateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisCreateOrUpdateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.Type = typeInstance;
}
JToken propertiesValue2 = responseDoc["properties"];
if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null)
{
RedisReadablePropertiesWithAccessKey propertiesInstance = new RedisReadablePropertiesWithAccessKey();
result.Properties = propertiesInstance;
JToken accessKeysValue = propertiesValue2["accessKeys"];
if (accessKeysValue != null && accessKeysValue.Type != JTokenType.Null)
{
RedisAccessKeys accessKeysInstance = new RedisAccessKeys();
propertiesInstance.AccessKeys = accessKeysInstance;
JToken primaryKeyValue = accessKeysValue["primaryKey"];
if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
{
string primaryKeyInstance = ((string)primaryKeyValue);
accessKeysInstance.PrimaryKey = primaryKeyInstance;
}
JToken secondaryKeyValue = accessKeysValue["secondaryKey"];
if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
{
string secondaryKeyInstance = ((string)secondaryKeyValue);
accessKeysInstance.SecondaryKey = secondaryKeyInstance;
}
}
JToken provisioningStateValue = propertiesValue2["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue2["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue2["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue2["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue2["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue2 = propertiesValue2["sku"];
if (skuValue2 != null && skuValue2.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue2["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue2["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue2["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue2["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
JToken enableNonSslPortValue = propertiesValue2["enableNonSslPort"];
if (enableNonSslPortValue != null && enableNonSslPortValue.Type != JTokenType.Null)
{
bool enableNonSslPortInstance = ((bool)enableNonSslPortValue);
propertiesInstance.EnableNonSslPort = enableNonSslPortInstance;
}
}
}
}
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>
/// Deletes a redis cache. This operation takes a while to complete.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string name, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Cache";
url = url + "/Redis/";
url = url + Uri.EscapeDataString(name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
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
// 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 && statusCode != HttpStatusCode.Accepted && statusCode != HttpStatusCode.NotFound)
{
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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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>
/// Gets a redis cache (resource description).
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of GET redis operation.
/// </returns>
public async Task<RedisGetResponse> GetAsync(string resourceGroupName, string name, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Cache";
url = url + "/Redis/";
url = url + Uri.EscapeDataString(name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken locationValue = responseDoc["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
result.Location = locationInstance;
}
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.Type = typeInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RedisReadableProperties propertiesInstance = new RedisReadableProperties();
result.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
JToken enableNonSslPortValue = propertiesValue["enableNonSslPort"];
if (enableNonSslPortValue != null && enableNonSslPortValue.Type != JTokenType.Null)
{
bool enableNonSslPortInstance = ((bool)enableNonSslPortValue);
propertiesInstance.EnableNonSslPort = enableNonSslPortInstance;
}
}
}
}
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>
/// Gets all redis caches in a resource group (if provided) otherwise
/// all in subscription.
/// </summary>
/// <param name='resourceGroupName'>
/// Optional. The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public async Task<RedisListResponse> ListAsync(string resourceGroupName, 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("resourceGroupName", resourceGroupName);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
if (resourceGroupName != null)
{
url = url + "/resourceGroups/" + Uri.EscapeDataString(resourceGroupName);
}
url = url + "/providers/";
url = url + "Microsoft.Cache";
url = url + "/Redis/";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
RedisResource redisResourceInstance = new RedisResource();
result.Value.Add(redisResourceInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
redisResourceInstance.Id = idInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
redisResourceInstance.Location = locationInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
redisResourceInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
redisResourceInstance.Type = typeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RedisReadableProperties propertiesInstance = new RedisReadableProperties();
redisResourceInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
JToken enableNonSslPortValue = propertiesValue["enableNonSslPort"];
if (enableNonSslPortValue != null && enableNonSslPortValue.Type != JTokenType.Null)
{
bool enableNonSslPortInstance = ((bool)enableNonSslPortValue);
propertiesInstance.EnableNonSslPort = enableNonSslPortInstance;
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
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>
/// Retrieve a redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of redis list keys operation.
/// </returns>
public async Task<RedisListKeysResponse> ListKeysAsync(string resourceGroupName, string name, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
TracingAdapter.Enter(invocationId, this, "ListKeysAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Cache";
url = url + "/Redis/";
url = url + Uri.EscapeDataString(name);
url = url + "/listKeys";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
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
// 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
RedisListKeysResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisListKeysResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken primaryKeyValue = responseDoc["primaryKey"];
if (primaryKeyValue != null && primaryKeyValue.Type != JTokenType.Null)
{
string primaryKeyInstance = ((string)primaryKeyValue);
result.PrimaryKey = primaryKeyInstance;
}
JToken secondaryKeyValue = responseDoc["secondaryKey"];
if (secondaryKeyValue != null && secondaryKeyValue.Type != JTokenType.Null)
{
string secondaryKeyInstance = ((string)secondaryKeyValue);
result.SecondaryKey = secondaryKeyInstance;
}
}
}
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>
/// Gets all redis caches using next link.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response of list redis operation.
/// </returns>
public async Task<RedisListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
RedisListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new RedisListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
RedisResource redisResourceInstance = new RedisResource();
result.Value.Add(redisResourceInstance);
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
redisResourceInstance.Id = idInstance;
}
JToken locationValue = valueValue["location"];
if (locationValue != null && locationValue.Type != JTokenType.Null)
{
string locationInstance = ((string)locationValue);
redisResourceInstance.Location = locationInstance;
}
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
redisResourceInstance.Name = nameInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
redisResourceInstance.Type = typeInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
RedisReadableProperties propertiesInstance = new RedisReadableProperties();
redisResourceInstance.Properties = propertiesInstance;
JToken provisioningStateValue = propertiesValue["provisioningState"];
if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null)
{
string provisioningStateInstance = ((string)provisioningStateValue);
propertiesInstance.ProvisioningState = provisioningStateInstance;
}
JToken hostNameValue = propertiesValue["hostName"];
if (hostNameValue != null && hostNameValue.Type != JTokenType.Null)
{
string hostNameInstance = ((string)hostNameValue);
propertiesInstance.HostName = hostNameInstance;
}
JToken portValue = propertiesValue["port"];
if (portValue != null && portValue.Type != JTokenType.Null)
{
int portInstance = ((int)portValue);
propertiesInstance.Port = portInstance;
}
JToken sslPortValue = propertiesValue["sslPort"];
if (sslPortValue != null && sslPortValue.Type != JTokenType.Null)
{
int sslPortInstance = ((int)sslPortValue);
propertiesInstance.SslPort = sslPortInstance;
}
JToken redisVersionValue = propertiesValue["redisVersion"];
if (redisVersionValue != null && redisVersionValue.Type != JTokenType.Null)
{
string redisVersionInstance = ((string)redisVersionValue);
propertiesInstance.RedisVersion = redisVersionInstance;
}
JToken skuValue = propertiesValue["sku"];
if (skuValue != null && skuValue.Type != JTokenType.Null)
{
Sku skuInstance = new Sku();
propertiesInstance.Sku = skuInstance;
JToken nameValue2 = skuValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
skuInstance.Name = nameInstance2;
}
JToken familyValue = skuValue["family"];
if (familyValue != null && familyValue.Type != JTokenType.Null)
{
string familyInstance = ((string)familyValue);
skuInstance.Family = familyInstance;
}
JToken capacityValue = skuValue["capacity"];
if (capacityValue != null && capacityValue.Type != JTokenType.Null)
{
int capacityInstance = ((int)capacityValue);
skuInstance.Capacity = capacityInstance;
}
}
JToken maxMemoryPolicyValue = propertiesValue["maxMemoryPolicy"];
if (maxMemoryPolicyValue != null && maxMemoryPolicyValue.Type != JTokenType.Null)
{
string maxMemoryPolicyInstance = ((string)maxMemoryPolicyValue);
propertiesInstance.MaxMemoryPolicy = maxMemoryPolicyInstance;
}
JToken enableNonSslPortValue = propertiesValue["enableNonSslPort"];
if (enableNonSslPortValue != null && enableNonSslPortValue.Type != JTokenType.Null)
{
bool enableNonSslPortInstance = ((bool)enableNonSslPortValue);
propertiesInstance.EnableNonSslPort = enableNonSslPortInstance;
}
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
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>
/// Regenerate redis cache's access keys. This operation requires write
/// permission to the cache resource.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='name'>
/// Required. The name of the redis cache.
/// </param>
/// <param name='parameters'>
/// Required. Specifies which key to reset.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> RegenerateKeyAsync(string resourceGroupName, string name, RedisRegenerateKeyParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (name == null)
{
throw new ArgumentNullException("name");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("name", name);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "RegenerateKeyAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.Cache";
url = url + "/Redis/";
url = url + Uri.EscapeDataString(name);
url = url + "/regenerateKey";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-04-01-preview");
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
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject redisRegenerateKeyParametersValue = new JObject();
requestDoc = redisRegenerateKeyParametersValue;
redisRegenerateKeyParametersValue["keyType"] = parameters.KeyType.ToString();
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
// 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
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
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 DotNet;
using lanterna.graphics;
using lanterna.input;
using System;
using System.Runtime.CompilerServices;
using TextColor = System.Nullable<System.ConsoleColor>;
namespace lanterna.screen {
/**
* VirtualScreen wraps a normal screen and presents it as a screen that has a configurable minimum size; if the real
* screen is smaller than this size, the presented screen will add scrolling to get around it. To anyone using this
* class, it will appear and behave just as a normal screen. Scrolling is done by using CTRL + arrow keys.
* <p>
* The use case for this class is to allow you to set a minimum size that you can count on be honored, no matter how
* small the user makes the terminal. This should make programming GUIs easier.
* @author Martin
*/
class VirtualScreen : AbstractScreen {
private Screen realScreen;
private FrameRenderer frameRenderer;
private TerminalSize minimumSize;
private TerminalPosition viewportTopLeft;
private TerminalSize viewportSize;
/**
* Creates a new VirtualScreen that wraps a supplied Screen. The screen passed in here should be the real screen
* that is created on top of the real {@code Terminal}, it will have the correct size and content for what's
* actually displayed to the user, but this class will present everything as one view with a fixed minimum size,
* no matter what size the real terminal has.
* <p>
* The initial minimum size will be the current size of the screen.
* @param screen Real screen that will be used when drawing the whole or partial virtual screen
*/
public VirtualScreen(Screen screen)
: base(screen.getTerminalSize()) {
this.frameRenderer = new DefaultFrameRenderer();
this.realScreen = screen;
this.minimumSize = screen.getTerminalSize();
this.viewportTopLeft = TerminalPosition.TOP_LEFT_CORNER;
this.viewportSize = minimumSize;
}
/**
* Sets the minimum size we want the virtual screen to have. If the user resizes the real terminal to something
* smaller than this, the virtual screen will refuse to make it smaller and add scrollbars to the view.
* @param minimumSize Minimum size we want the screen to have
*/
public virtual void setMinimumSize(TerminalSize minimumSize) {
this.minimumSize = minimumSize;
TerminalSize virtualSize = minimumSize.max(realScreen.getTerminalSize());
if (!minimumSize.Equals(virtualSize)) {
addResizeRequest(virtualSize);
base.doResizeIfNecessary();
}
calculateViewport(realScreen.getTerminalSize());
}
/**
* Returns the minimum size this virtual screen can have. If the real terminal is made smaller than this, the
* virtual screen will draw scrollbars and implement scrolling
* @return Minimum size configured for this virtual screen
*/
public virtual TerminalSize getMinimumSize() {
return minimumSize;
}
//@Override
public override void startScreen() {
realScreen.startScreen();
}
//@Override
public override void stopScreen() {
this.realScreen.stopScreen();
}
//@Override
public override TextCharacter getFrontCharacter(TerminalPosition position) {
return null;
}
//@Override
public override void setCursorPosition(TerminalPosition position) {
base.setCursorPosition(position);
if (position == null) {
realScreen.setCursorPosition(null);
return;
}
position = position.withRelativeColumn(-viewportTopLeft.getColumn()).withRelativeRow(-viewportTopLeft.getRow());
if (position.getColumn() >= 0 && position.getColumn() < viewportSize.getColumns() &&
position.getRow() >= 0 && position.getRow() < viewportSize.getRows()) {
realScreen.setCursorPosition(position);
}
else {
realScreen.setCursorPosition(null);
}
}
//@Override
public override TerminalSize doResizeIfNecessary() {
TerminalSize underlyingSize = realScreen.doResizeIfNecessary();
if (underlyingSize == null) {
return null;
}
TerminalSize newVirtualSize = calculateViewport(underlyingSize);
if (!getTerminalSize().Equals(newVirtualSize)) {
addResizeRequest(newVirtualSize);
return base.doResizeIfNecessary();
}
return newVirtualSize;
}
private TerminalSize calculateViewport(TerminalSize realTerminalSize) {
TerminalSize newVirtualSize = minimumSize.max(realTerminalSize);
if (newVirtualSize.Equals(realTerminalSize)) {
viewportSize = realTerminalSize;
viewportTopLeft = TerminalPosition.TOP_LEFT_CORNER;
}
else {
TerminalSize newViewportSize = frameRenderer.getViewportSize(realTerminalSize, newVirtualSize);
if (newViewportSize.getRows() > viewportSize.getRows()) {
viewportTopLeft = viewportTopLeft.withRow(Math.Max(0, viewportTopLeft.getRow() - (newViewportSize.getRows() - viewportSize.getRows())));
}
if (newViewportSize.getColumns() > viewportSize.getColumns()) {
viewportTopLeft = viewportTopLeft.withColumn(Math.Max(0, viewportTopLeft.getColumn() - (newViewportSize.getColumns() - viewportSize.getColumns())));
}
viewportSize = newViewportSize;
}
return newVirtualSize;
}
//@Override
public override void refresh(RefreshType refreshType) {
setCursorPosition(getCursorPosition()); //Make sure the cursor is at the correct position
if (!viewportSize.Equals(realScreen.getTerminalSize())) {
this.frameRenderer.drawFrame(
this.realScreen.newTextGraphics(),
this.realScreen.getTerminalSize(),
this.getTerminalSize(),
this.viewportTopLeft);
}
//Copy the rows
TerminalPosition viewportOffset = this.frameRenderer.getViewportOffset();
if (this.realScreen is AbstractScreen) {
AbstractScreen asAbstractScreen = (AbstractScreen)this.realScreen;
this.getBackBuffer().copyTo(
asAbstractScreen.getBackBuffer(),
this.viewportTopLeft.getRow(),
this.viewportSize.getRows(),
this.viewportTopLeft.getColumn(),
this.viewportSize.getColumns(),
viewportOffset.getRow(),
viewportOffset.getColumn());
} else {
for (int y = 0; y < this.viewportSize.getRows(); y++) {
for (int x = 0; x < this.viewportSize.getColumns(); x++) {
this.realScreen.setCharacter(
x + viewportOffset.getColumn(),
y + viewportOffset.getRow(),
this.getBackBuffer().getCharacterAt(
x + this.viewportTopLeft.getColumn(),
y + this.viewportTopLeft.getRow()));
}
}
}
this.realScreen.refresh(refreshType);
}
//
public override KeyStroke pollInput() {
return this.filter(this.realScreen.pollInput());
}
//
//
//
//
private KeyStroke filter(KeyStroke keyStroke) {
if (keyStroke == null) {
return null;
}
if (keyStroke.isAltDown() && keyStroke.getKeyType() == KeyType.ArrowLeft) {
if (this.viewportTopLeft.getColumn() > 0) {
this.viewportTopLeft = this.viewportTopLeft.withRelativeColumn(-1);
this.refresh();
return null;
}
} else if (keyStroke.isAltDown() && keyStroke.getKeyType() == KeyType.ArrowRight) {
if (this.viewportTopLeft.getColumn() + this.viewportSize.getColumns() < this.getTerminalSize().getColumns()) {
this.viewportTopLeft = this.viewportTopLeft.withRelativeColumn(1);
this.refresh();
return null;
}
} else if (keyStroke.isAltDown() && keyStroke.getKeyType() == KeyType.ArrowUp) {
if (this.viewportTopLeft.getRow() > 0) {
this.viewportTopLeft = this.viewportTopLeft.withRelativeRow(-1);
this.realScreen.scrollLines(0, this.viewportSize.getRows() - 1, -1);
this.refresh();
return null;
}
} else if (keyStroke.isAltDown() && keyStroke.getKeyType() == KeyType.ArrowDown
&& this.viewportTopLeft.getRow() + this.viewportSize.getRows() < this.getTerminalSize().getRows()) {
this.viewportTopLeft = this.viewportTopLeft.withRelativeRow(1);
this.realScreen.scrollLines(0, this.viewportSize.getRows() - 1, 1);
this.refresh();
return null;
}
return keyStroke;
}
//
public override void scrollLines(int firstLine, int lastLine, int distance) {
// do base class stuff (scroll own back buffer)
base.scrollLines(firstLine, lastLine, distance);
// vertical range visible in realScreen:
int vpFirst = this.viewportTopLeft.getRow();
int vpRows = this.viewportSize.getRows();
// adapt to realScreen range:
firstLine = Math.Max(0, firstLine - vpFirst);
lastLine = Math.Min(vpRows - 1, lastLine - vpFirst);
// if resulting range non-empty: scroll that range in realScreen:
if (firstLine <= lastLine) {
this.realScreen.scrollLines(firstLine, lastLine, distance);
}
}
/**
* Interface for rendering the virtual screen's frame when the real terminal is too small for the virtual screen
*/
public interface FrameRenderer {
/**
* Given the size of the real terminal and the current size of the virtual screen, how large should the viewport
* where the screen content is drawn be?
* @param realSize Size of the real terminal
* @param virtualSize Size of the virtual screen
* @return Size of the viewport, according to this FrameRenderer
*/
TerminalSize getViewportSize(TerminalSize realSize, TerminalSize virtualSize);
/**
* Where in the virtual screen should the top-left position of the viewport be? To draw the viewport from the
* top-left position of the screen, return 0x0 (or TerminalPosition.TOP_LEFT_CORNER) here.
* @return Position of the top-left corner of the viewport inside the screen
*/
TerminalPosition getViewportOffset();
/**
* Drawn the 'frame', meaning anything that is outside the viewport (title, scrollbar, etc)
* @param graphics Graphics to use to text drawing operations
* @param realSize Size of the real terminal
* @param virtualSize Size of the virtual screen
* @param virtualScrollPosition If the virtual screen is larger than the real terminal, this is the current
* scroll offset the VirtualScreen is using
*/
void drawFrame(
TextGraphics graphics,
TerminalSize realSize,
TerminalSize virtualSize,
TerminalPosition virtualScrollPosition);
}
class DefaultFrameRenderer : VirtualScreen.FrameRenderer {
//
public virtual TerminalSize getViewportSize(TerminalSize realSize, TerminalSize virtualSize) {
if (realSize.getColumns() > 1 && realSize.getRows() > 2) {
return realSize.withRelativeColumns(-1).withRelativeRows(-2);
}
return realSize;
}
//
public virtual TerminalPosition getViewportOffset() {
return TerminalPosition.TOP_LEFT_CORNER;
}
//
public virtual void drawFrame(
TextGraphics graphics,
TerminalSize realSize,
TerminalSize virtualSize,
TerminalPosition virtualScrollPosition) {
if (realSize.getColumns() == 1 || realSize.getRows() <= 2) {
return;
}
TerminalSize viewportSize = this.getViewportSize(realSize, virtualSize);
graphics.setForegroundColor(ConsoleColor.White);
graphics.setBackgroundColor(ConsoleColor.Black);
graphics.fill(' ');
graphics.putString(0, graphics.getSize().getRows() - 1, "Terminal too small, use ALT+arrows to scroll");
int horizontalSize = ByteCodeHelper.d2i((double)viewportSize.getColumns() / (double)virtualSize.getColumns() * (double)viewportSize.getColumns());
int scrollable = viewportSize.getColumns() - horizontalSize - 1;
int horizontalPosition = ByteCodeHelper.d2i((double)scrollable * ((double)virtualScrollPosition.getColumn() / (double)(virtualSize.getColumns() - viewportSize.getColumns())));
TerminalPosition arg_E6_1 = new TerminalPosition(horizontalPosition, graphics.getSize().getRows() - 2);
graphics.drawLine(
arg_E6_1,
new TerminalPosition(horizontalPosition + horizontalSize, graphics.getSize().getRows() - 2),
Symbols.BLOCK_MIDDLE);
int verticalSize = ByteCodeHelper.d2i((double)viewportSize.getRows() / (double)virtualSize.getRows() * (double)viewportSize.getRows());
scrollable = viewportSize.getRows() - verticalSize - 1;
int verticalPosition = ByteCodeHelper.d2i((double)scrollable * ((double)virtualScrollPosition.getRow() / (double)(virtualSize.getRows() - viewportSize.getRows())));
TerminalPosition arg_179_1 = new TerminalPosition(graphics.getSize().getColumns() - 1, verticalPosition);
graphics.drawLine(
arg_179_1,
new TerminalPosition(graphics.getSize().getColumns() - 1, verticalPosition + verticalSize),
Symbols.BLOCK_MIDDLE);
}
}
}
}
| |
//-----------------------------------------------------------------------------
// <copyright file="CommittableTransaction.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------------
namespace System.Transactions
{
using System;
using System.Threading;
using System.Transactions.Diagnostics;
/// <include file='doc\CommittableTransaction.uex' path='docs/doc[@for="CommittableTransaction"]/*' />
// When we serialize a CommittableTransaction, we specify the type OletxTransaction, so a CommittableTransaction never
// actually gets deserialized.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229:ImplementSerializationConstructors")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")]
[Serializable]
public sealed class CommittableTransaction : Transaction, IAsyncResult
{
internal bool completedSynchronously = false;
// Create a transaction with defaults
public CommittableTransaction(
) : this(System.Transactions.TransactionManager.DefaultIsolationLevel,
System.Transactions.TransactionManager.DefaultTimeout)
{
}
// Create a transaction with the given info
public CommittableTransaction(
TimeSpan timeout
) : this(System.Transactions.TransactionManager.DefaultIsolationLevel, timeout)
{
}
// Create a transaction with the given options
public CommittableTransaction(
TransactionOptions options
) : this(options.IsolationLevel, options.Timeout)
{
}
internal CommittableTransaction(
IsolationLevel isoLevel,
TimeSpan timeout
) : base(isoLevel, (InternalTransaction)null)
{
// object to use for synchronization rather than locking on a public object
this.internalTransaction = new InternalTransaction(timeout, this);
// Because we passed null for the internal transaction to the base class, we need to
// fill in the traceIdentifier field here.
this.internalTransaction.cloneCount = 1;
this.cloneId = 1;
if (DiagnosticTrace.Information)
{
TransactionCreatedTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
this.TransactionTraceId
);
}
}
public IAsyncResult BeginCommit(
AsyncCallback asyncCallback,
object asyncState
)
{
if (DiagnosticTrace.Verbose)
{
MethodEnteredTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"CommittableTransaction.BeginCommit"
);
TransactionCommitCalledTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
this.TransactionTraceId
);
}
if (Disposed)
{
throw new ObjectDisposedException("Transaction");
}
lock (this.internalTransaction)
{
if (this.complete)
{
throw TransactionException.CreateTransactionCompletedException(SR.GetString(SR.TraceSourceLtm), this.DistributedTxId);
}
// this.complete will get set to true when the transaction enters a state that is
// beyond Phase0.
this.internalTransaction.State.BeginCommit(this.internalTransaction, true, asyncCallback, asyncState);
}
if (DiagnosticTrace.Verbose)
{
MethodExitedTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"CommittableTransaction.BeginCommit"
);
}
return this;
}
// Forward the commit to the state machine to take the appropriate action.
//
/// <include file='doc\Transaction.uex' path='docs/doc[@for="Transaction."]/*' />
public void Commit()
{
if (DiagnosticTrace.Verbose)
{
MethodEnteredTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"CommittableTransaction.Commit"
);
TransactionCommitCalledTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
this.TransactionTraceId
);
}
if (Disposed)
{
throw new ObjectDisposedException("Transaction");
}
lock (this.internalTransaction)
{
if (this.complete)
{
throw TransactionException.CreateTransactionCompletedException(SR.GetString(SR.TraceSourceLtm), this.DistributedTxId);
}
this.internalTransaction.State.BeginCommit(this.internalTransaction, false, null, null);
// now that commit has started wait for the monitor on the transaction to know
// if the transaction is done.
do
{
if (this.internalTransaction.State.IsCompleted(this.internalTransaction))
{
break;
}
} while (System.Threading.Monitor.Wait(this.internalTransaction));
this.internalTransaction.State.EndCommit(this.internalTransaction);
}
if (DiagnosticTrace.Verbose)
{
MethodExitedTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"CommittableTransaction.Commit"
);
}
}
internal override void InternalDispose()
{
if (DiagnosticTrace.Verbose)
{
MethodEnteredTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"IDisposable.Dispose"
);
}
if (Interlocked.Exchange(ref this.disposed, Transaction.disposedTrueValue) == Transaction.disposedTrueValue)
{
return;
}
if (this.internalTransaction.State.get_Status(this.internalTransaction) == TransactionStatus.Active)
{
lock (this.internalTransaction)
{
// Since this is the root transaction do state based dispose.
this.internalTransaction.State.DisposeRoot(this.internalTransaction);
}
}
// Attempt to clean up the internal transaction
long remainingITx = Interlocked.Decrement(ref this.internalTransaction.cloneCount);
if (remainingITx == 0)
{
this.internalTransaction.Dispose();
}
if (DiagnosticTrace.Verbose)
{
MethodExitedTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"IDisposable.Dispose"
);
}
}
public void EndCommit(
IAsyncResult asyncResult
)
{
if (DiagnosticTrace.Verbose)
{
MethodEnteredTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"CommittableTransaction.EndCommit"
);
}
if (asyncResult != ((object)this))
{
throw new ArgumentException(SR.GetString(SR.BadAsyncResult), "asyncResult");
}
lock (this.internalTransaction)
{
do
{
if (this.internalTransaction.State.IsCompleted(this.internalTransaction))
{
break;
}
} while (System.Threading.Monitor.Wait(this.internalTransaction));
this.internalTransaction.State.EndCommit(this.internalTransaction);
}
if (DiagnosticTrace.Verbose)
{
MethodExitedTraceRecord.Trace(SR.GetString(SR.TraceSourceLtm),
"CommittableTransaction.EndCommit"
);
}
}
object IAsyncResult.AsyncState
{
get
{
return this.internalTransaction.asyncState;
}
}
bool IAsyncResult.CompletedSynchronously
{
get
{
return this.completedSynchronously;
}
}
WaitHandle IAsyncResult.AsyncWaitHandle
{
get
{
if (this.internalTransaction.asyncResultEvent == null)
{
lock (this.internalTransaction)
{
if (this.internalTransaction.asyncResultEvent == null)
{
// Demand create an event that is already signaled if the transaction has completed.
ManualResetEvent temp = new ManualResetEvent(
this.internalTransaction.State.get_Status(this.internalTransaction) != TransactionStatus.Active
);
this.internalTransaction.asyncResultEvent = temp;
}
}
}
return this.internalTransaction.asyncResultEvent;
}
}
bool IAsyncResult.IsCompleted
{
get
{
lock (this.internalTransaction)
{
return this.internalTransaction.State.get_Status(this.internalTransaction) != TransactionStatus.Active;
}
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gccv = Google.Cloud.Channel.V1;
using sys = System;
namespace Google.Cloud.Channel.V1
{
/// <summary>Resource name for the <c>Product</c> resource.</summary>
public sealed partial class ProductName : gax::IResourceName, sys::IEquatable<ProductName>
{
/// <summary>The possible contents of <see cref="ProductName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>products/{product}</c>.</summary>
Product = 1,
}
private static gax::PathTemplate s_product = new gax::PathTemplate("products/{product}");
/// <summary>Creates a <see cref="ProductName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="ProductName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static ProductName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ProductName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="ProductName"/> with the pattern <c>products/{product}</c>.</summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ProductName"/> constructed from the provided ids.</returns>
public static ProductName FromProduct(string productId) =>
new ProductName(ResourceNameType.Product, productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProductName"/> with pattern
/// <c>products/{product}</c>.
/// </summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProductName"/> with pattern <c>products/{product}</c>.
/// </returns>
public static string Format(string productId) => FormatProduct(productId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ProductName"/> with pattern
/// <c>products/{product}</c>.
/// </summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ProductName"/> with pattern <c>products/{product}</c>.
/// </returns>
public static string FormatProduct(string productId) =>
s_product.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)));
/// <summary>Parses the given resource name string into a new <see cref="ProductName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}</c></description></item></list>
/// </remarks>
/// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ProductName"/> if successful.</returns>
public static ProductName Parse(string productName) => Parse(productName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ProductName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="ProductName"/> if successful.</returns>
public static ProductName Parse(string productName, bool allowUnparsed) =>
TryParse(productName, allowUnparsed, out ProductName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProductName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}</c></description></item></list>
/// </remarks>
/// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProductName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string productName, out ProductName result) => TryParse(productName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ProductName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="productName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ProductName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string productName, bool allowUnparsed, out ProductName result)
{
gax::GaxPreconditions.CheckNotNull(productName, nameof(productName));
gax::TemplatedResourceName resourceName;
if (s_product.TryParseName(productName, out resourceName))
{
result = FromProduct(resourceName[0]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(productName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ProductName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string productId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProductId = productId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ProductName"/> class from the component parts of pattern
/// <c>products/{product}</c>
/// </summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
public ProductName(string productId) : this(ResourceNameType.Product, productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Product</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProductId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.Product: return s_product.Expand(ProductId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as ProductName);
/// <inheritdoc/>
public bool Equals(ProductName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ProductName a, ProductName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ProductName a, ProductName b) => !(a == b);
}
/// <summary>Resource name for the <c>Sku</c> resource.</summary>
public sealed partial class SkuName : gax::IResourceName, sys::IEquatable<SkuName>
{
/// <summary>The possible contents of <see cref="SkuName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>products/{product}/skus/{sku}</c>.</summary>
ProductSku = 1,
}
private static gax::PathTemplate s_productSku = new gax::PathTemplate("products/{product}/skus/{sku}");
/// <summary>Creates a <see cref="SkuName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="SkuName"/> containing the provided <paramref name="unparsedResourceName"/>.
/// </returns>
public static SkuName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SkuName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>Creates a <see cref="SkuName"/> with the pattern <c>products/{product}/skus/{sku}</c>.</summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SkuName"/> constructed from the provided ids.</returns>
public static SkuName FromProductSku(string productId, string skuId) =>
new SkuName(ResourceNameType.ProductSku, productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)), skuId: gax::GaxPreconditions.CheckNotNullOrEmpty(skuId, nameof(skuId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SkuName"/> with pattern
/// <c>products/{product}/skus/{sku}</c>.
/// </summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SkuName"/> with pattern <c>products/{product}/skus/{sku}</c>.
/// </returns>
public static string Format(string productId, string skuId) => FormatProductSku(productId, skuId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SkuName"/> with pattern
/// <c>products/{product}/skus/{sku}</c>.
/// </summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SkuName"/> with pattern <c>products/{product}/skus/{sku}</c>.
/// </returns>
public static string FormatProductSku(string productId, string skuId) =>
s_productSku.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)), gax::GaxPreconditions.CheckNotNullOrEmpty(skuId, nameof(skuId)));
/// <summary>Parses the given resource name string into a new <see cref="SkuName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}/skus/{sku}</c></description></item></list>
/// </remarks>
/// <param name="skuName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SkuName"/> if successful.</returns>
public static SkuName Parse(string skuName) => Parse(skuName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SkuName"/> instance; optionally allowing an
/// unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}/skus/{sku}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="skuName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="SkuName"/> if successful.</returns>
public static SkuName Parse(string skuName, bool allowUnparsed) =>
TryParse(skuName, allowUnparsed, out SkuName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>Tries to parse the given resource name string into a new <see cref="SkuName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}/skus/{sku}</c></description></item></list>
/// </remarks>
/// <param name="skuName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SkuName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string skuName, out SkuName result) => TryParse(skuName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SkuName"/> instance; optionally allowing
/// an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet"><item><description><c>products/{product}/skus/{sku}</c></description></item></list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="skuName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SkuName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string skuName, bool allowUnparsed, out SkuName result)
{
gax::GaxPreconditions.CheckNotNull(skuName, nameof(skuName));
gax::TemplatedResourceName resourceName;
if (s_productSku.TryParseName(skuName, out resourceName))
{
result = FromProductSku(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(skuName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SkuName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string productId = null, string skuId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ProductId = productId;
SkuId = skuId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SkuName"/> class from the component parts of pattern
/// <c>products/{product}/skus/{sku}</c>
/// </summary>
/// <param name="productId">The <c>Product</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="skuId">The <c>Sku</c> ID. Must not be <c>null</c> or empty.</param>
public SkuName(string productId, string skuId) : this(ResourceNameType.ProductSku, productId: gax::GaxPreconditions.CheckNotNullOrEmpty(productId, nameof(productId)), skuId: gax::GaxPreconditions.CheckNotNullOrEmpty(skuId, nameof(skuId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>Product</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProductId { get; }
/// <summary>
/// The <c>Sku</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string SkuId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProductSku: return s_productSku.Expand(ProductId, SkuId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as SkuName);
/// <inheritdoc/>
public bool Equals(SkuName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SkuName a, SkuName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SkuName a, SkuName b) => !(a == b);
}
public partial class Product
{
/// <summary>
/// <see cref="gccv::ProductName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::ProductName ProductName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::ProductName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class Sku
{
/// <summary>
/// <see cref="gccv::SkuName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gccv::SkuName SkuName
{
get => string.IsNullOrEmpty(Name) ? null : gccv::SkuName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
// 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 Xunit;
namespace System.Linq.Expressions.Tests
{
public class Break : GotoExpressionTests
{
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void JustBreakValue(object value, bool useInterpreter)
{
Type type = value.GetType();
LabelTarget target = Expression.Label(type);
Expression block = Expression.Block(
Expression.Break(target, Expression.Constant(value)),
Expression.Label(target, Expression.Default(type))
);
Expression equals = Expression.Equal(Expression.Constant(value), block);
Assert.True(Expression.Lambda<Func<bool>>(equals).Compile(useInterpreter)());
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void BreakToMiddle(bool useInterpreter)
{
// The behaviour is that return jumps to a label, but does not necessarily leave a block.
LabelTarget target = Expression.Label(typeof(int));
Expression block = Expression.Block(
Expression.Break(target, Expression.Constant(1)),
Expression.Label(target, Expression.Constant(2)),
Expression.Constant(3)
);
Assert.Equal(3, Expression.Lambda<Func<int>>(block).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void BreakJumps(object value, bool useInterpreter)
{
Type type = value.GetType();
LabelTarget target = Expression.Label(type);
Expression block = Expression.Block(
Expression.Break(target, Expression.Constant(value)),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target, Expression.Default(type))
);
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(Expression.Constant(value), block)).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(TypesData))]
public void NonVoidTargetBreakHasNoValue(Type type)
{
LabelTarget target = Expression.Label(type);
Assert.Throws<ArgumentException>("target", () => Expression.Break(target));
}
[Theory]
[MemberData(nameof(TypesData))]
public void NonVoidTargetBreakHasNoValueTypeExplicit(Type type)
{
LabelTarget target = Expression.Label(type);
Assert.Throws<ArgumentException>("target", () => Expression.Break(target, type));
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void BreakVoidNoValue(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression block = Expression.Block(
Expression.Break(target),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target)
);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[ClassData(typeof(CompilationTypes))]
public void BreakExplicitVoidNoValue(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression block = Expression.Block(
Expression.Break(target, typeof(void)),
Expression.Throw(Expression.Constant(new InvalidOperationException())),
Expression.Label(target)
);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[MemberData(nameof(TypesData))]
public void NullValueOnNonVoidBreak(Type type)
{
Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type)));
Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type), default(Expression)));
Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(type), null, type));
}
[Theory]
[MemberData(nameof(ConstantValueData))]
public void ExplicitNullTypeWithValue(object value)
{
Assert.Throws<ArgumentException>("target", () => Expression.Break(Expression.Label(value.GetType()), default(Type)));
}
[Fact]
public void UnreadableLabel()
{
Expression value = Expression.Property(null, typeof(Unreadable<string>), "WriteOnly");
LabelTarget target = Expression.Label(typeof(string));
Assert.Throws<ArgumentException>("value", () => Expression.Break(target, value));
Assert.Throws<ArgumentException>("value", () => Expression.Break(target, value, typeof(string)));
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void CanAssignAnythingToVoid(object value, bool useInterpreter)
{
LabelTarget target = Expression.Label();
BlockExpression block = Expression.Block(
Expression.Break(target, Expression.Constant(value)),
Expression.Label(target)
);
Assert.Equal(typeof(void), block.Type);
Expression.Lambda<Action>(block).Compile(useInterpreter)();
}
[Theory]
[MemberData(nameof(NonObjectAssignableConstantValueData))]
public void CannotAssignValueTypesToObject(object value)
{
Assert.Throws<ArgumentException>(null, () => Expression.Break(Expression.Label(typeof(object)), Expression.Constant(value)));
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValueData))]
public void ExplicitTypeAssigned(object value, bool useInterpreter)
{
LabelTarget target = Expression.Label(typeof(object));
BlockExpression block = Expression.Block(
Expression.Break(target, Expression.Constant(value), typeof(object)),
Expression.Label(target, Expression.Default(typeof(object)))
);
Assert.Equal(typeof(object), block.Type);
Assert.Equal(value, Expression.Lambda<Func<object>>(block).Compile(useInterpreter)());
}
[Fact]
public void BreakQuotesIfNecessary()
{
LabelTarget target = Expression.Label(typeof(Expression<Func<int>>));
BlockExpression block = Expression.Block(
Expression.Break(target, Expression.Lambda<Func<int>>(Expression.Constant(0))),
Expression.Label(target, Expression.Default(typeof(Expression<Func<int>>)))
);
Assert.Equal(typeof(Expression<Func<int>>), block.Type);
}
[Fact]
public void UpdateSameIsSame()
{
LabelTarget target = Expression.Label(typeof(int));
Expression value = Expression.Constant(0);
GotoExpression ret = Expression.Break(target, value);
Assert.Same(ret, ret.Update(target, value));
Assert.Same(ret, NoOpVisitor.Instance.Visit(ret));
}
[Fact]
public void UpdateDiferentValueIsDifferent()
{
LabelTarget target = Expression.Label(typeof(int));
GotoExpression ret = Expression.Break(target, Expression.Constant(0));
Assert.NotSame(ret, ret.Update(target, Expression.Constant(0)));
}
[Fact]
public void UpdateDifferentTargetIsDifferent()
{
Expression value = Expression.Constant(0);
GotoExpression ret = Expression.Break(Expression.Label(typeof(int)), value);
Assert.NotSame(ret, ret.Update(Expression.Label(typeof(int)), value));
}
[Fact]
public void OpenGenericType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>)));
}
[Fact]
public static void TypeContainsGenericParameters()
{
Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>.Enumerator)));
Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(List<>).MakeGenericType(typeof(List<>))));
}
[Fact]
public void PointerType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(int).MakePointerType()));
}
[Fact]
public void ByRefType()
{
Assert.Throws<ArgumentException>("type", () => Expression.Break(Expression.Label(typeof(void)), typeof(int).MakeByRefType()));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void UndefinedLabel(bool useInterpreter)
{
Expression<Action> breakNowhere = Expression.Lambda<Action>(Expression.Break(Expression.Label()));
Assert.Throws<InvalidOperationException>(() => breakNowhere.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void AmbiguousJump(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression<Action> exp = Expression.Lambda<Action>(
Expression.Block(
Expression.Break(target),
Expression.Block(Expression.Label(target)),
Expression.Block(Expression.Label(target))
)
);
Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void MultipleDefinitionsInSeparateBlocks(bool useInterpreter)
{
LabelTarget target = Expression.Label(typeof(int));
Func<int> add = Expression.Lambda<Func<int>>(
Expression.Add(
Expression.Add(
Expression.Block(
Expression.Break(target, Expression.Constant(6)),
Expression.Throw(Expression.Constant(new Exception())),
Expression.Label(target, Expression.Constant(0))
),
Expression.Block(
Expression.Break(target, Expression.Constant(4)),
Expression.Throw(Expression.Constant(new Exception())),
Expression.Label(target, Expression.Constant(0))
)
),
Expression.Block(
Expression.Break(target, Expression.Constant(5)),
Expression.Throw(Expression.Constant(new Exception())),
Expression.Label(target, Expression.Constant(0))
)
)
).Compile(useInterpreter);
Assert.Equal(15, add());
}
[Theory, ClassData(typeof(CompilationTypes))]
public void JumpIntoExpression(bool useInterpreter)
{
LabelTarget target = Expression.Label();
Expression<Func<bool>> isInt = Expression.Lambda<Func<bool>>(
Expression.Block(
Expression.Break(target),
Expression.TypeIs(Expression.Label(target), typeof(int))
)
);
Assert.Throws<InvalidOperationException>(() => isInt.Compile(useInterpreter));
}
[Theory, ClassData(typeof(CompilationTypes))]
public void JumpInWithValue(bool useInterpreter)
{
LabelTarget target = Expression.Label(typeof(int));
Expression<Func<int>> exp = Expression.Lambda<Func<int>>(
Expression.Block(
Expression.Break(target, Expression.Constant(2)),
Expression.Block(
Expression.Label(target, Expression.Constant(3)))
)
);
Assert.Throws<InvalidOperationException>(() => exp.Compile(useInterpreter));
}
}
}
| |
using System;
using System.Text;
///<summary>
///System.Test.UnicodeEncoding.GetByteCount(String) [v-zuolan]
///</summary>
public class UnicodeEncodingGetByteCount
{
public static int Main()
{
UnicodeEncodingGetByteCount testObj = new UnicodeEncodingGetByteCount();
TestLibrary.TestFramework.BeginTestCase("for field of System.Test.UnicodeEncoding");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("Positive");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("Positive");
retVal = NegTest1() && retVal;
return retVal;
}
#region Helper Method
//Create a None-Surrogate-Char String.
public String GetString(int length)
{
if (length <= 0) return "";
String tempStr = null;
int i = 0;
while (i < length)
{
Char temp = TestLibrary.Generator.GetChar(-55);
if (!Char.IsSurrogate(temp))
{
tempStr = tempStr + temp.ToString();
i++;
}
}
return tempStr;
}
public String ToString(String myString)
{
String str = "{";
Char[] chars = myString.ToCharArray();
for (int i = 0;i < chars.Length; i++)
{
str = str + @"\u" + String.Format("{0:X04}", (int)chars[i]);
if (i != chars.Length - 1) str = str + ",";
}
str = str + "}";
return str;
}
#endregion
#region Positive Test Logic
public bool PosTest1()
{
bool retVal = true;
UnicodeEncoding uEncoding = new UnicodeEncoding();
int expectedValue = 0;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest1:Invoke the method with a empty String.");
try
{
actualValue = uEncoding.GetByteCount("");
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("001", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
String str = GetString(10);
UnicodeEncoding uEncoding = new UnicodeEncoding();
int expectedValue = 20;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest2:Invoke the method with normal string");
try
{
String temp = ToString(str);
actualValue = uEncoding.GetByteCount(str);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("003", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when chars is:" + ToString(str));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e + "when chars is:" + ToString(str));
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
String str = GetString(1);
UnicodeEncoding uEncoding = new UnicodeEncoding();
int expectedValue = 2;
int actualValue;
TestLibrary.TestFramework.BeginScenario("PosTest3:Invoke the method with one char String.");
try
{
actualValue = uEncoding.GetByteCount(str);
if (expectedValue != actualValue)
{
TestLibrary.TestFramework.LogError("005", "ExpectedValue(" + expectedValue + ") !=ActualValue(" + actualValue + ") when chars is:" + ToString(str));
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception:" + e + "when chars is:" + ToString(str));
retVal = false;
}
return retVal;
}
#endregion
#region Negative Test Logic
public bool NegTest1()
{
bool retVal = true;
String str = null;
UnicodeEncoding uEncoding = new UnicodeEncoding();
int actualValue;
TestLibrary.TestFramework.BeginScenario("NegTest1:Invoke the method with null");
try
{
actualValue = uEncoding.GetByteCount(str);
TestLibrary.TestFramework.LogError("007", "No ArgumentNullException throw out expected.");
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
namespace System.IO
{
// This class implements a text reader that reads from a string.
//
public class StringReader : TextReader
{
private string _s;
private int _pos;
private int _length;
public StringReader(string s)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
_length = s == null ? 0 : s.Length;
}
protected override void Dispose(bool disposing)
{
_s = null;
_pos = 0;
_length = 0;
base.Dispose(disposing);
}
// Returns the next available character without actually reading it from
// the underlying string. The current position of the StringReader is not
// changed by this operation. The returned value is -1 if no further
// characters are available.
//
[Pure]
public override int Peek()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
if (_pos == _length)
{
return -1;
}
return _s[_pos];
}
// Reads the next character from the underlying string. The returned value
// is -1 if no further characters are available.
//
public override int Read()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
if (_pos == _length)
{
return -1;
}
return _s[_pos++];
}
// Reads a block of characters. This method will read up to count
// characters from this StringReader into the buffer character
// array starting at position index. Returns the actual number of
// characters read, or zero if the end of the string is reached.
//
public override int Read(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
int n = _length - _pos;
if (n > 0)
{
if (n > count)
{
n = count;
}
_s.CopyTo(_pos, buffer, index, n);
_pos += n;
}
return n;
}
public override string ReadToEnd()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
string s;
if (_pos == 0)
{
s = _s;
}
else
{
s = _s.Substring(_pos, _length - _pos);
}
_pos = _length;
return s;
}
// Reads a line. A line is defined as a sequence of characters followed by
// a carriage return ('\r'), a line feed ('\n'), or a carriage return
// immediately followed by a line feed. The resulting string does not
// contain the terminating carriage return and/or line feed. The returned
// value is null if the end of the underlying string has been reached.
//
public override string ReadLine()
{
if (_s == null)
{
throw new ObjectDisposedException(null, SR.ObjectDisposed_ReaderClosed);
}
int i = _pos;
while (i < _length)
{
char ch = _s[i];
if (ch == '\r' || ch == '\n')
{
string result = _s.Substring(_pos, i - _pos);
_pos = i + 1;
if (ch == '\r' && _pos < _length && _s[_pos] == '\n')
{
_pos++;
}
return result;
}
i++;
}
if (i > _pos)
{
string result = _s.Substring(_pos, i - _pos);
_pos = i;
return result;
}
return null;
}
#region Task based Async APIs
public override Task<string> ReadLineAsync()
{
return Task.FromResult(ReadLine());
}
public override Task<string> ReadToEndAsync()
{
return Task.FromResult(ReadToEnd());
}
public override Task<int> ReadBlockAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return Task.FromResult(ReadBlock(buffer, index, count));
}
public override Task<int> ReadAsync(char[] buffer, int index, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
}
if (index < 0 || count < 0)
{
throw new ArgumentOutOfRangeException((index < 0 ? "index" : "count"), SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (buffer.Length - index < count)
{
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
return Task.FromResult(Read(buffer, index, count));
}
#endregion
}
}
| |
/*
* 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;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.CoreModules.World.Terrain;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.Estate
{
public class EstateManagementModule : IEstateModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private delegate void LookupUUIDS(List<UUID> uuidLst);
private Scene m_scene;
private EstateTerrainXferHandler TerrainUploader = null;
#region Packet Data Responders
private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice)
{
uint sun = 0;
if (!m_scene.RegionInfo.EstateSettings.UseGlobalTime)
sun=(uint)(m_scene.RegionInfo.EstateSettings.SunPosition*1024.0) + 0x1800;
UUID estateOwner;
if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero)
estateOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
else
estateOwner = m_scene.RegionInfo.MasterAvatarAssignedUUID;
if (m_scene.Permissions.IsGod(remote_client.AgentId))
estateOwner = remote_client.AgentId;
remote_client.SendDetailedEstateData(invoice,
m_scene.RegionInfo.EstateSettings.EstateName,
m_scene.RegionInfo.EstateSettings.EstateID,
m_scene.RegionInfo.EstateSettings.ParentEstateID,
GetEstateFlags(),
sun,
m_scene.RegionInfo.RegionSettings.Covenant,
m_scene.RegionInfo.EstateSettings.AbuseEmail,
estateOwner);
remote_client.SendEstateManagersList(invoice,
m_scene.RegionInfo.EstateSettings.EstateManagers,
m_scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendBannedUserList(invoice,
m_scene.RegionInfo.EstateSettings.EstateBans,
m_scene.RegionInfo.EstateSettings.EstateID);
}
private void estateSetRegionInfoHandler(bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor,
int matureLevel, bool restrictPushObject, bool allowParcelChanges)
{
if (blockTerraform)
m_scene.RegionInfo.RegionSettings.BlockTerraform = true;
else
m_scene.RegionInfo.RegionSettings.BlockTerraform = false;
if (noFly)
m_scene.RegionInfo.RegionSettings.BlockFly = true;
else
m_scene.RegionInfo.RegionSettings.BlockFly = false;
if (allowDamage)
m_scene.RegionInfo.RegionSettings.AllowDamage = true;
else
m_scene.RegionInfo.RegionSettings.AllowDamage = false;
if (blockLandResell)
m_scene.RegionInfo.RegionSettings.AllowLandResell = false;
else
m_scene.RegionInfo.RegionSettings.AllowLandResell = true;
m_scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents;
m_scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor;
if (matureLevel <= 13)
m_scene.RegionInfo.RegionSettings.Maturity = 0;
else if (matureLevel <= 21)
m_scene.RegionInfo.RegionSettings.Maturity = 1;
else
m_scene.RegionInfo.RegionSettings.Maturity = 2;
if (restrictPushObject)
m_scene.RegionInfo.RegionSettings.RestrictPushing = true;
else
m_scene.RegionInfo.RegionSettings.RestrictPushing = false;
if (allowParcelChanges)
m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true;
else
m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false;
m_scene.RegionInfo.RegionSettings.Save();
sendRegionInfoPacketToAll();
}
public void setEstateTerrainBaseTexture(IClientAPI remoteClient, int corner, UUID texture)
{
if (texture == UUID.Zero)
return;
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
m_scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
m_scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
m_scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
}
public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue)
{
switch (corner)
{
case 0:
m_scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
m_scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
m_scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
m_scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
m_scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
m_scene.RegionInfo.RegionSettings.Save();
}
private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient)
{
sendRegionHandshakeToAll();
}
public void setRegionTerrainSettings(float WaterHeight,
float TerrainRaiseLimit, float TerrainLowerLimit,
bool UseEstateSun, bool UseFixedSun, float SunHour,
bool UseGlobal, bool EstateFixedSun, float EstateSunHour)
{
// Water Height
m_scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight;
// Terraforming limits
m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit;
m_scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit;
// Time of day / fixed sun
m_scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun;
m_scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun;
m_scene.RegionInfo.RegionSettings.SunPosition = SunHour;
TriggerEstateToolsSunUpdate();
//m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString());
//m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString());
sendRegionInfoPacketToAll();
m_scene.RegionInfo.RegionSettings.Save();
}
private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds)
{
m_scene.Restart(timeInSeconds);
}
private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID)
{
m_scene.RegionInfo.RegionSettings.Covenant = estateCovenantID;
m_scene.RegionInfo.RegionSettings.Save();
}
private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user)
{
// EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc.
if (user == m_scene.RegionInfo.EstateSettings.EstateOwner)
return; // never process EO
if (user == m_scene.RegionInfo.MasterAvatarAssignedUUID)
return; // never process owner
switch (estateAccessType)
{
case 64:
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions())
{
EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
break;
}
}
if (!alreadyInList)
{
EstateBan item = new EstateBan();
item.BannedUserID = user;
item.EstateID = m_scene.RegionInfo.EstateSettings.EstateID;
item.BannedHostAddress = "0.0.0.0";
item.BannedHostIPMask = "0.0.0.0";
m_scene.RegionInfo.EstateSettings.AddBan(item);
m_scene.RegionInfo.EstateSettings.Save();
ScenePresence s = m_scene.GetScenePresence(user);
if (s != null)
{
if (!s.IsChildAgent)
{
s.ControllingClient.SendTeleportLocationStart();
m_scene.TeleportClientHome(user, s.ControllingClient);
}
}
}
else
{
remote_client.SendAlertMessage("User is already on the region ban list");
}
//m_scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, m_scene.RegionInfo.EstateSettings.EstateBans, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
break;
case 128:
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false) || m_scene.Permissions.BypassPermissions())
{
EstateBan[] banlistcheck = m_scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
EstateBan listitem = null;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
listitem = banlistcheck[i];
break;
}
}
if (alreadyInList && listitem != null)
{
m_scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID);
m_scene.RegionInfo.EstateSettings.Save();
}
else
{
remote_client.SendAlertMessage("User is not on the region ban list");
}
//m_scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, m_scene.RegionInfo.EstateSettings.EstateBans, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
break;
case 256:
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.AddEstateManager(user);
m_scene.RegionInfo.EstateSettings.Save();
remote_client.SendEstateManagersList(invoice, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
break;
case 512:
if (m_scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true) || m_scene.Permissions.BypassPermissions())
{
m_scene.RegionInfo.EstateSettings.RemoveEstateManager(user);
m_scene.RegionInfo.EstateSettings.Save();
remote_client.SendEstateManagersList(invoice, m_scene.RegionInfo.EstateSettings.EstateManagers, m_scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
break;
default:
m_log.ErrorFormat("EstateOwnerMessage: Unknown EstateAccessType requested in estateAccessDelta: {0}", estateAccessType.ToString());
break;
}
}
private void SendSimulatorBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
IDialogModule dm = m_scene.RequestModuleInterface<IDialogModule>();
if (dm != null)
dm.SendNotificationToUsersInRegion(senderID, senderName, message);
}
private void SendEstateBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
IDialogModule dm = m_scene.RequestModuleInterface<IDialogModule>();
if (dm != null)
dm.SendNotificationToUsersInEstate(senderID, senderName, message);
}
private void handleEstateDebugRegionRequest(IClientAPI remote_client, UUID invoice, UUID senderID, bool scripted, bool collisionEvents, bool physics)
{
if (physics)
m_scene.RegionInfo.RegionSettings.DisablePhysics = true;
else
m_scene.RegionInfo.RegionSettings.DisablePhysics = false;
if (scripted)
m_scene.RegionInfo.RegionSettings.DisableScripts = true;
else
m_scene.RegionInfo.RegionSettings.DisableScripts = false;
if (collisionEvents)
m_scene.RegionInfo.RegionSettings.DisableCollisions = true;
else
m_scene.RegionInfo.RegionSettings.DisableCollisions = false;
m_scene.RegionInfo.RegionSettings.Save();
m_scene.SetSceneCoreDebug(scripted, collisionEvents, physics);
}
private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey)
{
if (prey != UUID.Zero)
{
ScenePresence s = m_scene.GetScenePresence(prey);
if (s != null)
{
s.ControllingClient.SendTeleportLocationStart();
m_scene.TeleportClientHome(prey, s.ControllingClient);
}
}
}
private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID)
{
// Get a fresh list that will not change as people get teleported away
List<ScenePresence> prescences = m_scene.GetScenePresences();
foreach (ScenePresence p in prescences)
{
if (p.UUID != senderID)
{
// make sure they are still there, we could be working down a long list
ScenePresence s = m_scene.GetScenePresence(p.UUID);
if (s != null)
{
// Also make sure they are actually in the region
if (!s.IsChildAgent)
{
s.ControllingClient.SendTeleportLocationStart();
m_scene.TeleportClientHome(s.UUID, s.ControllingClient);
}
}
}
}
}
private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID)
{
if (TerrainUploader != null)
{
lock (TerrainUploader)
{
if (XferID == TerrainUploader.XferID)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
remoteClient.SendAlertMessage("Terrain Upload aborted by the client");
}
}
}
}
private void HandleTerrainApplication(string filename, byte[] terrainData, IClientAPI remoteClient)
{
lock (TerrainUploader)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
}
remoteClient.SendAlertMessage("Terrain Upload Complete. Loading....");
ITerrainModule terr = m_scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName);
if (File.Exists(Util.dataDir() + "/terrain.raw"))
{
File.Delete(Util.dataDir() + "/terrain.raw");
}
try
{
FileStream input = new FileStream(Util.dataDir() + "/terrain.raw", FileMode.CreateNew);
input.Write(terrainData, 0, terrainData.Length);
input.Close();
}
catch (IOException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was an IO Exception loading your terrain. Please check free space");
return;
}
catch (SecurityException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (UnauthorizedAccessException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
try
{
terr.LoadFromFile(Util.dataDir() + "/terrain.raw");
remoteClient.SendAlertMessage("Your terrain was loaded. Give it a minute or two to apply");
}
catch (Exception e)
{
m_log.ErrorFormat("[TERRAIN]: Error loading a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a general error loading your terrain. Please fix the terrain file and try again");
}
}
else
{
remoteClient.SendAlertMessage("Unable to apply terrain. Cannot get an instance of the terrain module");
}
}
private void handleUploadTerrain(IClientAPI remote_client, string clientFileName)
{
if (TerrainUploader == null)
{
TerrainUploader = new EstateTerrainXferHandler(remote_client, clientFileName);
lock (TerrainUploader)
{
remote_client.OnXferReceive += TerrainUploader.XferReceive;
remote_client.OnAbortXfer += AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone += HandleTerrainApplication;
}
TerrainUploader.RequestStartXfer(remote_client);
}
else
{
remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!");
}
}
private void handleTerrainRequest(IClientAPI remote_client, string clientFileName)
{
// Save terrain here
ITerrainModule terr = m_scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + m_scene.RegionInfo.RegionName);
if (File.Exists(Util.dataDir() + "/terrain.raw"))
{
File.Delete(Util.dataDir() + "/terrain.raw");
}
terr.SaveToFile(Util.dataDir() + "/terrain.raw");
FileStream input = new FileStream(Util.dataDir() + "/terrain.raw", FileMode.Open);
byte[] bdata = new byte[input.Length];
input.Read(bdata, 0, (int)input.Length);
remote_client.SendAlertMessage("Terrain file written, starting download...");
m_scene.XferManager.AddNewFile("terrain.raw", bdata);
// Tell client about it
m_log.Warn("[CLIENT]: Sending Terrain to " + remote_client.Name);
remote_client.SendInitiateDownload("terrain.raw", clientFileName);
}
}
private void HandleRegionInfoRequest(IClientAPI remote_client)
{
RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs();
args.billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor;
args.estateID = m_scene.RegionInfo.EstateSettings.EstateID;
args.maxAgents = (byte)m_scene.RegionInfo.RegionSettings.AgentLimit;
args.objectBonusFactor = (float)m_scene.RegionInfo.RegionSettings.ObjectBonus;
args.parentEstateID = m_scene.RegionInfo.EstateSettings.ParentEstateID;
args.pricePerMeter = m_scene.RegionInfo.EstateSettings.PricePerMeter;
args.redirectGridX = m_scene.RegionInfo.EstateSettings.RedirectGridX;
args.redirectGridY = m_scene.RegionInfo.EstateSettings.RedirectGridY;
args.regionFlags = GetRegionFlags();
args.simAccess = m_scene.RegionInfo.AccessLevel;
args.sunHour = (float)m_scene.RegionInfo.RegionSettings.SunPosition;
args.terrainLowerLimit = (float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit;
args.terrainRaiseLimit = (float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
args.useEstateSun = m_scene.RegionInfo.RegionSettings.UseEstateSun;
args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
args.simName = m_scene.RegionInfo.RegionName;
remote_client.SendRegionInfoToEstateMenu(args);
}
private void HandleEstateCovenantRequest(IClientAPI remote_client)
{
remote_client.SendEstateCovenantInformation(m_scene.RegionInfo.RegionSettings.Covenant);
}
private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient)
{
Dictionary<uint, float> SceneData = new Dictionary<uint,float>();
List<UUID> uuidNameLookupList = new List<UUID>();
if (reportType == 1)
{
SceneData = m_scene.PhysicsScene.GetTopColliders();
}
else if (reportType == 0)
{
SceneData = m_scene.SceneGraph.GetTopScripts();
}
List<LandStatReportItem> SceneReport = new List<LandStatReportItem>();
lock (SceneData)
{
foreach (uint obj in SceneData.Keys)
{
SceneObjectPart prt = m_scene.GetSceneObjectPart(obj);
if (prt != null)
{
if (prt.ParentGroup != null)
{
SceneObjectGroup sog = prt.ParentGroup;
if (sog != null)
{
LandStatReportItem lsri = new LandStatReportItem();
lsri.LocationX = sog.AbsolutePosition.X;
lsri.LocationY = sog.AbsolutePosition.Y;
lsri.LocationZ = sog.AbsolutePosition.Z;
lsri.Score = SceneData[obj];
lsri.TaskID = sog.UUID;
lsri.TaskLocalID = sog.LocalId;
lsri.TaskName = sog.GetPartName(obj);
if (m_scene.CommsManager.UUIDNameCachedTest(sog.OwnerID))
{
lsri.OwnerName = m_scene.CommsManager.UUIDNameRequestString(sog.OwnerID);
}
else
{
lsri.OwnerName = "waiting";
lock (uuidNameLookupList)
uuidNameLookupList.Add(sog.OwnerID);
}
if (filter.Length != 0)
{
if ((lsri.OwnerName.Contains(filter) || lsri.TaskName.Contains(filter)))
{
}
else
{
continue;
}
}
SceneReport.Add(lsri);
}
}
}
}
}
remoteClient.SendLandStatReply(reportType, requestFlags, (uint)SceneReport.Count,SceneReport.ToArray());
if (uuidNameLookupList.Count > 0)
LookupUUID(uuidNameLookupList);
}
private void LookupUUIDSCompleted(IAsyncResult iar)
{
LookupUUIDS icon = (LookupUUIDS)iar.AsyncState;
icon.EndInvoke(iar);
}
private void LookupUUID(List<UUID> uuidLst)
{
LookupUUIDS d = LookupUUIDsAsync;
d.BeginInvoke(uuidLst,
LookupUUIDSCompleted,
d);
}
private void LookupUUIDsAsync(List<UUID> uuidLst)
{
UUID[] uuidarr = new UUID[0];
lock (uuidLst)
{
uuidarr = uuidLst.ToArray();
}
for (int i = 0; i < uuidarr.Length; i++)
{
// string lookupname = m_scene.CommsManager.UUIDNameRequestString(uuidarr[i]);
m_scene.CommsManager.UUIDNameRequestString(uuidarr[i]);
// we drop it. It gets cached though... so we're ready for the next request.
}
}
#endregion
#region Outgoing Packets
public void sendRegionInfoPacketToAll()
{
List<ScenePresence> avatars = m_scene.GetAvatars();
for (int i = 0; i < avatars.Count; i++)
{
HandleRegionInfoRequest(avatars[i].ControllingClient); ;
}
}
public void sendRegionHandshake(IClientAPI remoteClient)
{
RegionHandshakeArgs args = new RegionHandshakeArgs();
args.isEstateManager = m_scene.RegionInfo.EstateSettings.IsEstateManager(remoteClient.AgentId);
if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && m_scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId)
args.isEstateManager = true;
args.billableFactor = m_scene.RegionInfo.EstateSettings.BillableFactor;
args.terrainStartHeight0 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SW;
args.terrainHeightRange0 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SW;
args.terrainStartHeight1 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NW;
args.terrainHeightRange1 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NW;
args.terrainStartHeight2 = (float)m_scene.RegionInfo.RegionSettings.Elevation1SE;
args.terrainHeightRange2 = (float)m_scene.RegionInfo.RegionSettings.Elevation2SE;
args.terrainStartHeight3 = (float)m_scene.RegionInfo.RegionSettings.Elevation1NE;
args.terrainHeightRange3 = (float)m_scene.RegionInfo.RegionSettings.Elevation2NE;
args.simAccess = m_scene.RegionInfo.AccessLevel;
args.waterHeight = (float)m_scene.RegionInfo.RegionSettings.WaterHeight;
args.regionFlags = GetRegionFlags();
args.regionName = m_scene.RegionInfo.RegionName;
if (m_scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero)
args.SimOwner = m_scene.RegionInfo.EstateSettings.EstateOwner;
else
args.SimOwner = m_scene.RegionInfo.MasterAvatarAssignedUUID;
// Fudge estate owner
//if (m_scene.Permissions.IsGod(remoteClient.AgentId))
// args.SimOwner = remoteClient.AgentId;
args.terrainBase0 = UUID.Zero;
args.terrainBase1 = UUID.Zero;
args.terrainBase2 = UUID.Zero;
args.terrainBase3 = UUID.Zero;
args.terrainDetail0 = m_scene.RegionInfo.RegionSettings.TerrainTexture1;
args.terrainDetail1 = m_scene.RegionInfo.RegionSettings.TerrainTexture2;
args.terrainDetail2 = m_scene.RegionInfo.RegionSettings.TerrainTexture3;
args.terrainDetail3 = m_scene.RegionInfo.RegionSettings.TerrainTexture4;
remoteClient.SendRegionHandshake(m_scene.RegionInfo,args);
}
public void sendRegionHandshakeToAll()
{
m_scene.Broadcast(sendRegionHandshake);
}
public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2)
{
if (parms2 == 0)
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = true;
m_scene.RegionInfo.EstateSettings.SunPosition = 0.0;
}
else
{
m_scene.RegionInfo.EstateSettings.UseGlobalTime = false;
m_scene.RegionInfo.EstateSettings.SunPosition = (double)(parms2 - 0x1800)/1024.0;
}
if ((parms1 & 0x00000010) != 0)
m_scene.RegionInfo.EstateSettings.FixedSun = true;
else
m_scene.RegionInfo.EstateSettings.FixedSun = false;
if ((parms1 & 0x00008000) != 0)
m_scene.RegionInfo.EstateSettings.PublicAccess = true;
else
m_scene.RegionInfo.EstateSettings.PublicAccess = false;
if ((parms1 & 0x10000000) != 0)
m_scene.RegionInfo.EstateSettings.AllowVoice = true;
else
m_scene.RegionInfo.EstateSettings.AllowVoice = false;
if ((parms1 & 0x00100000) != 0)
m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = true;
else
m_scene.RegionInfo.EstateSettings.AllowDirectTeleport = false;
if ((parms1 & 0x00800000) != 0)
m_scene.RegionInfo.EstateSettings.DenyAnonymous = true;
else
m_scene.RegionInfo.EstateSettings.DenyAnonymous = false;
if ((parms1 & 0x01000000) != 0)
m_scene.RegionInfo.EstateSettings.DenyIdentified = true;
else
m_scene.RegionInfo.EstateSettings.DenyIdentified = false;
if ((parms1 & 0x02000000) != 0)
m_scene.RegionInfo.EstateSettings.DenyTransacted = true;
else
m_scene.RegionInfo.EstateSettings.DenyTransacted = false;
if ((parms1 & 0x40000000) != 0)
m_scene.RegionInfo.EstateSettings.DenyMinors = true;
else
m_scene.RegionInfo.EstateSettings.DenyMinors = false;
m_scene.RegionInfo.EstateSettings.Save();
TriggerEstateToolsSunUpdate();
sendDetailedEstateData(remoteClient, invoice);
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source)
{
m_scene = scene;
m_scene.RegisterModuleInterface<IEstateModule>(this);
m_scene.EventManager.OnNewClient += EventManager_OnNewClient;
m_scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight;
}
public void PostInitialise()
{
// Sets up the sun module based no the saved Estate and Region Settings
// DO NOT REMOVE or the sun will stop working
TriggerEstateToolsSunUpdate();
}
public void Close()
{
}
public string Name
{
get { return "EstateManagementModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
#region Other Functions
private void TriggerEstateToolsSunUpdate()
{
float sun;
if (m_scene.RegionInfo.RegionSettings.UseEstateSun)
{
sun = (float)m_scene.RegionInfo.EstateSettings.SunPosition;
if (m_scene.RegionInfo.EstateSettings.UseGlobalTime)
{
sun = m_scene.EventManager.GetCurrentTimeAsSunLindenHour() - 6.0f;
}
//
m_scene.EventManager.TriggerEstateToolsSunUpdate(
m_scene.RegionInfo.RegionHandle,
m_scene.RegionInfo.EstateSettings.FixedSun,
m_scene.RegionInfo.RegionSettings.UseEstateSun,
sun);
}
else
{
// Use the Sun Position from the Region Settings
sun = (float)m_scene.RegionInfo.RegionSettings.SunPosition - 6.0f;
m_scene.EventManager.TriggerEstateToolsSunUpdate(
m_scene.RegionInfo.RegionHandle,
m_scene.RegionInfo.RegionSettings.FixedSun,
m_scene.RegionInfo.RegionSettings.UseEstateSun,
sun);
}
}
public void changeWaterHeight(float height)
{
setRegionTerrainSettings(height,
(float)m_scene.RegionInfo.RegionSettings.TerrainRaiseLimit,
(float)m_scene.RegionInfo.RegionSettings.TerrainLowerLimit,
m_scene.RegionInfo.RegionSettings.UseEstateSun,
m_scene.RegionInfo.RegionSettings.FixedSun,
(float)m_scene.RegionInfo.RegionSettings.SunPosition,
m_scene.RegionInfo.EstateSettings.UseGlobalTime,
m_scene.RegionInfo.EstateSettings.FixedSun,
(float)m_scene.RegionInfo.EstateSettings.SunPosition);
sendRegionInfoPacketToAll();
}
#endregion
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnDetailedEstateDataRequest += sendDetailedEstateData;
client.OnSetEstateFlagsRequest += estateSetRegionInfoHandler;
// client.OnSetEstateTerrainBaseTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainDetailTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainTextureHeights += setEstateTerrainTextureHeights;
client.OnCommitEstateTerrainTextureRequest += handleCommitEstateTerrainTextureRequest;
client.OnSetRegionTerrainSettings += setRegionTerrainSettings;
client.OnEstateRestartSimRequest += handleEstateRestartSimRequest;
client.OnEstateChangeCovenantRequest += handleChangeEstateCovenantRequest;
client.OnEstateChangeInfo += handleEstateChangeInfo;
client.OnUpdateEstateAccessDeltaRequest += handleEstateAccessDeltaRequest;
client.OnSimulatorBlueBoxMessageRequest += SendSimulatorBlueBoxMessage;
client.OnEstateBlueBoxMessageRequest += SendEstateBlueBoxMessage;
client.OnEstateDebugRegionRequest += handleEstateDebugRegionRequest;
client.OnEstateTeleportOneUserHomeRequest += handleEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest += handleEstateTeleportAllUsersHomeRequest;
client.OnRequestTerrain += handleTerrainRequest;
client.OnUploadTerrain += handleUploadTerrain;
client.OnRegionInfoRequest += HandleRegionInfoRequest;
client.OnEstateCovenantRequest += HandleEstateCovenantRequest;
client.OnLandStatRequest += HandleLandStatRequest;
sendRegionHandshake(client);
}
public uint GetRegionFlags()
{
RegionFlags flags = RegionFlags.None;
// Fully implemented
//
if (m_scene.RegionInfo.RegionSettings.AllowDamage)
flags |= RegionFlags.AllowDamage;
if (m_scene.RegionInfo.RegionSettings.BlockTerraform)
flags |= RegionFlags.BlockTerraform;
if (!m_scene.RegionInfo.RegionSettings.AllowLandResell)
flags |= RegionFlags.BlockLandResell;
if (m_scene.RegionInfo.RegionSettings.DisableCollisions)
flags |= RegionFlags.SkipCollisions;
if (m_scene.RegionInfo.RegionSettings.DisableScripts)
flags |= RegionFlags.SkipScripts;
if (m_scene.RegionInfo.RegionSettings.DisablePhysics)
flags |= RegionFlags.SkipPhysics;
if (m_scene.RegionInfo.RegionSettings.BlockFly)
flags |= RegionFlags.NoFly;
if (m_scene.RegionInfo.RegionSettings.RestrictPushing)
flags |= RegionFlags.RestrictPushObject;
if (m_scene.RegionInfo.RegionSettings.AllowLandJoinDivide)
flags |= RegionFlags.AllowParcelChanges;
if (m_scene.RegionInfo.RegionSettings.BlockShowInSearch)
flags |= (RegionFlags)(1 << 29);
if (m_scene.RegionInfo.RegionSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (m_scene.RegionInfo.RegionSettings.Sandbox)
flags |= RegionFlags.Sandbox;
// Fudge these to always on, so the menu options activate
//
flags |= RegionFlags.AllowLandmark;
flags |= RegionFlags.AllowSetHome;
// TODO: SkipUpdateInterestList
// Omitted
//
// Omitted: NullLayer (what is that?)
// Omitted: SkipAgentAction (what does it do?)
return (uint)flags;
}
public uint GetEstateFlags()
{
RegionFlags flags = RegionFlags.None;
if (m_scene.RegionInfo.EstateSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (m_scene.RegionInfo.EstateSettings.PublicAccess)
flags |= (RegionFlags.PublicAllowed |
RegionFlags.ExternallyVisible);
if (m_scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
if (m_scene.RegionInfo.EstateSettings.AllowDirectTeleport)
flags |= RegionFlags.AllowDirectTeleport;
if (m_scene.RegionInfo.EstateSettings.DenyAnonymous)
flags |= RegionFlags.DenyAnonymous;
if (m_scene.RegionInfo.EstateSettings.DenyIdentified)
flags |= RegionFlags.DenyIdentified;
if (m_scene.RegionInfo.EstateSettings.DenyTransacted)
flags |= RegionFlags.DenyTransacted;
if (m_scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner)
flags |= RegionFlags.AbuseEmailToEstateOwner;
if (m_scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (m_scene.RegionInfo.EstateSettings.EstateSkipScripts)
flags |= RegionFlags.EstateSkipScripts;
if (m_scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
if (m_scene.RegionInfo.EstateSettings.TaxFree)
flags |= RegionFlags.TaxFree;
if (m_scene.RegionInfo.EstateSettings.DenyMinors)
flags |= (RegionFlags)(1 << 30);
return (uint)flags;
}
public bool IsManager(UUID avatarID)
{
if (avatarID == m_scene.RegionInfo.MasterAvatarAssignedUUID)
return true;
if (avatarID == m_scene.RegionInfo.EstateSettings.EstateOwner)
return true;
List<UUID> ems = new List<UUID>(m_scene.RegionInfo.EstateSettings.EstateManagers);
if (ems.Contains(avatarID))
return true;
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace System.Reflection
{
internal static class Associates
{
[Flags]
internal enum Attributes
{
ComposedOfAllVirtualMethods = 0x1,
ComposedOfAllPrivateMethods = 0x2,
ComposedOfNoPublicMembers = 0x4,
ComposedOfNoStaticMembers = 0x8,
}
internal static bool IncludeAccessor(MethodInfo associate, bool nonPublic)
{
if ((object)associate == null)
return false;
if (nonPublic)
return true;
if (associate.IsPublic)
return true;
return false;
}
private static unsafe RuntimeMethodInfo AssignAssociates(
int tkMethod,
RuntimeType declaredType,
RuntimeType reflectedType)
{
if (MetadataToken.IsNullToken(tkMethod))
return null;
Debug.Assert(declaredType != null);
Debug.Assert(reflectedType != null);
bool isInherited = declaredType != reflectedType;
IntPtr[] genericArgumentHandles = null;
int genericArgumentCount = 0;
RuntimeType[] genericArguments = declaredType.GetTypeHandleInternal().GetInstantiationInternal();
if (genericArguments != null)
{
genericArgumentCount = genericArguments.Length;
genericArgumentHandles = new IntPtr[genericArguments.Length];
for (int i = 0; i < genericArguments.Length; i++)
{
genericArgumentHandles[i] = genericArguments[i].GetTypeHandleInternal().Value;
}
}
RuntimeMethodHandleInternal associateMethodHandle = ModuleHandle.ResolveMethodHandleInternalCore(RuntimeTypeHandle.GetModule(declaredType), tkMethod, genericArgumentHandles, genericArgumentCount, null, 0);
Debug.Assert(!associateMethodHandle.IsNullHandle(), "Failed to resolve associateRecord methodDef token");
if (isInherited)
{
MethodAttributes methAttr = RuntimeMethodHandle.GetAttributes(associateMethodHandle);
// ECMA MethodSemantics: "All methods for a given Property or Event shall have the same accessibility
//(ie the MemberAccessMask subfield of their Flags row) and cannot be CompilerControlled [CLS]"
// Consequently, a property may be composed of public and private methods. If the declared type !=
// the reflected type, the private methods should not be exposed. Note that this implies that the
// identity of a property includes it's reflected type.
if ((methAttr & MethodAttributes.MemberAccessMask) == MethodAttributes.Private)
return null;
// Note this is the first time the property was encountered walking from the most derived class
// towards the base class. It would seem to follow that any associated methods would not
// be overriden -- but this is not necessarily true. A more derived class may have overriden a
// virtual method associated with a property in a base class without associating the override with
// the same or any property in the derived class.
if ((methAttr & MethodAttributes.Virtual) != 0)
{
bool declaringTypeIsClass =
(RuntimeTypeHandle.GetAttributes(declaredType) & TypeAttributes.ClassSemanticsMask) == TypeAttributes.Class;
// It makes no sense to search for a virtual override of a method declared on an interface.
if (declaringTypeIsClass)
{
int slot = RuntimeMethodHandle.GetSlot(associateMethodHandle);
// Find the override visible from the reflected type
associateMethodHandle = RuntimeTypeHandle.GetMethodAt(reflectedType, slot);
}
}
}
RuntimeMethodInfo associateMethod =
RuntimeType.GetMethodBase(reflectedType, associateMethodHandle) as RuntimeMethodInfo;
// suppose a property was mapped to a method not in the derivation hierarchy of the reflectedTypeHandle
if (associateMethod == null)
associateMethod = reflectedType.Module.ResolveMethod(tkMethod, null, null) as RuntimeMethodInfo;
return associateMethod;
}
internal static unsafe void AssignAssociates(
MetadataImport scope,
int mdPropEvent,
RuntimeType declaringType,
RuntimeType reflectedType,
out RuntimeMethodInfo addOn,
out RuntimeMethodInfo removeOn,
out RuntimeMethodInfo fireOn,
out RuntimeMethodInfo getter,
out RuntimeMethodInfo setter,
out MethodInfo[] other,
out bool composedOfAllPrivateMethods,
out BindingFlags bindingFlags)
{
addOn = removeOn = fireOn = getter = setter = null;
Attributes attributes =
Attributes.ComposedOfAllPrivateMethods |
Attributes.ComposedOfAllVirtualMethods |
Attributes.ComposedOfNoPublicMembers |
Attributes.ComposedOfNoStaticMembers;
while (RuntimeTypeHandle.IsGenericVariable(reflectedType))
reflectedType = (RuntimeType)reflectedType.BaseType;
bool isInherited = declaringType != reflectedType;
List<MethodInfo> otherList = null;
MetadataEnumResult associatesData;
scope.Enum(MetadataTokenType.MethodDef, mdPropEvent, out associatesData);
int cAssociates = associatesData.Length / 2;
for (int i = 0; i < cAssociates; i++)
{
int methodDefToken = associatesData[i * 2];
MethodSemanticsAttributes semantics = (MethodSemanticsAttributes)associatesData[i * 2 + 1];
#region Assign each associate
RuntimeMethodInfo associateMethod =
AssignAssociates(methodDefToken, declaringType, reflectedType);
if (associateMethod == null)
continue;
MethodAttributes methAttr = associateMethod.Attributes;
bool isPrivate = (methAttr & MethodAttributes.MemberAccessMask) == MethodAttributes.Private;
bool isVirtual = (methAttr & MethodAttributes.Virtual) != 0;
MethodAttributes visibility = methAttr & MethodAttributes.MemberAccessMask;
bool isPublic = visibility == MethodAttributes.Public;
bool isStatic = (methAttr & MethodAttributes.Static) != 0;
if (isPublic)
{
attributes &= ~Attributes.ComposedOfNoPublicMembers;
attributes &= ~Attributes.ComposedOfAllPrivateMethods;
}
else if (!isPrivate)
{
attributes &= ~Attributes.ComposedOfAllPrivateMethods;
}
if (isStatic)
attributes &= ~Attributes.ComposedOfNoStaticMembers;
if (!isVirtual)
attributes &= ~Attributes.ComposedOfAllVirtualMethods;
#endregion
if (semantics == MethodSemanticsAttributes.Setter)
setter = associateMethod;
else if (semantics == MethodSemanticsAttributes.Getter)
getter = associateMethod;
else if (semantics == MethodSemanticsAttributes.Fire)
fireOn = associateMethod;
else if (semantics == MethodSemanticsAttributes.AddOn)
addOn = associateMethod;
else if (semantics == MethodSemanticsAttributes.RemoveOn)
removeOn = associateMethod;
else
{
if (otherList == null)
otherList = new List<MethodInfo>(cAssociates);
otherList.Add(associateMethod);
}
}
bool isPseudoPublic = (attributes & Attributes.ComposedOfNoPublicMembers) == 0;
bool isPseudoStatic = (attributes & Attributes.ComposedOfNoStaticMembers) == 0;
bindingFlags = RuntimeType.FilterPreCalculate(isPseudoPublic, isInherited, isPseudoStatic);
composedOfAllPrivateMethods = (attributes & Attributes.ComposedOfAllPrivateMethods) != 0;
other = (otherList != null) ? otherList.ToArray() : null;
}
}
}
| |
using OpenKh.Common;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace OpenKh.Kh2
{
public class Msg
{
private static uint MagicCode = 1;
private static byte Terminator = 0;
public static ushort FallbackMessage = 2780;
public class Entry
{
public int Id { get; set; }
public byte[] Data { get; set; }
}
internal class OptimizedEntry
{
public int Id { get; }
public byte[] Data { get; }
public int Offset { get; set; }
public int LinkId { get; private set; }
public int LinkOffset { get; private set; }
public bool HasbeenLinked { get; private set; }
public bool IsLinked => LinkId >= 0;
public OptimizedEntry(Entry entry)
{
Id = entry.Id;
Data = entry.Data;
Offset = -1;
LinkId = -1;
LinkOffset = -1;
HasbeenLinked = false;
}
public void LinkTo(OptimizedEntry entry, int offset)
{
LinkId = entry.Id;
LinkOffset = offset;
entry.HasbeenLinked = true;
}
}
public static List<Entry> Read(Stream stream)
{
if (!stream.CanRead || !stream.CanSeek)
throw new InvalidDataException($"Read or seek must be supported.");
var reader = new BinaryReader(stream);
if (stream.Length < 8L || reader.ReadUInt32() != MagicCode)
throw new InvalidDataException("Invalid header");
int entriesCount = reader.ReadInt32();
return Enumerable.Range(0, entriesCount)
.Select(x => new
{
Id = reader.ReadInt32(),
Offset = reader.ReadInt32(),
})
.ToList()
.Select(x =>
{
reader.BaseStream.Position = x.Offset;
return new Entry
{
Id = x.Id,
Data = GetMsgData(reader)
};
})
.ToList();
}
public static void Write(Stream stream, List<Entry> entries)
{
if (!stream.CanWrite || !stream.CanSeek)
throw new InvalidDataException($"Write or seek must be supported.");
var writer = new BinaryWriter(stream);
writer.Write(MagicCode);
writer.Write(entries.Count);
var offset = 8 + entries.Count * 8;
var orderedEntries = entries.OrderBy(x => x.Id).ToList();
foreach (var entry in orderedEntries)
{
writer.Write(entry.Id);
writer.Write(offset);
offset += entry.Data.Length;
}
foreach (var entry in orderedEntries)
{
writer.Write(entry.Data);
}
}
public static void WriteOptimized(Stream stream, List<Entry> entries)
{
if (!stream.CanWrite || !stream.CanSeek)
throw new InvalidDataException($"Write or seek must be supported.");
var writer = new BinaryWriter(stream);
writer.Write(MagicCode);
writer.Write(entries.Count);
var optimizedEntries = entries.OrderBy(x => x.Id).Select(x => new OptimizedEntry(x)).ToList();
foreach (var entry in optimizedEntries)
{
if (entry.HasbeenLinked)
continue;
foreach (var x in optimizedEntries)
{
if (entry == x || x.IsLinked)
continue;
var indexFound = IndexOf(x.Data, entry.Data);
if (indexFound >= 0)
{
entry.LinkTo(x, indexFound);
break;
}
}
}
var offset = 8 + entries.Count * 8;
foreach (var entry in optimizedEntries)
{
if (entry.LinkId < 0)
{
entry.Offset = offset;
offset += entry.Data.Length;
}
}
foreach (var entry in optimizedEntries)
{
writer.Write(entry.Id);
if (entry.IsLinked)
{
var msgLink = optimizedEntries.Find(x => x.Id == entry.LinkId);
writer.Write(msgLink.Offset + entry.LinkOffset);
}
else
writer.Write(entry.Offset);
}
foreach (var entry in optimizedEntries)
{
if (!entry.IsLinked)
writer.Write(entry.Data);
}
}
private static int IndexOf(byte[] data, byte[] pattern)
{
var c = data.Length - pattern.Length + 1;
for (var i = 0; i < c; i++)
{
if (data[i] != pattern[0])
continue;
int j;
for (j = pattern.Length - 1; j >= 1 && data[i + j] == pattern[j]; j--) ;
if (j == 0) return i;
}
return -1;
}
private static byte[] GetMsgData(BinaryReader stream)
{
byte r;
var data = new List<byte>();
do
{
r = stream.ReadByte();
data.Add(r);
switch (r)
{
case 0x04:
case 0x06:
case 0x09:
case 0x0a:
case 0x0b:
case 0x0c:
case 0x0e:
case 0x16:
case 0x19:
case 0x1a:
case 0x1b:
case 0x1c:
case 0x1d:
case 0x1e:
case 0x1f:
data.Add(stream.ReadByte());
break;
case 0x12:
case 0x14:
case 0x15:
case 0x18:
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
break;
case 0x08:
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
break;
case 0x07:
case 0x11:
case 0x13:
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
break;
case 0x0f:
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
break;
case 0x05:
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
data.Add(stream.ReadByte());
break;
}
} while (r != Terminator);
return data.ToArray();
}
public static bool IsValid(Stream stream) =>
stream.Length >= 4 && stream.PeekUInt32() == MagicCode;
}
}
| |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace BuildIt
{
/// <summary>
/// General helper methods.
/// </summary>
public static partial class Utilities
{
private static DateTime Epoch => new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Decodes a string to an entity.
/// </summary>
/// <typeparam name="T">The type to deserialise to.</typeparam>
/// <param name="jsonString">The string to deserialise.</param>
/// <returns>The deserialised entity.</returns>
public static T DecodeJson<T>(this string jsonString)
{
try
{
return JsonConvert.DeserializeObject<T>(jsonString);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return default(T);
}
}
/// <summary>
/// Decodes json string to an entity.
/// </summary>
/// <param name="jsonString">The string to deserialize.</param>
/// <param name="jsonType">The type of the entity to deserialize to.</param>
/// <returns>The deserialized entity.</returns>
public static object DecodeJson(this string jsonString, Type jsonType)
{
try
{
return JsonConvert.DeserializeObject(jsonString, jsonType);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
/// <summary>
/// Serialize entity to json string.
/// </summary>
/// <typeparam name="T">The type of entity to serialize.</typeparam>
/// <param name="objectToJsonify">The entity to serialize.</param>
/// <returns>The serialized string.</returns>
public static string EncodeJson<T>(this T objectToJsonify)
{
// ReSharper disable CompareNonConstrainedGenericWithNull
return objectToJsonify == null ? null : JsonConvert.SerializeObject(objectToJsonify);
// ReSharper restore CompareNonConstrainedGenericWithNull
}
/// <summary>
/// Iterate through collection and perform action on each item.
/// </summary>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="source">The collection of items.</param>
/// <param name="action">The action to perform.</param>
/// <returns>Successful execution.</returns>
public static bool DoForEach<T>(this IEnumerable<T> source, Action<T> action)
{
if (source == null || action == null)
{
return false;
}
foreach (var item in source)
{
action(item);
}
return true;
}
/// <summary>
/// Iterate through collection and perform async action on each item.
/// </summary>
/// <typeparam name="T">The type of items in the collection.</typeparam>
/// <param name="source">The collection of items.</param>
/// <param name="action">The action to perform.</param>
/// <returns>Successful execution.</returns>
public static async Task<bool> DoForEachAsync<T>(this IEnumerable<T> source, Func<T, Task> action)
{
if (source == null || action == null)
{
return false;
}
foreach (var item in source)
{
await action(item);
}
return true;
}
/// <summary>
/// Iterates over a collection and adds items to another collection.
/// </summary>
/// <typeparam name="TList">The type of list to add items.</typeparam>
/// <typeparam name="T">The type of items in both lists.</typeparam>
/// <param name="source">The list to add items to.</param>
/// <param name="items">The list of items to add.</param>
/// <returns>The combined list.</returns>
public static TList Fill<TList, T>(this TList source, IEnumerable<T> items)
where TList : IList<T>
{
if (source == null || items == null)
{
return source;
}
foreach (var item in items)
{
source.Add(item);
}
return source;
}
/// <summary>
/// Replace all items in an existing list.
/// </summary>
/// <typeparam name="TList">The type of the list to replace items.</typeparam>
/// <typeparam name="T">The type of items in both lists.</typeparam>
/// <param name="source">The list to replace items in.</param>
/// <param name="newItems">The list of items to add into the existing list.</param>
/// <returns>The final list.</returns>
public static TList Replace<TList, T>(this TList source, IEnumerable<T> newItems)
where TList : IList<T>
{
if (source == null || newItems == null)
{
return source;
}
source.Clear();
source.Fill(newItems);
return source;
}
/// <summary>
/// Append comma if length>0.
/// </summary>
/// <param name="sb">The string builder to modify.</param>
/// <returns>The modified string builder.</returns>
public static StringBuilder AppendCommaIfNeeded(this StringBuilder sb)
{
if (sb != null && sb.Length > 0)
{
sb.Append(",");
}
return sb;
}
/// <summary>
/// Append text if predicate/condition is true.
/// </summary>
/// <param name="sb">The strinbuilder to add to.</param>
/// <param name="condition">The condition to invoke.</param>
/// <param name="toAppend">The text to add.</param>
/// <returns>The modified stringbuilder.</returns>
public static StringBuilder AppendOnCondition(this StringBuilder sb, Func<bool> condition, string toAppend)
{
if (sb != null && condition != null && condition())
{
sb.Append(toAppend);
}
return sb;
}
/// <summary>
/// Append text if the stringbuilder if the text isn't null/empty.
/// </summary>
/// <param name="sb">The stringbuilder to modify.</param>
/// <param name="toAppend">The text to add (if not null/empty).</param>
/// <returns>The modified stringbuilder.</returns>
public static StringBuilder AppendIfNotNullOrEmpty(this StringBuilder sb, string toAppend)
{
if (sb != null && !string.IsNullOrEmpty(toAppend))
{
sb.Append(toAppend);
}
return sb;
}
/// <summary>
/// Raises an event without throwing exception if not handlers.
/// </summary>
/// <typeparam name="TParameter1">The type of the first parameter.</typeparam>
/// <param name="handler">The event to raise.</param>
/// <param name="sender">The sender entity.</param>
/// <param name="args">The first parameter.</param>
public static void SafeRaise<TParameter1>(this EventHandler<ParameterEventArgs<TParameter1>> handler, object sender, TParameter1 args)
{
handler.SafeRaise(sender, new ParameterEventArgs<TParameter1>(args));
}
/// <summary>
/// Raises an event without throwing exception if not handlers.
/// </summary>
/// <typeparam name="TParameter1">The type of the first parameter.</typeparam>
/// <typeparam name="TParameter2">The type of the second parameter.</typeparam>
/// <param name="handler">The event to raise.</param>
/// <param name="sender">The sender entity.</param>
/// <param name="arg1">The first parameter.</param>
/// <param name="arg2">The second parameter.</param>
public static void SafeRaise<TParameter1, TParameter2>(this EventHandler<DualParameterEventArgs<TParameter1, TParameter2>> handler, object sender, TParameter1 arg1, TParameter2 arg2)
{
handler.SafeRaise(sender, new DualParameterEventArgs<TParameter1, TParameter2>(arg1, arg2));
}
/// <summary>
/// Raises an event without throwing exception if not handlers.
/// </summary>
/// <typeparam name="TParameter1">The type of the first parameter.</typeparam>
/// <typeparam name="TParameter2">The type of the second parameter.</typeparam>
/// <typeparam name="TParameter3">The type of the third parameter.</typeparam>
/// <param name="handler">The event to raise.</param>
/// <param name="sender">The sender entity.</param>
/// <param name="arg1">The first parameter.</param>
/// <param name="arg2">The second parameter.</param>
/// <param name="arg3">The third parameter.</param>
public static void SafeRaise<TParameter1, TParameter2, TParameter3>(this EventHandler<TripleParameterEventArgs<TParameter1, TParameter2, TParameter3>> handler, object sender, TParameter1 arg1, TParameter2 arg2, TParameter3 arg3)
{
handler.SafeRaise(sender, new TripleParameterEventArgs<TParameter1, TParameter2, TParameter3>(arg1, arg2, arg3));
}
/// <summary>
/// Raises an event without throwing exception if not handlers.
/// </summary>
/// <param name="handler">The event to raise.</param>
/// <param name="sender">The sender entity.</param>
/// <param name="args">The parameters.</param>
public static void SafeRaise(this EventHandler handler, object sender, EventArgs args = null)
{
if (args == null)
{
args = EventArgs.Empty;
}
handler?.Invoke(sender, args);
}
/// <summary>
/// Raises an event without throwing exception if not handlers.
/// </summary>
/// <typeparam name="T">The type of the first parameter.</typeparam>
/// <param name="handler">The event to raise.</param>
/// <param name="sender">The sender entity.</param>
/// <param name="args">The parameter.</param>
public static void SafeRaise<T>(this EventHandler<T> handler, object sender, T args)
where T : EventArgs
{
handler?.Invoke(sender, args);
}
/// <summary>
/// Safetly retrieves a value from the dictionary. No exception thrown if key is null, or doesn't exist in dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <typeparam name="TReturn">The type to be returned.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key to lookup.</param>
/// <returns>The value, or null.</returns>
public static TReturn SafeValue<TKey, TValue, TReturn>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
if (dictionary == null || key == null)
{
return default(TReturn);
}
TValue val;
if (dictionary.TryGetValue(key, out val))
{
if (val is TReturn)
{
return (TReturn)(object)val;
}
}
return default(TReturn);
}
/// <summary>
/// Safetly retrieves a value from the dictionary. No exception thrown if key is null, or doesn't exist in dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key to lookup.</param>
/// <returns>The value, or null.</returns>
public static TValue SafeValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TKey key)
{
if (dictionary == null || key == null)
{
return default(TValue);
}
return dictionary.TryGetValue(key, out var val) ? val : default(TValue);
}
/// <summary>
/// Safetly retrieves a value from the dictionary. No exception thrown if key is null, or doesn't exist in dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="dictionary">The dictionary.</param>
/// <param name="key">The key to lookup.</param>
/// <returns>The value, or null.</returns>
public static TValue SafeValue<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dictionary, TKey key)
{
if (dictionary == null || key == null)
{
return default(TValue);
}
TValue val;
return dictionary.TryGetValue(key, out val) ? val : default(TValue);
}
/// <summary>
/// Does an action if both the item and the action are not null.
/// </summary>
/// <typeparam name="T">The type of the entity to pass into the action.</typeparam>
/// <param name="item">The entity to pass into the action.</param>
/// <param name="action">The action.</param>
/// <returns>Successfully called action.</returns>
public static bool DoIfNotNull<T>(this T item, Action<T> action)
where T : class
{
if (item == null || action == null)
{
return false;
}
action(item);
return true;
}
/// <summary>
/// Does an action if both the item and the action are not null.
/// </summary>
/// <param name="instance">The entity to pass into the action.</param>
/// <param name="method">The action.</param>
/// <returns>Successfully called action.</returns>
public static bool ExecuteIfNotNull(this object instance, Action method)
{
if (instance == null || method == null)
{
return false;
}
method();
return true;
}
/// <summary>
/// Parses a string into an enum value.
/// </summary>
/// <typeparam name="T">The enum type.</typeparam>
/// <param name="enumValue">The string to parse.</param>
/// <param name="ignoreCase">Whether to ignore case.</param>
/// <returns>The enum value, or the default (first) enum value.</returns>
public static T EnumParse<T>(this string enumValue, bool ignoreCase = true)
where T : struct
{
try
{
if (string.IsNullOrEmpty(enumValue))
{
return default(T);
}
return (T)Enum.Parse(typeof(T), enumValue, ignoreCase);
}
catch
{
return default(T);
}
}
/// <summary>
/// Converts a string to a double, or returns the default value.
/// </summary>
/// <param name="doubleValue">The string to parse.</param>
/// <param name="defaultValue">The default value to return if string doesn't parse.</param>
/// <returns>The parsed (or default) value.</returns>
public static double ToDouble(this string doubleValue, double defaultValue = 0.0)
{
if (string.IsNullOrWhiteSpace(doubleValue))
{
return defaultValue;
}
return double.TryParse(doubleValue, out double retValue) ? retValue : defaultValue;
}
/// <summary>
/// Converts a string to a date.
/// </summary>
/// <param name="doubleValue">The string to parse.</param>
/// <returns>The parsed value.</returns>
public static DateTime ToDate(this string doubleValue)
{
if (string.IsNullOrWhiteSpace(doubleValue))
{
return DateTime.Now;
}
return DateTime.TryParse(doubleValue, out DateTime retValue) ? retValue : DateTime.Now;
}
/// <summary>
/// Converts a string to a int, or returns the default value.
/// </summary>
/// <param name="intValue">The string to parse.</param>
/// <param name="defaultValue">The default value to return if string doesn't parse.</param>
/// <returns>The parsed (or default) value.</returns>
public static int ToInt(this string intValue, int defaultValue = 0)
{
if (string.IsNullOrWhiteSpace(intValue))
{
return defaultValue;
}
int retValue;
if (int.TryParse(intValue, out retValue))
{
return retValue;
}
return defaultValue;
}
/// <summary>
/// Reads an object from a stream into an entity (assumes json string).
/// </summary>
/// <typeparam name="T">The type of entity to read out.</typeparam>
/// <param name="stream">The stream to read from.</param>
/// <returns>The entity read from the stream.</returns>
public static T ReadObject<T>(this Stream stream)
{
try
{
using (var reader = new StreamReader(stream))
using (var jreader = new JsonTextReader(reader))
{
#if DEBUG
var txt = reader.ReadToEnd();
Debug.WriteLine(txt);
stream.Position = 0;
#endif
return JsonSerializer.CreateDefault().Deserialize<T>(jreader);
}
}
catch (Exception ex)
{
Debug.WriteLine("Unable to read object from json stream - " + ex.Message);
return default(T);
}
}
/// <summary>
/// Converts a date time to a friendly string.
/// </summary>
/// <param name="date">The date to convert.</param>
/// <returns>The pretty date string.</returns>
public static string FriendlyDateFormat(this DateTime date)
{
if (date == DateTime.MinValue || date == DateTime.MaxValue)
{
return " ";
}
var days = date.Date.Subtract(DateTime.Now.Date).TotalDays;
if (days < -365 * 2)
{
return (-(int)days / 365) + " years ago";
}
if (days < -365)
{
return "Last year";
}
if (days < -31)
{
return ((int)(-days / 31)) + " months ago";
}
if (days < -14)
{
return ((int)(-days / 7)) + " weeks ago";
}
if (days < -7)
{
return "Last week";
}
if (days < -1)
{
return (-days) + " days ago";
}
if (date.Date < DateTime.Now.Date)
{
return "Yesterday";
}
if (days > 365 * 2)
{
return ((int)days / 365) + " years";
}
if (days > 365)
{
return "Next year";
}
if (days > 31)
{
return ((int)(days / 31)) + " months";
}
if (days > 14)
{
return ((int)(days / 7)) + " weeks";
}
if (days > 7)
{
return "Next week";
}
if (days > 1)
{
return days + " days";
}
if (date.Date > DateTime.Now.Date)
{
return "Tomorrow";
}
return date.ToString(); // .ToShortTimeString();
}
/// <summary>
/// Combines two dictionaries into a new dictionary - doesn't replace items in first dictionary.
/// </summary>
/// <typeparam name="TKey">The type of the keys.</typeparam>
/// <typeparam name="TValue">The type of the values.</typeparam>
/// <param name="first">The original dictionary.</param>
/// <param name="second">The dictionary with additionalvalues.</param>
/// <returns>Returns a new dictionary.</returns>
public static IDictionary<TKey, TValue> Combine<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
{
first = first ?? new Dictionary<TKey, TValue>();
second = second ?? new Dictionary<TKey, TValue>();
var dictionary = second.ToDictionary(current => current.Key, current => current.Value);
foreach (var current in first)
{
if (!dictionary.ContainsKey(current.Key))
{
dictionary.Add(current.Key, current.Value);
}
}
return dictionary;
}
/// <summary>
/// Serializes an entity into query string.
/// </summary>
/// <typeparam name="T">The type of entity to serialize.</typeparam>
/// <param name="obj">The entity to serialize.</param>
/// <param name="applyLowerCaseFirstChar">Whether the first letter of each parameter should be lower case.</param>
/// <param name="applyUrlEncoding">Encodes each parameter.</param>
/// <returns>The query string.</returns>
public static string ToQueryString<T>(T obj, bool applyLowerCaseFirstChar = true, bool applyUrlEncoding = true)
{
var queryString = string.Empty;
var properties = typeof(T).GetTypeInfo().DeclaredProperties.OrderBy(p => p.Name).ToList();
foreach (var property in properties)
{
var propertyValue = property.GetValue(obj);
if (propertyValue == null)
{
continue;
}
var propertyStringValue = propertyValue.ToString();
if (propertyValue is string)
{
if (string.IsNullOrWhiteSpace(propertyStringValue))
{
continue;
}
if (applyUrlEncoding)
{
propertyStringValue = WebUtility.UrlEncode(propertyStringValue);
}
}
var propertyName = property.Name;
if (applyLowerCaseFirstChar)
{
propertyName = $"{char.ToLowerInvariant(propertyName[0])}{propertyName.Substring(1)}";
}
queryString = $"{queryString}{(!string.IsNullOrWhiteSpace(queryString) ? "&" : string.Empty)}{propertyName}={propertyStringValue}";
}
return queryString;
}
/// <summary>
/// Converst a string value (ticks from Epoch) to a date time.
/// </summary>
/// <param name="unixTime">Ticks from Epoch.</param>
/// <returns>The date time.</returns>
public static DateTime ConvertToDateTimeFromUnixTimestamp(this string unixTime)
{
double parsedTime;
DateTime result;
result = Epoch.AddSeconds(!double.TryParse(unixTime, out parsedTime) ? 0.0 : parsedTime);
return result;
}
}
}
| |
//
// Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net>
// Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using Sooda.CodeGen;
using System;
using System.IO;
namespace SoodaStubGen
{
public class EntryPoint
{
static int Usage()
{
Console.WriteLine("Usage:");
Console.WriteLine("SoodaStubGen FILE.soodaproject");
Console.WriteLine("or:");
Console.WriteLine("SoodaStubGen [OPTIONS] --schema FILE.xml --namespace NAME --output DIR");
Console.WriteLine();
Console.WriteLine(" --lang csharp - (default) generate C# code");
#if !NO_VB
Console.WriteLine(" --lang vb - generate VB.NET code");
#endif
#if !NO_JSCRIPT
Console.WriteLine(" --lang js - generate JS.NET code (broken)");
#endif
Console.WriteLine(" --lang TYPE - generate code using the specified CodeDOM codeProvider");
Console.WriteLine();
Console.WriteLine(" --project vs2005 - (default) generate VS 2005 project file (.??proj)");
Console.WriteLine(" --project null - generate no project file");
Console.WriteLine(" --project TYPE - generate project file using custom type");
Console.WriteLine();
Console.WriteLine(" --schema FILE.xml - generate code from the specified schema");
Console.WriteLine(" --namespace NAME - specify the namespace to use");
Console.WriteLine(" --output DIR - specify the output directory for files");
Console.WriteLine(" --assembly NAME - specify the name of resulting assembly");
Console.WriteLine(" --base-class NAME - specify the name of stub base class (SoodaObject)");
Console.WriteLine(" --rebuild-if-changed - rebuild only if source files newer than targets");
Console.WriteLine(" --force-rebuild - rebuild always");
Console.WriteLine(" --rewrite-skeletons - force overwrite of skeleton classes");
Console.WriteLine(" --rewrite-project - force overwrite of project file");
Console.WriteLine(" --separate-stubs - enable separate compilation of stubs");
Console.WriteLine(" --merged-stubs - disable separate compilation of stubs");
Console.WriteLine(" --schema-embed-xml - embed schema as an XML file");
Console.WriteLine(" --schema-embed-bin - embed schema as an BIN file");
Console.WriteLine(" --help - display this help");
Console.WriteLine();
Console.WriteLine(" --null-progagation - enable null propagation");
Console.WriteLine(" --no-null-progagation - disable null propagation (default)");
Console.WriteLine(" --nullable-as [boxed | sqltype | raw | nullable ] (default = boxed)");
Console.WriteLine(" --not-null-as [boxed | sqltype | raw | nullable ] (default = raw)");
Console.WriteLine(" - specify the way primitive values are handled");
Console.WriteLine(" --no-typed-queries - disable Typed Queries");
Console.WriteLine(" --no-soql - disable SOQL queries");
Console.WriteLine();
return 1;
}
public static int Main(string[] args)
{
try
{
Sooda.CodeGen.SoodaProject project = new SoodaProject();
Sooda.CodeGen.CodeGenerator generator = new CodeGenerator(project, new ConsoleCodeGeneratorOutput());
string writeProjectTo = null;
for (int i = 0; i < args.Length; ++i)
{
switch (args[i])
{
case "/?":
case "-?":
case "--help":
case "-h":
return Usage();
// generator options (this run only)
case "--rebuild-if-changed":
generator.RebuildIfChanged = true;
break;
case "--force-rebuild":
generator.RebuildIfChanged = false;
break;
case "-l":
case "--lang":
project.Language = args[++i];
break;
case "-p":
case "--project":
string projectType = args[++i];
ExternalProjectInfo projectInfo = new ExternalProjectInfo(projectType);
project.ExternalProjects.Add(projectInfo);
break;
case "--separate-stubs":
project.SeparateStubs = true;
break;
case "--merged-stubs":
project.SeparateStubs = false;
break;
case "--schema-embed-xml":
project.EmbedSchema = EmbedSchema.Xml;
break;
case "--schema-embed-bin":
project.EmbedSchema = EmbedSchema.Binary;
break;
case "--nullable-as":
project.NullableRepresentation = (PrimitiveRepresentation)Enum.Parse(typeof(PrimitiveRepresentation), args[++i], true);
break;
case "--not-null-as":
project.NotNullRepresentation = (PrimitiveRepresentation)Enum.Parse(typeof(PrimitiveRepresentation), args[++i], true);
break;
case "-s":
case "--schema":
project.SchemaFile = args[++i];
break;
case "-a":
case "--assembly-name":
project.AssemblyName = args[++i];
break;
case "-bc":
case "--base-class":
project.BaseClassName = args[++i];
break;
case "--null-propagation":
project.NullPropagation = true;
break;
case "--no-null-propagation":
project.NullPropagation = false;
break;
case "--no-typed-queries":
project.WithTypedQueryWrappers = false;
break;
case "--no-soql":
project.WithSoql = false;
break;
case "--rewrite-skeletons":
generator.RewriteSkeletons = true;
break;
case "--rewrite-projects":
case "--rewrite-project":
generator.RewriteProjects = true;
break;
case "-n":
case "-ns":
case "--namespace":
project.OutputNamespace = args[++i];
break;
case "-o":
case "-out":
case "--output":
project.OutputPath = args[++i];
break;
case "--write-project":
writeProjectTo = args[++i];
break;
default:
if (args[i].EndsWith(".soodaproject"))
{
string fullPath = Path.GetFullPath(args[i]);
Console.WriteLine("Loading project from file '{0}'...", fullPath);
Environment.CurrentDirectory = Path.GetDirectoryName(fullPath);
generator.Project = SoodaProject.LoadFrom(fullPath);
//XmlSerializer ser = new XmlSerializer(typeof(SoodaProject));
//ser.Serialize(Console.Out, project);
//Console.WriteLine("OUT: {0}", project.OutputPath);
}
else
{
Console.WriteLine("Unknown option '{0}'", args[i]);
return Usage();
}
break;
}
};
if (writeProjectTo != null)
{
project.WriteTo(writeProjectTo);
}
generator.Run();
return 0;
}
catch (SoodaCodeGenException ex)
{
Console.WriteLine("ERROR: " + ex.Message);
if (ex.InnerException != null)
Console.WriteLine(ex.InnerException);
return 1;
}
catch (Exception ex)
{
Console.WriteLine("ERROR: " + ex);
return 1;
}
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.SecurityTokenService;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace StockRequestRERWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
SecondaryClientSecret,
authorizationCode,
redirectUri,
resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, SecondaryClientSecret, refreshToken, resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, SecondaryClientSecret, resource);
oauth2Request.Resource = resource;
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an add-in event
/// </summary>
/// <param name="properties">Properties of an add-in event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted add-in. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust add-in.
/// </summary>
/// <returns>True if this is a high trust add-in.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted add-in configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
/**
* Couchbase Lite for .NET
*
* Original iOS version by Jens Alfke
* Android Port by Marty Schoch, Traun Leyden
* C# Port by Zack Gramana
*
* Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved.
* Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Apache.Http.Client;
using Apache.Http.Entity.Mime;
using Apache.Http.Entity.Mime.Content;
using Couchbase.Lite;
using Couchbase.Lite.Internal;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Support;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Replicator
{
/// <exclude></exclude>
public sealed class Pusher : Replication, Database.ChangeListener
{
private bool createTarget;
private bool creatingTarget;
private bool observing;
private ReplicationFilter filter;
/// <summary>Constructor</summary>
[InterfaceAudience.Private]
public Pusher(Database db, Uri remote, bool continuous, ScheduledExecutorService
workExecutor) : this(db, remote, continuous, null, workExecutor)
{
}
/// <summary>Constructor</summary>
[InterfaceAudience.Private]
public Pusher(Database db, Uri remote, bool continuous, HttpClientFactory clientFactory
, ScheduledExecutorService workExecutor) : base(db, remote, continuous, clientFactory
, workExecutor)
{
createTarget = false;
observing = false;
}
[InterfaceAudience.Public]
public override bool IsPull()
{
return false;
}
[InterfaceAudience.Public]
public override bool ShouldCreateTarget()
{
return createTarget;
}
[InterfaceAudience.Public]
public override void SetCreateTarget(bool createTarget)
{
this.createTarget = createTarget;
}
[InterfaceAudience.Public]
public override void Stop()
{
StopObserving();
base.Stop();
}
[InterfaceAudience.Private]
internal override void MaybeCreateRemoteDB()
{
if (!createTarget)
{
return;
}
creatingTarget = true;
Log.V(Database.Tag, "Remote db might not exist; creating it...");
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": maybeCreateRemoteDB() calling asyncTaskStarted()"
);
AsyncTaskStarted();
SendAsyncRequest("PUT", string.Empty, null, new _RemoteRequestCompletionBlock_100
(this));
}
private sealed class _RemoteRequestCompletionBlock_100 : RemoteRequestCompletionBlock
{
public _RemoteRequestCompletionBlock_100(Pusher _enclosing)
{
this._enclosing = _enclosing;
}
public void OnCompletion(object result, Exception e)
{
try
{
this._enclosing.creatingTarget = false;
if (e != null && e is HttpResponseException && ((HttpResponseException)e).GetStatusCode
() != 412)
{
Log.E(Database.Tag, this + ": Failed to create remote db", e);
this._enclosing.SetError(e);
this._enclosing.Stop();
}
else
{
// this is fatal: no db to push to!
Log.V(Database.Tag, this + ": Created remote db");
this._enclosing.createTarget = false;
this._enclosing.BeginReplicating();
}
}
finally
{
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": maybeCreateRemoteDB.onComplete() calling asyncTaskFinished()"
);
this._enclosing.AsyncTaskFinished(1);
}
}
private readonly Pusher _enclosing;
}
[InterfaceAudience.Private]
public override void BeginReplicating()
{
// If we're still waiting to create the remote db, do nothing now. (This method will be
// re-invoked after that request finishes; see maybeCreateRemoteDB() above.)
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": beginReplicating() called"
);
if (creatingTarget)
{
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": creatingTarget == true, doing nothing"
);
return;
}
else
{
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": creatingTarget != true, continuing"
);
}
if (filterName != null)
{
filter = db.GetFilter(filterName);
}
if (filterName != null && filter == null)
{
Log.W(Database.Tag, string.Format("%s: No ReplicationFilter registered for filter '%s'; ignoring"
, this, filterName));
}
// Process existing changes since the last push:
long lastSequenceLong = 0;
if (lastSequence != null)
{
lastSequenceLong = long.Parse(lastSequence);
}
ChangesOptions options = new ChangesOptions();
options.SetIncludeConflicts(true);
RevisionList changes = db.ChangesSince(lastSequenceLong, options, filter);
if (changes.Count > 0)
{
batcher.QueueObjects(changes);
batcher.Flush();
}
// Now listen for future changes (in continuous mode):
if (continuous)
{
observing = true;
db.AddChangeListener(this);
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": pusher.beginReplicating() calling asyncTaskStarted()"
);
AsyncTaskStarted();
}
}
// prevents stopped() from being called when other tasks finish
[InterfaceAudience.Private]
private void StopObserving()
{
if (observing)
{
try
{
observing = false;
db.RemoveChangeListener(this);
}
finally
{
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": stopObserving() calling asyncTaskFinished()"
);
AsyncTaskFinished(1);
}
}
}
[InterfaceAudience.Private]
public void Changed(Database.ChangeEvent @event)
{
IList<DocumentChange> changes = @event.GetChanges();
foreach (DocumentChange change in changes)
{
// Skip revisions that originally came from the database I'm syncing to:
Uri source = change.GetSourceUrl();
if (source != null && source.Equals(remote))
{
return;
}
RevisionInternal rev = change.GetAddedRevision();
IDictionary<string, object> paramsFixMe = null;
// TODO: these should not be null
if (GetLocalDatabase().RunFilter(filter, paramsFixMe, rev))
{
AddToInbox(rev);
}
}
}
[InterfaceAudience.Private]
protected internal override void ProcessInbox(RevisionList inbox)
{
long lastInboxSequence = inbox[inbox.Count - 1].GetSequence();
// Generate a set of doc/rev IDs in the JSON format that _revs_diff wants:
// <http://wiki.apache.org/couchdb/HttpPostRevsDiff>
IDictionary<string, IList<string>> diffs = new Dictionary<string, IList<string>>(
);
foreach (RevisionInternal rev in inbox)
{
string docID = rev.GetDocId();
IList<string> revs = diffs.Get(docID);
if (revs == null)
{
revs = new AList<string>();
diffs.Put(docID, revs);
}
revs.AddItem(rev.GetRevId());
}
// Call _revs_diff on the target db:
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": processInbox() calling asyncTaskStarted()"
);
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": posting to /_revs_diff: "
+ diffs);
AsyncTaskStarted();
SendAsyncRequest("POST", "/_revs_diff", diffs, new _RemoteRequestCompletionBlock_226
(this, inbox, lastInboxSequence));
}
private sealed class _RemoteRequestCompletionBlock_226 : RemoteRequestCompletionBlock
{
public _RemoteRequestCompletionBlock_226(Pusher _enclosing, RevisionList inbox, long
lastInboxSequence)
{
this._enclosing = _enclosing;
this.inbox = inbox;
this.lastInboxSequence = lastInboxSequence;
}
public void OnCompletion(object response, Exception e)
{
try
{
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": /_revs_diff response: "
+ response);
IDictionary<string, object> results = (IDictionary<string, object>)response;
if (e != null)
{
this._enclosing.SetError(e);
this._enclosing.RevisionFailed();
}
else
{
if (results.Count != 0)
{
// Go through the list of local changes again, selecting the ones the destination server
// said were missing and mapping them to a JSON dictionary in the form _bulk_docs wants:
IList<object> docsToSend = new AList<object>();
foreach (RevisionInternal rev in inbox)
{
IDictionary<string, object> properties = null;
IDictionary<string, object> resultDoc = (IDictionary<string, object>)results.Get(
rev.GetDocId());
if (resultDoc != null)
{
IList<string> revs = (IList<string>)resultDoc.Get("missing");
if (revs != null && revs.Contains(rev.GetRevId()))
{
//remote server needs this revision
// Get the revision's properties
if (rev.IsDeleted())
{
properties = new Dictionary<string, object>();
properties.Put("_id", rev.GetDocId());
properties.Put("_rev", rev.GetRevId());
properties.Put("_deleted", true);
}
else
{
// OPT: Shouldn't include all attachment bodies, just ones that have changed
EnumSet<Database.TDContentOptions> contentOptions = EnumSet.Of(Database.TDContentOptions
.TDIncludeAttachments, Database.TDContentOptions.TDBigAttachmentsFollow);
try
{
this._enclosing.db.LoadRevisionBody(rev, contentOptions);
}
catch (CouchbaseLiteException)
{
string msg = string.Format("%s Couldn't get local contents of %s", rev, this._enclosing
);
Log.W(Database.Tag, msg);
this._enclosing.RevisionFailed();
continue;
}
properties = new Dictionary<string, object>(rev.GetProperties());
}
if (properties.ContainsKey("_attachments"))
{
if (this._enclosing.UploadMultipartRevision(rev))
{
continue;
}
}
if (properties != null)
{
// Add the _revisions list:
properties.Put("_revisions", this._enclosing.db.GetRevisionHistoryDict(rev));
//now add it to the docs to send
docsToSend.AddItem(properties);
}
}
}
}
// Post the revisions to the destination. "new_edits":false means that the server should
// use the given _rev IDs instead of making up new ones.
int numDocsToSend = docsToSend.Count;
if (numDocsToSend > 0)
{
IDictionary<string, object> bulkDocsBody = new Dictionary<string, object>();
bulkDocsBody.Put("docs", docsToSend);
bulkDocsBody.Put("new_edits", false);
Log.V(Database.Tag, string.Format("%s: POSTing " + numDocsToSend + " revisions to _bulk_docs: %s"
, this._enclosing, docsToSend));
this._enclosing.SetChangesCount(this._enclosing.GetChangesCount() + numDocsToSend
);
Log.D(Database.Tag, this._enclosing + "|" + Sharpen.Thread.CurrentThread() + ": processInbox-before_bulk_docs() calling asyncTaskStarted()"
);
this._enclosing.AsyncTaskStarted();
this._enclosing.SendAsyncRequest("POST", "/_bulk_docs", bulkDocsBody, new _RemoteRequestCompletionBlock_300
(this, docsToSend, lastInboxSequence, numDocsToSend));
}
}
else
{
// If none of the revisions are new to the remote, just bump the lastSequence:
this._enclosing.SetLastSequence(string.Format("%d", lastInboxSequence));
}
}
}
finally
{
Log.D(Database.Tag, this._enclosing + "|" + Sharpen.Thread.CurrentThread() + ": processInbox() calling asyncTaskFinished()"
);
this._enclosing.AsyncTaskFinished(1);
}
}
private sealed class _RemoteRequestCompletionBlock_300 : RemoteRequestCompletionBlock
{
public _RemoteRequestCompletionBlock_300(_RemoteRequestCompletionBlock_226 _enclosing
, IList<object> docsToSend, long lastInboxSequence, int numDocsToSend)
{
this._enclosing = _enclosing;
this.docsToSend = docsToSend;
this.lastInboxSequence = lastInboxSequence;
this.numDocsToSend = numDocsToSend;
}
public void OnCompletion(object result, Exception e)
{
try
{
if (e != null)
{
this._enclosing._enclosing.SetError(e);
this._enclosing._enclosing.RevisionFailed();
}
else
{
Log.V(Database.Tag, string.Format("%s: POSTed to _bulk_docs: %s", this._enclosing
._enclosing, docsToSend));
this._enclosing._enclosing.SetLastSequence(string.Format("%d", lastInboxSequence)
);
}
this._enclosing._enclosing.SetCompletedChangesCount(this._enclosing._enclosing.GetCompletedChangesCount
() + numDocsToSend);
}
finally
{
Log.D(Database.Tag, this._enclosing._enclosing + "|" + Sharpen.Thread.CurrentThread
() + ": processInbox-after_bulk_docs() calling asyncTaskFinished()");
this._enclosing._enclosing.AsyncTaskFinished(1);
}
}
private readonly _RemoteRequestCompletionBlock_226 _enclosing;
private readonly IList<object> docsToSend;
private readonly long lastInboxSequence;
private readonly int numDocsToSend;
}
private readonly Pusher _enclosing;
private readonly RevisionList inbox;
private readonly long lastInboxSequence;
}
[InterfaceAudience.Private]
private bool UploadMultipartRevision(RevisionInternal revision)
{
MultipartEntity multiPart = null;
IDictionary<string, object> revProps = revision.GetProperties();
revProps.Put("_revisions", db.GetRevisionHistoryDict(revision));
// TODO: refactor this to
IDictionary<string, object> attachments = (IDictionary<string, object>)revProps.Get
("_attachments");
foreach (string attachmentKey in attachments.Keys)
{
IDictionary<string, object> attachment = (IDictionary<string, object>)attachments
.Get(attachmentKey);
if (attachment.ContainsKey("follows"))
{
if (multiPart == null)
{
multiPart = new MultipartEntity();
try
{
string json = Manager.GetObjectMapper().WriteValueAsString(revProps);
Encoding utf8charset = Sharpen.Extensions.GetEncoding("UTF-8");
multiPart.AddPart("param1", new StringBody(json, "application/json", utf8charset)
);
}
catch (IOException e)
{
throw new ArgumentException(e);
}
}
BlobStore blobStore = this.db.GetAttachments();
string base64Digest = (string)attachment.Get("digest");
BlobKey blobKey = new BlobKey(base64Digest);
InputStream inputStream = blobStore.BlobStreamForKey(blobKey);
if (inputStream == null)
{
Log.W(Database.Tag, "Unable to find blob file for blobKey: " + blobKey + " - Skipping upload of multipart revision."
);
multiPart = null;
}
else
{
string contentType = null;
if (attachment.ContainsKey("content_type"))
{
contentType = (string)attachment.Get("content_type");
}
else
{
if (attachment.ContainsKey("content-type"))
{
string message = string.Format("Found attachment that uses content-type" + " field name instead of content_type (see couchbase-lite-android"
+ " issue #80): " + attachment);
Log.W(Database.Tag, message);
}
}
multiPart.AddPart(attachmentKey, new InputStreamBody(inputStream, contentType, attachmentKey
));
}
}
}
if (multiPart == null)
{
return false;
}
string path = string.Format("/%s?new_edits=false", revision.GetDocId());
// TODO: need to throttle these requests
Log.D(Database.Tag, "Uploadeding multipart request. Revision: " + revision);
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": uploadMultipartRevision() calling asyncTaskStarted()"
);
AsyncTaskStarted();
SendAsyncMultipartRequest("PUT", path, multiPart, new _RemoteRequestCompletionBlock_411
(this));
// TODO:
return true;
}
private sealed class _RemoteRequestCompletionBlock_411 : RemoteRequestCompletionBlock
{
public _RemoteRequestCompletionBlock_411(Pusher _enclosing)
{
this._enclosing = _enclosing;
}
public void OnCompletion(object result, Exception e)
{
try
{
if (e != null)
{
Log.E(Database.Tag, "Exception uploading multipart request", e);
this._enclosing.SetError(e);
this._enclosing.RevisionFailed();
}
else
{
Log.D(Database.Tag, "Uploaded multipart request. Result: " + result);
}
}
finally
{
Log.D(Database.Tag, this + "|" + Sharpen.Thread.CurrentThread() + ": uploadMultipartRevision() calling asyncTaskFinished()"
);
this._enclosing.AsyncTaskFinished(1);
}
}
private readonly Pusher _enclosing;
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RedditSharp.Things;
using System;
using System.Linq;
using System.Net;
using System.Security.Authentication;
using System.Threading.Tasks;
using DefaultWebAgent = RedditSharp.WebAgent;
namespace RedditSharp
{
/// <summary>
/// Class to communicate with Reddit.com
/// </summary>
public class Reddit
{
#region Constant Urls
private const string SslLoginUrl = "https://ssl.reddit.com/api/login";
private const string LoginUrl = "/api/login/username";
private const string UserInfoUrl = "/user/{0}/about.json";
private const string MeUrl = "/api/me.json";
private const string OAuthMeUrl = "/api/v1/me.json";
private const string SubredditAboutUrl = "/r/{0}/about.json";
private const string ComposeMessageUrl = "/api/compose";
private const string RegisterAccountUrl = "/api/register";
private const string GetThingUrl = "/api/info.json?id={0}";
private const string GetCommentUrl = "/r/{0}/comments/{1}/foo/{2}";
private const string GetPostUrl = "{0}.json";
private const string DomainUrl = "www.reddit.com";
private const string OAuthDomainUrl = "oauth.reddit.com";
private const string SearchUrl = "/search.json?q={0}&restrict_sr=off&sort={1}&t={2}";
private const string UrlSearchPattern = "url:'{0}'";
private const string NewSubredditsUrl = "/subreddits/new.json";
private const string PopularSubredditsUrl = "/subreddits/popular.json";
private const string GoldSubredditsUrl = "/subreddits/gold.json";
private const string DefaultSubredditsUrl = "/subreddits/default.json";
private const string SearchSubredditsUrl = "/subreddits/search.json?q={0}";
#endregion
internal IWebAgent WebAgent { get; set; }
/// <summary>
/// Captcha solver instance to use when solving captchas.
/// </summary>
public ICaptchaSolver CaptchaSolver;
/// <summary>
/// The authenticated user for this instance.
/// </summary>
public AuthenticatedUser User { get; set; }
/// <summary>
/// Sets the Rate Limiting Mode of the underlying WebAgent
/// </summary>
public DefaultWebAgent.RateLimitMode RateLimit
{
get { return DefaultWebAgent.RateLimit; }
set { DefaultWebAgent.RateLimit = value; }
}
internal JsonSerializerSettings JsonSerializerSettings { get; set; }
/// <summary>
/// Gets the FrontPage using the current Reddit instance.
/// </summary>
public Subreddit FrontPage
{
get { return Subreddit.GetFrontPage(this); }
}
/// <summary>
/// Gets /r/All using the current Reddit instance.
/// </summary>
public Subreddit RSlashAll
{
get { return Subreddit.GetRSlashAll(this); }
}
public Reddit()
: this(true) { }
public Reddit(bool useSsl)
{
DefaultWebAgent defaultAgent = new DefaultWebAgent();
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
DefaultWebAgent.Protocol = useSsl ? "https" : "http";
WebAgent = defaultAgent;
CaptchaSolver = new ConsoleCaptchaSolver();
}
public Reddit(DefaultWebAgent.RateLimitMode limitMode, bool useSsl = true)
: this(useSsl)
{
DefaultWebAgent.UserAgent = "";
DefaultWebAgent.RateLimit = limitMode;
DefaultWebAgent.RootDomain = "www.reddit.com";
}
/// <summary>
/// DEPRECATED: Avoid use as Reddit will be removing this option eventually
/// </summary>
/// <param name="username"></param>
/// <param name="password"></param>
/// <param name="useSsl"></param>
public Reddit(string username, string password, bool useSsl = true)
: this(useSsl)
{
LogIn(username, password, useSsl);
}
public Reddit(string accessToken)
: this(true)
{
DefaultWebAgent.RootDomain = OAuthDomainUrl;
WebAgent.AccessToken = accessToken;
InitOrUpdateUser();
}
/// <summary>
/// Creates a Reddit instance with the given WebAgent implementation
/// </summary>
/// <param name="agent">Implementation of IWebAgent interface. Used to generate requests.</param>
public Reddit(IWebAgent agent)
{
WebAgent = agent;
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
CaptchaSolver = new ConsoleCaptchaSolver();
}
/// <summary>
/// Creates a Reddit instance with the given WebAgent implementation
/// </summary>
/// <param name="agent">Implementation of IWebAgent interface. Used to generate requests.</param>
/// <param name="initUser">Whether to run InitOrUpdateUser, requires <paramref name="agent"/> to have credentials first.</param>
public Reddit(IWebAgent agent, bool initUser)
{
WebAgent = agent;
JsonSerializerSettings = new JsonSerializerSettings
{
CheckAdditionalContent = false,
DefaultValueHandling = DefaultValueHandling.Ignore
};
CaptchaSolver = new ConsoleCaptchaSolver();
if(initUser) InitOrUpdateUser();
}
/// <summary>
/// Logs in the current Reddit instance. DEPRECATED
/// </summary>
/// <param name="username">The username of the user to log on to.</param>
/// <param name="password">The password of the user to log on to.</param>
/// <param name="useSsl">Whether to use SSL or not. (default: true)</param>
/// <returns></returns>
public AuthenticatedUser LogIn(string username, string password, bool useSsl = true)
{
if (Type.GetType("Mono.Runtime") != null)
ServicePointManager.ServerCertificateValidationCallback = (s, c, ch, ssl) => true;
WebAgent.Cookies = new CookieContainer();
HttpWebRequest request;
if (useSsl)
request = WebAgent.CreatePost(SslLoginUrl);
else
request = WebAgent.CreatePost(LoginUrl);
var stream = request.GetRequestStream();
if (useSsl)
{
WebAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json"
});
}
else
{
WebAgent.WritePostBody(stream, new
{
user = username,
passwd = password,
api_type = "json",
op = "login"
});
}
stream.Close();
var response = (HttpWebResponse)request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result)["json"];
if (json["errors"].Count() != 0)
throw new AuthenticationException("Incorrect login.");
InitOrUpdateUser();
return User;
}
public RedditUser GetUser(string name)
{
var request = WebAgent.CreateGet(string.Format(UserInfoUrl, name));
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new RedditUser().Init(this, json, WebAgent);
}
/// <summary>
/// Initializes the User property if it's null,
/// otherwise replaces the existing user object
/// with a new one fetched from reddit servers.
/// </summary>
public void InitOrUpdateUser()
{
var request = WebAgent.CreateGet(string.IsNullOrEmpty(WebAgent.AccessToken) ? MeUrl : OAuthMeUrl);
var response = (HttpWebResponse)request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
User = new AuthenticatedUser().Init(this, json, WebAgent);
}
#region Obsolete Getter Methods
[Obsolete("Use User property instead")]
public AuthenticatedUser GetMe()
{
return User;
}
#endregion Obsolete Getter Methods
public Subreddit GetSubreddit(string name)
{
name = System.Text.RegularExpressions.Regex.Replace(name, "(r/|/)", "");
return GetThing<Subreddit>(string.Format(SubredditAboutUrl, name));
}
/// <summary>
/// Returns the subreddit.
/// </summary>
/// <param name="name">The name of the subreddit</param>
/// <returns>The Subreddit by given name</returns>
public async Task<Subreddit> GetSubredditAsync(string name)
{
name = System.Text.RegularExpressions.Regex.Replace(name, "(r/|/)", "");
return await GetThingAsync<Subreddit>(string.Format(SubredditAboutUrl, name));
}
public Domain GetDomain(string domain)
{
if (!domain.StartsWith("http://") && !domain.StartsWith("https://"))
domain = "http://" + domain;
var uri = new Uri(domain);
return new Domain(this, uri, WebAgent);
}
public JToken GetToken(Uri uri)
{
var url = uri.AbsoluteUri;
if (url.EndsWith("/"))
url = url.Remove(url.Length - 1);
var request = WebAgent.CreateGet(string.Format(GetPostUrl, url));
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return json[0]["data"]["children"].First;
}
public Post GetPost(Uri uri)
{
return new Post().Init(this, GetToken(uri), WebAgent);
}
/// <summary>
///
/// </summary>
/// <param name="subject"></param>
/// <param name="body"></param>
/// <param name="to"></param>
/// <param name="fromSubReddit">The subreddit to send the message as (optional).</param>
/// <param name="captchaId"></param>
/// <param name="captchaAnswer"></param>
/// <remarks>If <paramref name="fromSubReddit"/> is passed in then the message is sent from the subreddit. the sender must be a mod of the specified subreddit.</remarks>
/// <exception cref="AuthenticationException">Thrown when a subreddit is passed in and the user is not a mod of that sub.</exception>
public void ComposePrivateMessage(string subject, string body, string to, string fromSubReddit = "", string captchaId = "", string captchaAnswer = "")
{
if (User == null)
throw new Exception("User can not be null.");
if (!string.IsNullOrWhiteSpace(fromSubReddit))
{
var subReddit = this.GetSubreddit(fromSubReddit);
var modNameList = subReddit.Moderators.Select(b => b.Name).ToList();
if (!modNameList.Contains(User.Name))
throw new AuthenticationException(
string.Format(
@"User {0} is not a moderator of subreddit {1}.",
User.Name,
subReddit.Name));
}
var request = WebAgent.CreatePost(ComposeMessageUrl);
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
subject,
text = body,
to,
from_sr = fromSubReddit,
uh = User.Modhash,
iden = captchaId,
captcha = captchaAnswer
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
ICaptchaSolver solver = CaptchaSolver; // Prevent race condition
if (json["json"]["errors"].Any() && json["json"]["errors"][0][0].ToString() == "BAD_CAPTCHA" && solver != null)
{
captchaId = json["json"]["captcha"].ToString();
CaptchaResponse captchaResponse = solver.HandleCaptcha(new Captcha(captchaId));
if (!captchaResponse.Cancel) // Keep trying until we are told to cancel
ComposePrivateMessage(subject, body, to, fromSubReddit, captchaId, captchaResponse.Answer);
}
}
/// <summary>
/// Registers a new Reddit user
/// </summary>
/// <param name="userName">The username for the new account.</param>
/// <param name="passwd">The password for the new account.</param>
/// <param name="email">The optional recovery email for the new account.</param>
/// <returns>The newly created user account</returns>
public AuthenticatedUser RegisterAccount(string userName, string passwd, string email = "")
{
var request = WebAgent.CreatePost(RegisterAccountUrl);
WebAgent.WritePostBody(request.GetRequestStream(), new
{
api_type = "json",
email = email,
passwd = passwd,
passwd2 = passwd,
user = userName
});
var response = request.GetResponse();
var result = WebAgent.GetResponseString(response.GetResponseStream());
var json = JObject.Parse(result);
return new AuthenticatedUser().Init(this, json, WebAgent);
// TODO: Error
}
public Thing GetThingByFullname(string fullname)
{
var request = WebAgent.CreateGet(string.Format(GetThingUrl, fullname));
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
return Thing.Parse(this, json["data"]["children"][0], WebAgent);
}
public Comment GetComment(string subreddit, string name, string linkName)
{
try
{
if (linkName.StartsWith("t3_"))
linkName = linkName.Substring(3);
if (name.StartsWith("t1_"))
name = name.Substring(3);
var url = string.Format(GetCommentUrl, subreddit, linkName, name);
return GetComment(new Uri(url));
}
catch (WebException)
{
return null;
}
}
public Comment GetComment(Uri uri)
{
var url = string.Format(GetPostUrl, uri.AbsoluteUri);
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var sender = new Post().Init(this, json[0]["data"]["children"][0], WebAgent);
return new Comment().Init(this, json[1]["data"]["children"][0], WebAgent, sender);
}
public Listing<T> SearchByUrl<T>(string url) where T : Thing
{
var urlSearchQuery = string.Format(UrlSearchPattern, url);
return Search<T>(urlSearchQuery);
}
public Listing<T> Search<T>(string query, Sorting sortE = Sorting.Relevance, TimeSorting timeE = TimeSorting.All) where T : Thing
{
string sort = sortE.ToString().ToLower();
string time = timeE.ToString().ToLower();
return new Listing<T>(this, string.Format(SearchUrl, query, sort, time), WebAgent);
}
public Listing<T> SearchByTimestamp<T>(DateTime from, DateTime to, string query = "", string subreddit = "", Sorting sortE = Sorting.Relevance, TimeSorting timeE = TimeSorting.All) where T : Thing
{
string sort = sortE.ToString().ToLower();
string time = timeE.ToString().ToLower();
var fromUnix = (from - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
var toUnix = (to - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
string searchQuery = "(and+timestamp:" + fromUnix + ".." + toUnix + "+'" + query + "'+" + "subreddit:'" + subreddit + "')&syntax=cloudsearch";
return new Listing<T>(this, string.Format(SearchUrl, searchQuery, sort, time), WebAgent);
}
#region SubredditSearching
/// <summary>
/// Returns a Listing of newly created subreddits.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetNewSubreddits()
{
return new Listing<Subreddit>(this, NewSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns a Listing of the most popular subreddits.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetPopularSubreddits()
{
return new Listing<Subreddit>(this, PopularSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns a Listing of Gold-only subreddits. This endpoint will not return anything if the authenticated Reddit account does not currently have gold.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetGoldSubreddits()
{
return new Listing<Subreddit>(this, GoldSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns the Listing of default subreddits.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> GetDefaultSubreddits()
{
return new Listing<Subreddit>(this, DefaultSubredditsUrl, WebAgent);
}
/// <summary>
/// Returns the Listing of subreddits related to a query.
/// </summary>
/// <returns></returns>
public Listing<Subreddit> SearchSubreddits(string query)
{
return new Listing<Subreddit>(this, string.Format(SearchSubredditsUrl, query), WebAgent);
}
#endregion SubredditSearching
#region Helpers
protected async internal Task<T> GetThingAsync<T>(string url) where T : Thing
{
var request = WebAgent.CreateGet(url);
var response = await request.GetResponseAsync();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var ret = await Thing.ParseAsync(this, json, WebAgent);
return (T)ret;
}
protected internal T GetThing<T>(string url) where T : Thing
{
var request = WebAgent.CreateGet(url);
var response = request.GetResponse();
var data = WebAgent.GetResponseString(response.GetResponseStream());
var json = JToken.Parse(data);
var ret = Thing.Parse(this, json, WebAgent);
return (T)ret;
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Win32.SafeHandles;
namespace Internal.Cryptography.Pal
{
internal class OpenSslX509Encoder : IX509Pal
{
public AsymmetricAlgorithm DecodePublicKey(Oid oid, byte[] encodedKeyValue, byte[] encodedParameters)
{
switch (oid.Value)
{
case Oids.RsaRsa:
return BuildRsaPublicKey(encodedKeyValue);
}
// NotSupportedException is what desktop and CoreFx-Windows throw in this situation.
throw new NotSupportedException(SR.NotSupported_KeyAlgorithm);
}
public unsafe string X500DistinguishedNameDecode(byte[] encodedDistinguishedName, X500DistinguishedNameFlags flag)
{
using (SafeX509NameHandle x509Name = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_X509_NAME, encodedDistinguishedName))
{
if (x509Name.IsInvalid)
{
throw new CryptographicException(Interop.libcrypto.GetOpenSslErrorString());
}
using (SafeBioHandle bioHandle = Interop.libcrypto.BIO_new(Interop.libcrypto.BIO_s_mem()))
{
if (bioHandle.IsInvalid)
{
throw new CryptographicException(Interop.libcrypto.GetOpenSslErrorString());
}
OpenSslX09NameFormatFlags nativeFlags = ConvertFormatFlags(flag);
int written = Interop.libcrypto.X509_NAME_print_ex(
bioHandle,
x509Name,
0,
new UIntPtr((uint)nativeFlags));
// X509_NAME_print_ex returns how many bytes were written into the buffer.
// BIO_gets wants to ensure that the response is NULL-terminated.
// So add one to leave space for the NULL.
StringBuilder builder = new StringBuilder(written + 1);
int read = Interop.libcrypto.BIO_gets(bioHandle, builder, builder.Capacity);
if (read < 0)
{
throw new CryptographicException(Interop.libcrypto.GetOpenSslErrorString());
}
return builder.ToString();
}
}
}
public byte[] X500DistinguishedNameEncode(string distinguishedName, X500DistinguishedNameFlags flag)
{
throw new NotImplementedException();
}
public string X500DistinguishedNameFormat(byte[] encodedDistinguishedName, bool multiLine)
{
throw new NotImplementedException();
}
public X509ContentType GetCertContentType(byte[] rawData)
{
throw new NotImplementedException();
}
public X509ContentType GetCertContentType(string fileName)
{
throw new NotImplementedException();
}
public byte[] EncodeX509KeyUsageExtension(X509KeyUsageFlags keyUsages)
{
throw new NotImplementedException();
}
public unsafe void DecodeX509KeyUsageExtension(byte[] encoded, out X509KeyUsageFlags keyUsages)
{
using (SafeAsn1BitStringHandle bitString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_BIT_STRING, encoded))
{
if (bitString.IsInvalid)
{
throw new CryptographicException(Interop.libcrypto.GetOpenSslErrorString());
}
byte[] decoded = Interop.NativeCrypto.GetAsn1StringBytes(bitString.DangerousGetHandle());
// Only 9 bits are defined.
if (decoded.Length > 2)
{
throw new CryptographicException();
}
// DER encodings of BIT_STRING values number the bits as
// 01234567 89 (big endian), plus a number saying how many bits of the last byte were padding.
//
// So digitalSignature (0) doesn't mean 2^0 (0x01), it means the most significant bit
// is set in this byte stream.
//
// BIT_STRING values are compact. So a value of cRLSign (6) | keyEncipherment (2), which
// is 0b0010001 => 0b0010 0010 (1 bit padding) => 0x22 encoded is therefore
// 0x02 (length remaining) 0x01 (1 bit padding) 0x22.
//
// OpenSSL's d2i_ASN1_BIT_STRING is going to take that, and return 0x22. 0x22 lines up
// exactly with X509KeyUsageFlags.CrlSign (0x20) | X509KeyUsageFlags.KeyEncipherment (0x02)
//
// Once the decipherOnly (8) bit is added to the mix, the values become:
// 0b001000101 => 0b0010 0010 1000 0000 (7 bits padding)
// { 0x03 0x07 0x22 0x80 }
// And OpenSSL returns new byte[] { 0x22 0x80 }
//
// The value of X509KeyUsageFlags.DecipherOnly is 0x8000. 0x8000 in a little endian
// representation is { 0x00 0x80 }. This means that the DER storage mechanism has effectively
// ended up being little-endian for BIT_STRING values. Untwist the bytes, and now the bits all
// line up with the existing X509KeyUsageFlags.
int value = 0;
if (decoded.Length > 0)
{
value = decoded[0];
}
if (decoded.Length > 1)
{
value |= decoded[1] << 8;
}
keyUsages = (X509KeyUsageFlags)value;
}
}
public byte[] EncodeX509BasicConstraints2Extension(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint)
{
throw new NotImplementedException();
}
public void DecodeX509BasicConstraintsExtension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
throw new NotImplementedException();
}
public unsafe void DecodeX509BasicConstraints2Extension(
byte[] encoded,
out bool certificateAuthority,
out bool hasPathLengthConstraint,
out int pathLengthConstraint)
{
using (SafeBasicConstraintsHandle constraints = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_BASIC_CONSTRAINTS, encoded))
{
Interop.libcrypto.BASIC_CONSTRAINTS* data = (Interop.libcrypto.BASIC_CONSTRAINTS*)constraints.DangerousGetHandle();
certificateAuthority = data->CA != 0;
if (data->pathlen != IntPtr.Zero)
{
hasPathLengthConstraint = true;
pathLengthConstraint = Interop.libcrypto.ASN1_INTEGER_get(data->pathlen).ToInt32();
}
else
{
hasPathLengthConstraint = false;
pathLengthConstraint = 0;
}
}
}
public byte[] EncodeX509EnhancedKeyUsageExtension(OidCollection usages)
{
throw new NotImplementedException();
}
public unsafe void DecodeX509EnhancedKeyUsageExtension(byte[] encoded, out OidCollection usages)
{
OidCollection oids = new OidCollection();
using (SafeEkuExtensionHandle eku = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_EXTENDED_KEY_USAGE, encoded))
{
int count = Interop.NativeCrypto.GetX509EkuFieldCount(eku);
for (int i = 0; i < count; i++)
{
IntPtr oidPtr = Interop.NativeCrypto.GetX509EkuField(eku, i);
if (oidPtr == IntPtr.Zero)
{
throw new CryptographicException();
}
string oidValue = Interop.libcrypto.OBJ_obj2txt_helper(oidPtr);
oids.Add(new Oid(oidValue));
}
}
usages = oids;
}
public byte[] EncodeX509SubjectKeyIdentifierExtension(byte[] subjectKeyIdentifier)
{
throw new NotImplementedException();
}
public unsafe void DecodeX509SubjectKeyIdentifierExtension(byte[] encoded, out byte[] subjectKeyIdentifier)
{
using (SafeAsn1OctetStringHandle octetString = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_ASN1_OCTET_STRING, encoded))
{
subjectKeyIdentifier = Interop.NativeCrypto.GetAsn1StringBytes(octetString.DangerousGetHandle());
}
}
public byte[] ComputeCapiSha1OfPublicKey(PublicKey key)
{
throw new NotImplementedException();
}
private static OpenSslX09NameFormatFlags ConvertFormatFlags(X500DistinguishedNameFlags inFlags)
{
OpenSslX09NameFormatFlags outFlags = 0;
if (inFlags.HasFlag(X500DistinguishedNameFlags.Reversed))
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_DN_REV;
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.UseSemicolons))
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_SPLUS_SPC;
}
else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseNewLines))
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_MULTILINE;
}
else
{
outFlags |= OpenSslX09NameFormatFlags.XN_FLAG_SEP_CPLUS_SPC;
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.DoNotUseQuotes))
{
// TODO: Handle this.
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.ForceUTF8Encoding))
{
// TODO: Handle this.
}
if (inFlags.HasFlag(X500DistinguishedNameFlags.UseUTF8Encoding))
{
// TODO: Handle this.
}
else if (inFlags.HasFlag(X500DistinguishedNameFlags.UseT61Encoding))
{
// TODO: Handle this.
}
return outFlags;
}
private static unsafe RSA BuildRsaPublicKey(byte[] encodedData)
{
using (SafeRsaHandle rsaHandle = Interop.libcrypto.OpenSslD2I(Interop.libcrypto.d2i_RSAPublicKey, encodedData))
{
if (rsaHandle.IsInvalid)
{
throw new CryptographicException(Interop.libcrypto.GetOpenSslErrorString());
}
RSAParameters rsaParameters = Interop.libcrypto.ExportRsaParameters(rsaHandle, false);
RSA rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
return rsa;
}
}
[Flags]
private enum OpenSslX09NameFormatFlags : uint
{
XN_FLAG_SEP_MASK = (0xf << 16),
// O=Apache HTTP Server, OU=Test Certificate, CN=localhost
// Note that this is the only not-reversed value, since XN_FLAG_COMPAT | XN_FLAG_DN_REV produces nothing.
XN_FLAG_COMPAT = 0,
// CN=localhost,OU=Test Certificate,O=Apache HTTP Server
XN_FLAG_SEP_COMMA_PLUS = (1 << 16),
// CN=localhost, OU=Test Certificate, O=Apache HTTP Server
XN_FLAG_SEP_CPLUS_SPC = (2 << 16),
// CN=localhost; OU=Test Certificate; O=Apache HTTP Server
XN_FLAG_SEP_SPLUS_SPC = (3 << 16),
// CN=localhost
// OU=Test Certificate
// O=Apache HTTP Server
XN_FLAG_SEP_MULTILINE = (4 << 16),
XN_FLAG_DN_REV = (1 << 20),
XN_FLAG_FN_MASK = (0x3 << 21),
// CN=localhost, OU=Test Certificate, O=Apache HTTP Server
XN_FLAG_FN_SN = 0,
// commonName=localhost, organizationalUnitName=Test Certificate, organizationName=Apache HTTP Server
XN_FLAG_FN_LN = (1 << 21),
// 2.5.4.3=localhost, 2.5.4.11=Test Certificate, 2.5.4.10=Apache HTTP Server
XN_FLAG_FN_OID = (2 << 21),
// localhost, Test Certificate, Apache HTTP Server
XN_FLAG_FN_NONE = (3 << 21),
// CN = localhost, OU = Test Certificate, O = Apache HTTP Server
XN_FLAG_SPC_EQ = (1 << 23),
XN_FLAG_DUMP_UNKNOWN_FIELDS = (1 << 24),
XN_FLAG_FN_ALIGN = (1 << 25),
}
}
}
| |
// SharpMath - C# Mathematical Library
/*************************************************************************
Copyright (c) 2005-2007, Sergey Bochkanov (ALGLIB project).
>>> SOURCE LICENSE >>>
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 (www.fsf.org); 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.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************/
using System;
namespace SharpMath.LinearAlgebra.AlgLib
{
internal class blas
{
public static double vectornorm2(ref double[] x,
int i1,
int i2)
{
double result = 0;
int n = 0;
int ix = 0;
double absxi = 0;
double scl = 0;
double ssq = 0;
n = i2 - i1 + 1;
if (n < 1)
{
result = 0;
return result;
}
if (n == 1)
{
result = Math.Abs(x[i1]);
return result;
}
scl = 0;
ssq = 1;
for (ix = i1; ix <= i2; ix++)
{
if ((double)(x[ix]) != (double)(0))
{
absxi = Math.Abs(x[ix]);
if ((double)(scl) < (double)(absxi))
{
ssq = 1 + ssq * AP.Math.Sqr(scl / absxi);
scl = absxi;
}
else
{
ssq = ssq + AP.Math.Sqr(absxi / scl);
}
}
}
result = scl * Math.Sqrt(ssq);
return result;
}
public static int vectoridxabsmax(ref double[] x,
int i1,
int i2)
{
int result = 0;
int i = 0;
double a = 0;
result = i1;
a = Math.Abs(x[result]);
for (i = i1 + 1; i <= i2; i++)
{
if ((double)(Math.Abs(x[i])) > (double)(Math.Abs(x[result])))
{
result = i;
}
}
return result;
}
public static int columnidxabsmax(ref double[,] x,
int i1,
int i2,
int j)
{
int result = 0;
int i = 0;
double a = 0;
result = i1;
a = Math.Abs(x[result, j]);
for (i = i1 + 1; i <= i2; i++)
{
if ((double)(Math.Abs(x[i, j])) > (double)(Math.Abs(x[result, j])))
{
result = i;
}
}
return result;
}
public static int rowidxabsmax(ref double[,] x,
int j1,
int j2,
int i)
{
int result = 0;
int j = 0;
double a = 0;
result = j1;
a = Math.Abs(x[i, result]);
for (j = j1 + 1; j <= j2; j++)
{
if ((double)(Math.Abs(x[i, j])) > (double)(Math.Abs(x[i, result])))
{
result = j;
}
}
return result;
}
public static double upperhessenberg1norm(ref double[,] a,
int i1,
int i2,
int j1,
int j2,
ref double[] work)
{
double result = 0;
int i = 0;
int j = 0;
System.Diagnostics.Debug.Assert(i2 - i1 == j2 - j1, "UpperHessenberg1Norm: I2-I1<>J2-J1!");
for (j = j1; j <= j2; j++)
{
work[j] = 0;
}
for (i = i1; i <= i2; i++)
{
for (j = Math.Max(j1, j1 + i - i1 - 1); j <= j2; j++)
{
work[j] = work[j] + Math.Abs(a[i, j]);
}
}
result = 0;
for (j = j1; j <= j2; j++)
{
result = Math.Max(result, work[j]);
}
return result;
}
public static void copymatrix(ref double[,] a,
int is1,
int is2,
int js1,
int js2,
ref double[,] b,
int id1,
int id2,
int jd1,
int jd2)
{
int isrc = 0;
int idst = 0;
int i_ = 0;
int i1_ = 0;
if (is1 > is2 | js1 > js2)
{
return;
}
System.Diagnostics.Debug.Assert(is2 - is1 == id2 - id1, "CopyMatrix: different sizes!");
System.Diagnostics.Debug.Assert(js2 - js1 == jd2 - jd1, "CopyMatrix: different sizes!");
for (isrc = is1; isrc <= is2; isrc++)
{
idst = isrc - is1 + id1;
i1_ = (js1) - (jd1);
for (i_ = jd1; i_ <= jd2; i_++)
{
b[idst, i_] = a[isrc, i_ + i1_];
}
}
}
public static void inplacetranspose(ref double[,] a,
int i1,
int i2,
int j1,
int j2,
ref double[] work)
{
int i = 0;
int j = 0;
int ips = 0;
int jps = 0;
int l = 0;
int i_ = 0;
int i1_ = 0;
if (i1 > i2 | j1 > j2)
{
return;
}
System.Diagnostics.Debug.Assert(i1 - i2 == j1 - j2, "InplaceTranspose error: incorrect array size!");
for (i = i1; i <= i2 - 1; i++)
{
j = j1 + i - i1;
ips = i + 1;
jps = j1 + ips - i1;
l = i2 - i;
i1_ = (ips) - (1);
for (i_ = 1; i_ <= l; i_++)
{
work[i_] = a[i_ + i1_, j];
}
i1_ = (jps) - (ips);
for (i_ = ips; i_ <= i2; i_++)
{
a[i_, j] = a[i, i_ + i1_];
}
i1_ = (1) - (jps);
for (i_ = jps; i_ <= j2; i_++)
{
a[i, i_] = work[i_ + i1_];
}
}
}
public static void copyandtranspose(ref double[,] a,
int is1,
int is2,
int js1,
int js2,
ref double[,] b,
int id1,
int id2,
int jd1,
int jd2)
{
int isrc = 0;
int jdst = 0;
int i_ = 0;
int i1_ = 0;
if (is1 > is2 | js1 > js2)
{
return;
}
System.Diagnostics.Debug.Assert(is2 - is1 == jd2 - jd1, "CopyAndTranspose: different sizes!");
System.Diagnostics.Debug.Assert(js2 - js1 == id2 - id1, "CopyAndTranspose: different sizes!");
for (isrc = is1; isrc <= is2; isrc++)
{
jdst = isrc - is1 + jd1;
i1_ = (js1) - (id1);
for (i_ = id1; i_ <= id2; i_++)
{
b[i_, jdst] = a[isrc, i_ + i1_];
}
}
}
public static void matrixvectormultiply(ref double[,] a,
int i1,
int i2,
int j1,
int j2,
bool trans,
ref double[] x,
int ix1,
int ix2,
double alpha,
ref double[] y,
int iy1,
int iy2,
double beta)
{
int i = 0;
double v = 0;
int i_ = 0;
int i1_ = 0;
if (!trans)
{
//
// y := alpha*A*x + beta*y;
//
if (i1 > i2 | j1 > j2)
{
return;
}
System.Diagnostics.Debug.Assert(j2 - j1 == ix2 - ix1, "MatrixVectorMultiply: A and X dont match!");
System.Diagnostics.Debug.Assert(i2 - i1 == iy2 - iy1, "MatrixVectorMultiply: A and Y dont match!");
//
// beta*y
//
if ((double)(beta) == (double)(0))
{
for (i = iy1; i <= iy2; i++)
{
y[i] = 0;
}
}
else
{
for (i_ = iy1; i_ <= iy2; i_++)
{
y[i_] = beta * y[i_];
}
}
//
// alpha*A*x
//
for (i = i1; i <= i2; i++)
{
i1_ = (ix1) - (j1);
v = 0.0;
for (i_ = j1; i_ <= j2; i_++)
{
v += a[i, i_] * x[i_ + i1_];
}
y[iy1 + i - i1] = y[iy1 + i - i1] + alpha * v;
}
}
else
{
//
// y := alpha*A'*x + beta*y;
//
if (i1 > i2 | j1 > j2)
{
return;
}
System.Diagnostics.Debug.Assert(i2 - i1 == ix2 - ix1, "MatrixVectorMultiply: A and X dont match!");
System.Diagnostics.Debug.Assert(j2 - j1 == iy2 - iy1, "MatrixVectorMultiply: A and Y dont match!");
//
// beta*y
//
if ((double)(beta) == (double)(0))
{
for (i = iy1; i <= iy2; i++)
{
y[i] = 0;
}
}
else
{
for (i_ = iy1; i_ <= iy2; i_++)
{
y[i_] = beta * y[i_];
}
}
//
// alpha*A'*x
//
for (i = i1; i <= i2; i++)
{
v = alpha * x[ix1 + i - i1];
i1_ = (j1) - (iy1);
for (i_ = iy1; i_ <= iy2; i_++)
{
y[i_] = y[i_] + v * a[i, i_ + i1_];
}
}
}
}
public static double pythag2(double x,
double y)
{
double result = 0;
double w = 0;
double xabs = 0;
double yabs = 0;
double z = 0;
xabs = Math.Abs(x);
yabs = Math.Abs(y);
w = Math.Max(xabs, yabs);
z = Math.Min(xabs, yabs);
if ((double)(z) == (double)(0))
{
result = w;
}
else
{
result = w * Math.Sqrt(1 + AP.Math.Sqr(z / w));
}
return result;
}
public static void matrixmatrixmultiply(ref double[,] a,
int ai1,
int ai2,
int aj1,
int aj2,
bool transa,
ref double[,] b,
int bi1,
int bi2,
int bj1,
int bj2,
bool transb,
double alpha,
ref double[,] c,
int ci1,
int ci2,
int cj1,
int cj2,
double beta,
ref double[] work)
{
int arows = 0;
int acols = 0;
int brows = 0;
int bcols = 0;
int crows = 0;
int ccols = 0;
int i = 0;
int j = 0;
int k = 0;
int l = 0;
int r = 0;
double v = 0;
int i_ = 0;
int i1_ = 0;
//
// Setup
//
if (!transa)
{
arows = ai2 - ai1 + 1;
acols = aj2 - aj1 + 1;
}
else
{
arows = aj2 - aj1 + 1;
acols = ai2 - ai1 + 1;
}
if (!transb)
{
brows = bi2 - bi1 + 1;
bcols = bj2 - bj1 + 1;
}
else
{
brows = bj2 - bj1 + 1;
bcols = bi2 - bi1 + 1;
}
System.Diagnostics.Debug.Assert(acols == brows, "MatrixMatrixMultiply: incorrect matrix sizes!");
if (arows <= 0 | acols <= 0 | brows <= 0 | bcols <= 0)
{
return;
}
crows = arows;
ccols = bcols;
//
// Test WORK
//
i = Math.Max(arows, acols);
i = Math.Max(brows, i);
i = Math.Max(i, bcols);
work[1] = 0;
work[i] = 0;
//
// Prepare C
//
if ((double)(beta) == (double)(0))
{
for (i = ci1; i <= ci2; i++)
{
for (j = cj1; j <= cj2; j++)
{
c[i, j] = 0;
}
}
}
else
{
for (i = ci1; i <= ci2; i++)
{
for (i_ = cj1; i_ <= cj2; i_++)
{
c[i, i_] = beta * c[i, i_];
}
}
}
//
// A*B
//
if (!transa & !transb)
{
for (l = ai1; l <= ai2; l++)
{
for (r = bi1; r <= bi2; r++)
{
v = alpha * a[l, aj1 + r - bi1];
k = ci1 + l - ai1;
i1_ = (bj1) - (cj1);
for (i_ = cj1; i_ <= cj2; i_++)
{
c[k, i_] = c[k, i_] + v * b[r, i_ + i1_];
}
}
}
return;
}
//
// A*B'
//
if (!transa & transb)
{
if (arows * acols < brows * bcols)
{
for (r = bi1; r <= bi2; r++)
{
for (l = ai1; l <= ai2; l++)
{
i1_ = (bj1) - (aj1);
v = 0.0;
for (i_ = aj1; i_ <= aj2; i_++)
{
v += a[l, i_] * b[r, i_ + i1_];
}
c[ci1 + l - ai1, cj1 + r - bi1] = c[ci1 + l - ai1, cj1 + r - bi1] + alpha * v;
}
}
return;
}
else
{
for (l = ai1; l <= ai2; l++)
{
for (r = bi1; r <= bi2; r++)
{
i1_ = (bj1) - (aj1);
v = 0.0;
for (i_ = aj1; i_ <= aj2; i_++)
{
v += a[l, i_] * b[r, i_ + i1_];
}
c[ci1 + l - ai1, cj1 + r - bi1] = c[ci1 + l - ai1, cj1 + r - bi1] + alpha * v;
}
}
return;
}
}
//
// A'*B
//
if (transa & !transb)
{
for (l = aj1; l <= aj2; l++)
{
for (r = bi1; r <= bi2; r++)
{
v = alpha * a[ai1 + r - bi1, l];
k = ci1 + l - aj1;
i1_ = (bj1) - (cj1);
for (i_ = cj1; i_ <= cj2; i_++)
{
c[k, i_] = c[k, i_] + v * b[r, i_ + i1_];
}
}
}
return;
}
//
// A'*B'
//
if (transa & transb)
{
if (arows * acols < brows * bcols)
{
for (r = bi1; r <= bi2; r++)
{
for (i = 1; i <= crows; i++)
{
work[i] = 0.0;
}
for (l = ai1; l <= ai2; l++)
{
v = alpha * b[r, bj1 + l - ai1];
k = cj1 + r - bi1;
i1_ = (aj1) - (1);
for (i_ = 1; i_ <= crows; i_++)
{
work[i_] = work[i_] + v * a[l, i_ + i1_];
}
}
i1_ = (1) - (ci1);
for (i_ = ci1; i_ <= ci2; i_++)
{
c[i_, k] = c[i_, k] + work[i_ + i1_];
}
}
return;
}
else
{
for (l = aj1; l <= aj2; l++)
{
k = ai2 - ai1 + 1;
i1_ = (ai1) - (1);
for (i_ = 1; i_ <= k; i_++)
{
work[i_] = a[i_ + i1_, l];
}
for (r = bi1; r <= bi2; r++)
{
i1_ = (bj1) - (1);
v = 0.0;
for (i_ = 1; i_ <= k; i_++)
{
v += work[i_] * b[r, i_ + i1_];
}
c[ci1 + l - aj1, cj1 + r - bi1] = c[ci1 + l - aj1, cj1 + r - bi1] + alpha * v;
}
}
return;
}
}
}
}
}
| |
namespace RealArtists.ChargeBee.Models {
using System;
using System.ComponentModel;
using System.Net.Http;
using RealArtists.ChargeBee.Api;
using RealArtists.ChargeBee.Internal;
using RealArtists.ChargeBee.Models.Enums;
public class PaymentSourceActions : ApiResourceActions {
public PaymentSourceActions(ChargeBeeApi api) : base(api) { }
public PaymentSource.CreateUsingTempTokenRequest CreateUsingTempToken() {
string url = BuildUrl("payment_sources", "create_using_temp_token");
return new PaymentSource.CreateUsingTempTokenRequest(Api, url, HttpMethod.Post);
}
public PaymentSource.CreateUsingPermanentTokenRequest CreateUsingPermanentToken() {
string url = BuildUrl("payment_sources", "create_using_permanent_token");
return new PaymentSource.CreateUsingPermanentTokenRequest(Api, url, HttpMethod.Post);
}
public PaymentSource.CreateCardRequest CreateCard() {
string url = BuildUrl("payment_sources", "create_card");
return new PaymentSource.CreateCardRequest(Api, url, HttpMethod.Post);
}
public PaymentSource.UpdateCardRequest UpdateCard(string id) {
string url = BuildUrl("payment_sources", id, "update_card");
return new PaymentSource.UpdateCardRequest(Api, url, HttpMethod.Post);
}
public EntityRequest<Type> Retrieve(string id) {
string url = BuildUrl("payment_sources", id);
return new EntityRequest<Type>(Api, url, HttpMethod.Get);
}
public PaymentSource.PaymentSourceListRequest List() {
string url = BuildUrl("payment_sources");
return new PaymentSource.PaymentSourceListRequest(Api, url);
}
public PaymentSource.SwitchGatewayAccountRequest SwitchGatewayAccount(string id) {
string url = BuildUrl("payment_sources", id, "switch_gateway_account");
return new PaymentSource.SwitchGatewayAccountRequest(Api, url, HttpMethod.Post);
}
public PaymentSource.ExportPaymentSourceRequest ExportPaymentSource(string id) {
string url = BuildUrl("payment_sources", id, "export_payment_source");
return new PaymentSource.ExportPaymentSourceRequest(Api, url, HttpMethod.Post);
}
public EntityRequest<Type> Delete(string id) {
string url = BuildUrl("payment_sources", id, "delete");
return new EntityRequest<Type>(Api, url, HttpMethod.Post);
}
}
public class PaymentSource : Resource {
public string Id {
get { return GetValue<string>("id", true); }
}
public string CustomerId {
get { return GetValue<string>("customer_id", true); }
}
public TypeEnum PaymentSourceType {
get { return GetEnum<TypeEnum>("type", true); }
}
public string ReferenceId {
get { return GetValue<string>("reference_id", true); }
}
public StatusEnum Status {
get { return GetEnum<StatusEnum>("status", true); }
}
public GatewayEnum Gateway {
get { return GetEnum<GatewayEnum>("gateway", true); }
}
public string GatewayAccountId {
get { return GetValue<string>("gateway_account_id", false); }
}
public string IpAddress {
get { return GetValue<string>("ip_address", false); }
}
public string IssuingCountry {
get { return GetValue<string>("issuing_country", false); }
}
public PaymentSourceCard Card {
get { return GetSubResource<PaymentSourceCard>("card"); }
}
public PaymentSourceBankAccount BankAccount {
get { return GetSubResource<PaymentSourceBankAccount>("bank_account"); }
}
public PaymentSourceAmazonPayment AmazonPayment {
get { return GetSubResource<PaymentSourceAmazonPayment>("amazon_payment"); }
}
public PaymentSourcePaypal Paypal {
get { return GetSubResource<PaymentSourcePaypal>("paypal"); }
}
public class CreateUsingTempTokenRequest : EntityRequest<CreateUsingTempTokenRequest> {
public CreateUsingTempTokenRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public CreateUsingTempTokenRequest CustomerId(string customerId) {
_params.Add("customer_id", customerId);
return this;
}
public CreateUsingTempTokenRequest GatewayAccountId(string gatewayAccountId) {
_params.AddOpt("gateway_account_id", gatewayAccountId);
return this;
}
public CreateUsingTempTokenRequest Type(ChargeBee.Models.Enums.TypeEnum type) {
_params.Add("type", type);
return this;
}
public CreateUsingTempTokenRequest TmpToken(string tmpToken) {
_params.Add("tmp_token", tmpToken);
return this;
}
public CreateUsingTempTokenRequest ReplacePrimaryPaymentSource(bool replacePrimaryPaymentSource) {
_params.AddOpt("replace_primary_payment_source", replacePrimaryPaymentSource);
return this;
}
}
public class CreateUsingPermanentTokenRequest : EntityRequest<CreateUsingPermanentTokenRequest> {
public CreateUsingPermanentTokenRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public CreateUsingPermanentTokenRequest CustomerId(string customerId) {
_params.Add("customer_id", customerId);
return this;
}
public CreateUsingPermanentTokenRequest Type(ChargeBee.Models.Enums.TypeEnum type) {
_params.Add("type", type);
return this;
}
public CreateUsingPermanentTokenRequest GatewayAccountId(string gatewayAccountId) {
_params.AddOpt("gateway_account_id", gatewayAccountId);
return this;
}
public CreateUsingPermanentTokenRequest ReferenceId(string referenceId) {
_params.Add("reference_id", referenceId);
return this;
}
public CreateUsingPermanentTokenRequest ReplacePrimaryPaymentSource(bool replacePrimaryPaymentSource) {
_params.AddOpt("replace_primary_payment_source", replacePrimaryPaymentSource);
return this;
}
}
public class CreateCardRequest : EntityRequest<CreateCardRequest> {
public CreateCardRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public CreateCardRequest CustomerId(string customerId) {
_params.Add("customer_id", customerId);
return this;
}
public CreateCardRequest ReplacePrimaryPaymentSource(bool replacePrimaryPaymentSource) {
_params.AddOpt("replace_primary_payment_source", replacePrimaryPaymentSource);
return this;
}
public CreateCardRequest CardGatewayAccountId(string cardGatewayAccountId) {
_params.AddOpt("card[gateway_account_id]", cardGatewayAccountId);
return this;
}
public CreateCardRequest CardFirstName(string cardFirstName) {
_params.AddOpt("card[first_name]", cardFirstName);
return this;
}
public CreateCardRequest CardLastName(string cardLastName) {
_params.AddOpt("card[last_name]", cardLastName);
return this;
}
public CreateCardRequest CardNumber(string cardNumber) {
_params.Add("card[number]", cardNumber);
return this;
}
public CreateCardRequest CardExpiryMonth(int cardExpiryMonth) {
_params.Add("card[expiry_month]", cardExpiryMonth);
return this;
}
public CreateCardRequest CardExpiryYear(int cardExpiryYear) {
_params.Add("card[expiry_year]", cardExpiryYear);
return this;
}
public CreateCardRequest CardCvv(string cardCvv) {
_params.AddOpt("card[cvv]", cardCvv);
return this;
}
public CreateCardRequest CardBillingAddr1(string cardBillingAddr1) {
_params.AddOpt("card[billing_addr1]", cardBillingAddr1);
return this;
}
public CreateCardRequest CardBillingAddr2(string cardBillingAddr2) {
_params.AddOpt("card[billing_addr2]", cardBillingAddr2);
return this;
}
public CreateCardRequest CardBillingCity(string cardBillingCity) {
_params.AddOpt("card[billing_city]", cardBillingCity);
return this;
}
public CreateCardRequest CardBillingStateCode(string cardBillingStateCode) {
_params.AddOpt("card[billing_state_code]", cardBillingStateCode);
return this;
}
public CreateCardRequest CardBillingState(string cardBillingState) {
_params.AddOpt("card[billing_state]", cardBillingState);
return this;
}
public CreateCardRequest CardBillingZip(string cardBillingZip) {
_params.AddOpt("card[billing_zip]", cardBillingZip);
return this;
}
public CreateCardRequest CardBillingCountry(string cardBillingCountry) {
_params.AddOpt("card[billing_country]", cardBillingCountry);
return this;
}
}
public class UpdateCardRequest : EntityRequest<UpdateCardRequest> {
public UpdateCardRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public UpdateCardRequest GatewayMetaData(string gatewayMetaData) {
_params.AddOpt("gateway_meta_data", gatewayMetaData);
return this;
}
public UpdateCardRequest CardFirstName(string cardFirstName) {
_params.AddOpt("card[first_name]", cardFirstName);
return this;
}
public UpdateCardRequest CardLastName(string cardLastName) {
_params.AddOpt("card[last_name]", cardLastName);
return this;
}
public UpdateCardRequest CardExpiryMonth(int cardExpiryMonth) {
_params.AddOpt("card[expiry_month]", cardExpiryMonth);
return this;
}
public UpdateCardRequest CardExpiryYear(int cardExpiryYear) {
_params.AddOpt("card[expiry_year]", cardExpiryYear);
return this;
}
public UpdateCardRequest CardBillingAddr1(string cardBillingAddr1) {
_params.AddOpt("card[billing_addr1]", cardBillingAddr1);
return this;
}
public UpdateCardRequest CardBillingAddr2(string cardBillingAddr2) {
_params.AddOpt("card[billing_addr2]", cardBillingAddr2);
return this;
}
public UpdateCardRequest CardBillingCity(string cardBillingCity) {
_params.AddOpt("card[billing_city]", cardBillingCity);
return this;
}
public UpdateCardRequest CardBillingZip(string cardBillingZip) {
_params.AddOpt("card[billing_zip]", cardBillingZip);
return this;
}
public UpdateCardRequest CardBillingStateCode(string cardBillingStateCode) {
_params.AddOpt("card[billing_state_code]", cardBillingStateCode);
return this;
}
public UpdateCardRequest CardBillingState(string cardBillingState) {
_params.AddOpt("card[billing_state]", cardBillingState);
return this;
}
public UpdateCardRequest CardBillingCountry(string cardBillingCountry) {
_params.AddOpt("card[billing_country]", cardBillingCountry);
return this;
}
}
public class PaymentSourceListRequest : ListRequestBase<PaymentSourceListRequest> {
public PaymentSourceListRequest(ChargeBeeApi api, string url)
: base(api, url) {
}
public StringFilter<PaymentSourceListRequest> CustomerId() {
return new StringFilter<PaymentSourceListRequest>("customer_id", this).SupportsMultiOperators(true);
}
public EnumFilter<ChargeBee.Models.Enums.TypeEnum, PaymentSourceListRequest> Type() {
return new EnumFilter<ChargeBee.Models.Enums.TypeEnum, PaymentSourceListRequest>("type", this);
}
public EnumFilter<PaymentSource.StatusEnum, PaymentSourceListRequest> Status() {
return new EnumFilter<PaymentSource.StatusEnum, PaymentSourceListRequest>("status", this);
}
}
public class SwitchGatewayAccountRequest : EntityRequest<SwitchGatewayAccountRequest> {
public SwitchGatewayAccountRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public SwitchGatewayAccountRequest GatewayAccountId(string gatewayAccountId) {
_params.Add("gateway_account_id", gatewayAccountId);
return this;
}
}
public class ExportPaymentSourceRequest : EntityRequest<ExportPaymentSourceRequest> {
public ExportPaymentSourceRequest(ChargeBeeApi api, string url, HttpMethod method)
: base(api, url, method) {
}
public ExportPaymentSourceRequest GatewayAccountId(string gatewayAccountId) {
_params.Add("gateway_account_id", gatewayAccountId);
return this;
}
}
public enum StatusEnum {
Unknown,
[Description("valid")]
Valid,
[Description("expiring")]
Expiring,
[Description("expired")]
Expired,
[Description("invalid")]
Invalid,
[Description("pending_verification")]
PendingVerification,
}
public class PaymentSourceCard : Resource {
public enum BrandEnum {
Unknown,
[Description("visa")]
Visa,
[Description("mastercard")]
Mastercard,
[Description("american_express")]
AmericanExpress,
[Description("discover")]
Discover,
[Description("jcb")]
Jcb,
[Description("diners_club")]
DinersClub,
[Description("other")]
Other,
}
public enum FundingTypeEnum {
Unknown,
[Description("credit")]
Credit,
[Description("debit")]
Debit,
[Description("prepaid")]
Prepaid,
[Description("not_known")]
NotKnown,
[Description("not_applicable")]
NotApplicable,
}
public string FirstName() {
return GetValue<string>("first_name", false);
}
public string LastName() {
return GetValue<string>("last_name", false);
}
public string Iin() {
return GetValue<string>("iin", true);
}
public string Last4() {
return GetValue<string>("last4", true);
}
public BrandEnum Brand() {
return GetEnum<BrandEnum>("brand", true);
}
public FundingTypeEnum FundingType() {
return GetEnum<FundingTypeEnum>("funding_type", true);
}
public int ExpiryMonth() {
return GetValue<int>("expiry_month", true);
}
public int ExpiryYear() {
return GetValue<int>("expiry_year", true);
}
public string BillingAddr1() {
return GetValue<string>("billing_addr1", false);
}
public string BillingAddr2() {
return GetValue<string>("billing_addr2", false);
}
public string BillingCity() {
return GetValue<string>("billing_city", false);
}
public string BillingStateCode() {
return GetValue<string>("billing_state_code", false);
}
public string BillingState() {
return GetValue<string>("billing_state", false);
}
public string BillingCountry() {
return GetValue<string>("billing_country", false);
}
public string BillingZip() {
return GetValue<string>("billing_zip", false);
}
public string MaskedNumber() {
return GetValue<string>("masked_number", false);
}
}
public class PaymentSourceBankAccount : Resource {
public enum AccountTypeEnum {
Unknown,
[Description("checking")]
Checking,
[Description("savings")]
Savings,
}
public string NameOnAccount() {
return GetValue<string>("name_on_account", false);
}
public string BankName() {
return GetValue<string>("bank_name", false);
}
public string MandateId() {
return GetValue<string>("mandate_id", false);
}
public AccountTypeEnum? AccountType() {
return GetEnum<AccountTypeEnum>("account_type", false);
}
}
public class PaymentSourceAmazonPayment : Resource {
public string Email() {
return GetValue<string>("email", false);
}
public string AgreementId() {
return GetValue<string>("agreement_id", false);
}
}
public class PaymentSourcePaypal : Resource {
public string Email() {
return GetValue<string>("email", false);
}
public string AgreementId() {
return GetValue<string>("agreement_id", false);
}
}
}
}
| |
#region License, Terms and Conditions
//
// Jayrock - JSON and JSON-RPC for Microsoft .NET Framework and Mono
// Written by Atif Aziz (atif.aziz@skybow.com)
// Copyright (c) 2005 Atif Aziz. All rights reserved.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License as published by the Free
// Software Foundation; either version 2.1 of the License, or (at your option)
// any later version.
//
// This library is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
// details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
#endregion
namespace Jayrock.Json
{
#region Imports
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
#endregion
public sealed class JsonString
{
/// <summary>
/// Produces a string in double quotes with backslash sequences in all
/// the right places.
/// </summary>
/// <returns>A correctly formatted string for insertion in a JSON
/// message.
/// </returns>
/// <remarks>
/// Public Domain 2002 JSON.org, ported to C# by Are Bjolseth
/// (teleplan.no) and nearly re-written by Atif Aziz (www.raboof.com)
/// </remarks>
public static string Enquote(string s)
{
if (s == null || s.Length == 0)
return "\"\"";
return Enquote(s, null).ToString();
}
public static StringBuilder Enquote(string s, StringBuilder sb)
{
int length = Mask.NullString(s).Length;
if (sb == null)
sb = new StringBuilder(length + 4);
sb.Append('"');
char last;
char ch = '\0';
for (int index = 0; index < length; index++)
{
last = ch;
ch = s[index];
switch (ch)
{
case '\\':
case '"':
{
sb.Append('\\');
sb.Append(ch);
break;
}
case '/':
{
if (last == '<')
sb.Append('\\');
sb.Append(ch);
break;
}
case '\b': sb.Append("\\b"); break;
case '\t': sb.Append("\\t"); break;
case '\n': sb.Append("\\n"); break;
case '\f': sb.Append("\\f"); break;
case '\r': sb.Append("\\r"); break;
default:
{
if (ch < ' ')
{
sb.Append("\\u");
sb.Append(((int) ch).ToString("x4", CultureInfo.InvariantCulture));
}
else
{
sb.Append(ch);
}
break;
}
}
}
return sb.Append('"');
}
/// <summary>
/// Return the characters up to the next close quote character.
/// Backslash processing is done. The formal JSON format does not
/// allow strings in single quotes, but an implementation is allowed to
/// accept them.
/// </summary>
/// <param name="quote">The quoting character, either " or '</param>
/// <returns>A String.</returns>
// TODO: Consider rendering Dequote public
internal static string Dequote(BufferedCharReader input, char quote)
{
return Dequote(input, quote, null).ToString();
}
internal static StringBuilder Dequote(BufferedCharReader input, char quote, StringBuilder output)
{
Debug.Assert(input != null);
if (output == null)
output = new StringBuilder();
char[] hexDigits = null;
while (true)
{
char ch = input.Next();
if ((ch == BufferedCharReader.EOF) || (ch == '\n') || (ch == '\r'))
throw new FormatException("Unterminated string.");
if (ch == '\\')
{
ch = input.Next();
switch (ch)
{
case 'b': output.Append('\b'); break; // Backspace
case 't': output.Append('\t'); break; // Horizontal tab
case 'n': output.Append('\n'); break; // Newline
case 'f': output.Append('\f'); break; // Form feed
case 'r': output.Append('\r'); break; // Carriage return
case 'u':
{
if (hexDigits == null)
hexDigits = new char[4];
output.Append(ParseHex(input, hexDigits));
break;
}
default:
output.Append(ch);
break;
}
}
else
{
if (ch == quote)
return output;
output.Append(ch);
}
}
}
/// <summary>
/// Eats the next four characters, assuming hex digits, and converts
/// into the represented character value.
/// </summary>
/// <returns>The parsed character.</returns>
private static char ParseHex(BufferedCharReader input, char[] hexDigits)
{
Debug.Assert(input != null);
Debug.Assert(hexDigits != null);
Debug.Assert(hexDigits.Length == 4);
hexDigits[0] = input.Next();
hexDigits[1] = input.Next();
hexDigits[2] = input.Next();
hexDigits[3] = input.Next();
return (char) ushort.Parse(new string(hexDigits), NumberStyles.HexNumber);
}
private JsonString()
{
throw new NotSupportedException();
}
}
}
| |
/*
* 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 OpenMetaverse.StructuredData;
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace OpenSim.Framework
{
/// <summary>
/// This class stores and retrieves dynamic attributes.
/// </summary>
/// <remarks>
/// Modules that want to use dynamic attributes need to do so in a private data store
/// which is accessed using a unique name. DAMap provides access to the data stores,
/// each of which is an OSDMap. Modules are free to store any type of data they want
/// within their data store. However, avoid storing large amounts of data because that
/// would slow down database access.
/// </remarks>
public class DAMap : IXmlSerializable
{
// private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private static readonly int MIN_NAMESPACE_LENGTH = 4;
private OSDMap m_map = new OSDMap();
// WARNING: this is temporary for experimentation only, it will be removed!!!!
public OSDMap TopLevelMap
{
get { return m_map; }
set { m_map = value; }
}
public XmlSchema GetSchema() { return null; }
public static DAMap FromXml(string rawXml)
{
DAMap map = new DAMap();
map.ReadXml(rawXml);
return map;
}
public void ReadXml(XmlReader reader)
{
ReadXml(reader.ReadInnerXml());
}
public void ReadXml(string rawXml)
{
// System.Console.WriteLine("Trying to deserialize [{0}]", rawXml);
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(rawXml);
lock (this)
{
m_map = map;
SanitiseMap(this);
}
}
public void WriteXml(XmlWriter writer)
{
writer.WriteRaw(ToXml());
}
public string ToXml()
{
OSDMap map;
lock (this)
{
map = m_map;
}
return OSDParser.SerializeLLSDXmlString(map);
}
public void CopyFrom(DAMap other)
{
// Deep copy
string data = null;
OSDMap othermap = null;
lock (other)
{
if (other.CountNamespaces > 0)
{
othermap = other.m_map;
}
}
if(othermap != null)
{
data = OSDParser.SerializeLLSDXmlString(othermap);
}
if (data == null)
Clear();
else
{
OSDMap map = (OSDMap)OSDParser.DeserializeLLSDXml(data);
lock (this)
{
m_map = map;
}
}
}
/// <summary>
/// Sanitise the map to remove any namespaces or stores that are not OSDMap.
/// </summary>
/// <param name='map'>
/// </param>
public static void SanitiseMap(DAMap daMap)
{
List<string> keysToRemove = null;
OSDMap namespacesMap = daMap.m_map;
foreach (string key in namespacesMap.Keys)
{
// Console.WriteLine("Processing ns {0}", key);
if (!(namespacesMap[key] is OSDMap))
{
if (keysToRemove == null)
keysToRemove = new List<string>();
keysToRemove.Add(key);
}
}
if (keysToRemove != null)
{
foreach (string key in keysToRemove)
{
// Console.WriteLine ("Removing bad ns {0}", key);
namespacesMap.Remove(key);
}
}
foreach (OSD nsOsd in namespacesMap.Values)
{
OSDMap nsOsdMap = (OSDMap)nsOsd;
keysToRemove = null;
foreach (string key in nsOsdMap.Keys)
{
if (!(nsOsdMap[key] is OSDMap))
{
if (keysToRemove == null)
keysToRemove = new List<string>();
keysToRemove.Add(key);
}
}
if (keysToRemove != null)
foreach (string key in keysToRemove)
nsOsdMap.Remove(key);
}
}
/// <summary>
/// Get the number of namespaces
/// </summary>
public int CountNamespaces { get { lock (this) { return m_map.Count; } } }
/// <summary>
/// Get the number of stores.
/// </summary>
public int CountStores
{
get
{
int count = 0;
lock (this)
{
foreach (OSD osdNamespace in m_map)
{
count += ((OSDMap)osdNamespace).Count;
}
}
return count;
}
}
/// <summary>
/// Retrieve a Dynamic Attribute store
/// </summary>
/// <param name="ns">namespace for the store - use "OpenSim" for in-core modules</param>
/// <param name="storeName">name of the store within the namespace</param>
/// <returns>an OSDMap representing the stored data, or null if not found</returns>
public OSDMap GetStore(string ns, string storeName)
{
OSD namespaceOsd;
lock (this)
{
if (!m_map.TryGetValue(ns, out namespaceOsd))
{
namespaceOsd = null;
}
}
if(namespaceOsd != null)
{
OSD store;
if (((OSDMap)namespaceOsd).TryGetValue(storeName, out store))
return (OSDMap)store;
}
return null;
}
/// <summary>
/// Saves a Dynamic attribute store
/// </summary>
/// <param name="ns">namespace for the store - use "OpenSim" for in-core modules</param>
/// <param name="storeName">name of the store within the namespace</param>
/// <param name="store">an OSDMap representing the data to store</param>
public void SetStore(string ns, string storeName, OSDMap store)
{
ValidateNamespace(ns);
OSDMap nsMap;
lock (this)
{
if (!m_map.ContainsKey(ns))
{
nsMap = new OSDMap();
m_map[ns] = nsMap;
}
nsMap = (OSDMap)m_map[ns];
// m_log.DebugFormat("[DA MAP]: Setting store to {0}:{1}", ns, storeName);
nsMap[storeName] = store;
}
}
/// <summary>
/// Validate the key used for storing separate data stores.
/// </summary>
/// <param name='key'></param>
public static void ValidateNamespace(string ns)
{
if (ns.Length < MIN_NAMESPACE_LENGTH)
throw new Exception("Minimum namespace length is " + MIN_NAMESPACE_LENGTH);
}
public bool ContainsStore(string ns, string storeName)
{
OSD namespaceOsd;
lock (this)
{
if (!m_map.TryGetValue(ns, out namespaceOsd))
{
namespaceOsd = null;
}
}
if(namespaceOsd != null)
{
return ((OSDMap)namespaceOsd).ContainsKey(storeName);
}
return false;
}
public bool TryGetStore(string ns, string storeName, out OSDMap store)
{
OSD namespaceOsd;
lock (this)
{
if (!m_map.TryGetValue(ns, out namespaceOsd))
{
namespaceOsd = null;
}
}
if(namespaceOsd != null)
{
OSD storeOsd;
bool result = ((OSDMap)namespaceOsd).TryGetValue(storeName, out storeOsd);
store = (OSDMap)storeOsd;
return result;
}
store = null;
return false;
}
public void Clear()
{
lock (this)
m_map.Clear();
}
public bool RemoveStore(string ns, string storeName)
{
OSD namespaceOsd;
lock (this)
{
if (m_map.TryGetValue(ns, out namespaceOsd))
{
namespaceOsd = null;
}
}
if(null != namespaceOsd)
{
OSDMap namespaceOsdMap = (OSDMap)namespaceOsd;
namespaceOsdMap.Remove(storeName);
// Don't keep empty namespaces around
if (namespaceOsdMap.Count <= 0)
m_map.Remove(ns);
}
return false;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CredentialCache.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Net {
using System.Net.Sockets;
using System.Collections;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Globalization;
// More sophisticated password cache that stores multiple
// name-password pairs and associates these with host/realm
/// <devdoc>
/// <para>Provides storage for multiple credentials.</para>
/// </devdoc>
public class CredentialCache : ICredentials, ICredentialsByHost, IEnumerable {
// fields
private Hashtable cache = new Hashtable();
private Hashtable cacheForHosts = new Hashtable();
internal int m_version;
private int m_NumbDefaultCredInCache = 0;
// [thread token optimization] The resulting counter of default credential resided in the cache.
internal bool IsDefaultInCache {
get {
return m_NumbDefaultCredInCache != 0;
}
}
// constructors
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Net.CredentialCache'/> class.
/// </para>
/// </devdoc>
public CredentialCache() {
}
// properties
// methods
/// <devdoc>
/// <para>Adds a <see cref='System.Net.NetworkCredential'/>
/// instance to the credential cache.</para>
/// </devdoc>
// UEUE
public void Add(Uri uriPrefix, string authType, NetworkCredential cred) {
//
// parameter validation
//
if (uriPrefix==null) {
throw new ArgumentNullException("uriPrefix");
}
if (authType==null) {
throw new ArgumentNullException("authType");
}
if ((cred is SystemNetworkCredential)
#if !FEATURE_PAL
&& !((string.Compare(authType, NtlmClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
|| (DigestClient.WDigestAvailable && (string.Compare(authType, DigestClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
|| (string.Compare(authType, KerberosClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
|| (string.Compare(authType, NegotiateClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
#endif
) {
throw new ArgumentException(SR.GetString(SR.net_nodefaultcreds, authType), "authType");
}
++m_version;
CredentialKey key = new CredentialKey(uriPrefix, authType);
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + cred.Domain + "],[" + cred.UserName + "]");
cache.Add(key, cred);
if (cred is SystemNetworkCredential) {
++m_NumbDefaultCredInCache;
}
}
public void Add(string host, int port, string authenticationType, NetworkCredential credential) {
//
// parameter validation
//
if (host==null) {
throw new ArgumentNullException("host");
}
if (authenticationType==null) {
throw new ArgumentNullException("authenticationType");
}
if (host.Length == 0) {
throw new ArgumentException(SR.GetString(SR.net_emptystringcall,"host"));
}
if (port < 0) {
throw new ArgumentOutOfRangeException("port");
}
if ((credential is SystemNetworkCredential)
#if !FEATURE_PAL
&& !((string.Compare(authenticationType, NtlmClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
|| (DigestClient.WDigestAvailable && (string.Compare(authenticationType, DigestClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
|| (string.Compare(authenticationType, KerberosClient.AuthType, StringComparison.OrdinalIgnoreCase)==0)
|| (string.Compare(authenticationType, NegotiateClient.AuthType, StringComparison.OrdinalIgnoreCase)==0))
#endif
) {
throw new ArgumentException(SR.GetString(SR.net_nodefaultcreds, authenticationType), "authenticationType");
}
++m_version;
CredentialHostKey key = new CredentialHostKey(host,port, authenticationType);
GlobalLog.Print("CredentialCache::Add() Adding key:[" + key.ToString() + "], cred:[" + credential.Domain + "],[" + credential.UserName + "]");
cacheForHosts.Add(key, credential);
if (credential is SystemNetworkCredential) {
++m_NumbDefaultCredInCache;
}
}
/// <devdoc>
/// <para>Removes a <see cref='System.Net.NetworkCredential'/>
/// instance from the credential cache.</para>
/// </devdoc>
public void Remove(Uri uriPrefix, string authType) {
if (uriPrefix==null || authType==null) {
// these couldn't possibly have been inserted into
// the cache because of the test in Add()
return;
}
++m_version;
CredentialKey key = new CredentialKey(uriPrefix, authType);
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
if (cache[key] is SystemNetworkCredential) {
--m_NumbDefaultCredInCache;
}
cache.Remove(key);
}
public void Remove(string host, int port, string authenticationType) {
if (host==null || authenticationType==null) {
// these couldn't possibly have been inserted into
// the cache because of the test in Add()
return;
}
if (port < 0) {
return;
}
++m_version;
CredentialHostKey key = new CredentialHostKey(host, port, authenticationType);
GlobalLog.Print("CredentialCache::Remove() Removing key:[" + key.ToString() + "]");
if (cacheForHosts[key] is SystemNetworkCredential) {
--m_NumbDefaultCredInCache;
}
cacheForHosts.Remove(key);
}
/// <devdoc>
/// <para>
/// Returns the <see cref='System.Net.NetworkCredential'/>
/// instance associated with the supplied Uri and
/// authentication type.
/// </para>
/// </devdoc>
public NetworkCredential GetCredential(Uri uriPrefix, string authType) {
if (uriPrefix==null)
throw new ArgumentNullException("uriPrefix");
if (authType==null)
throw new ArgumentNullException("authType");
GlobalLog.Print("CredentialCache::GetCredential(uriPrefix=\"" + uriPrefix + "\", authType=\"" + authType + "\")");
int longestMatchPrefix = -1;
NetworkCredential mostSpecificMatch = null;
IDictionaryEnumerator credEnum = cache.GetEnumerator();
//
// Enumerate through every credential in the cache
//
while (credEnum.MoveNext()) {
CredentialKey key = (CredentialKey)credEnum.Key;
//
// Determine if this credential is applicable to the current Uri/AuthType
//
if (key.Match(uriPrefix, authType)) {
int prefixLen = key.UriPrefixLength;
//
// Check if the match is better than the current-most-specific match
//
if (prefixLen > longestMatchPrefix) {
//
// Yes-- update the information about currently preferred match
//
longestMatchPrefix = prefixLen;
mostSpecificMatch = (NetworkCredential)credEnum.Value;
}
}
}
GlobalLog.Print("CredentialCache::GetCredential returning " + ((mostSpecificMatch==null)?"null":"(" + mostSpecificMatch.UserName + ":" + mostSpecificMatch.Domain + ")"));
return mostSpecificMatch;
}
public NetworkCredential GetCredential(string host, int port, string authenticationType) {
if (host==null) {
throw new ArgumentNullException("host");
}
if (authenticationType==null){
throw new ArgumentNullException("authenticationType");
}
if (host.Length == 0) {
throw new ArgumentException(SR.GetString(SR.net_emptystringcall, "host"));
}
if (port < 0) {
throw new ArgumentOutOfRangeException("port");
}
GlobalLog.Print("CredentialCache::GetCredential(host=\"" + host + ":" + port.ToString() +"\", authenticationType=\"" + authenticationType + "\")");
NetworkCredential match = null;
IDictionaryEnumerator credEnum = cacheForHosts.GetEnumerator();
//
// Enumerate through every credential in the cache
//
while (credEnum.MoveNext()) {
CredentialHostKey key = (CredentialHostKey)credEnum.Key;
//
// Determine if this credential is applicable to the current Uri/AuthType
//
if (key.Match(host, port, authenticationType)) {
match = (NetworkCredential)credEnum.Value;
}
}
GlobalLog.Print("CredentialCache::GetCredential returning " + ((match==null)?"null":"(" + match.UserName + ":" + match.Domain + ")"));
return match;
}
/// <devdoc>
/// [To be supplied]
/// </devdoc>
//
// IEnumerable interface
//
public IEnumerator GetEnumerator() {
return new CredentialEnumerator(this, cache ,cacheForHosts, m_version);
}
/// <devdoc>
/// <para>
/// Gets
/// the default system credentials from the <see cref='System.Net.CredentialCache'/>.
/// </para>
/// </devdoc>
public static ICredentials DefaultCredentials {
get {
//This check will not allow to use local user credentials at will.
//Hence the username will not be exposed to the network
new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME").Demand();
return SystemNetworkCredential.defaultCredential;
}
}
public static NetworkCredential DefaultNetworkCredentials {
get {
//This check will not allow to use local user credentials at will.
//Hence the username will not be exposed to the network
new EnvironmentPermission(EnvironmentPermissionAccess.Read, "USERNAME").Demand();
return SystemNetworkCredential.defaultCredential;
}
}
private class CredentialEnumerator : IEnumerator {
// fields
private CredentialCache m_cache;
private ICredentials[] m_array;
private int m_index = -1;
private int m_version;
// constructors
internal CredentialEnumerator(CredentialCache cache, Hashtable table, Hashtable hostTable, int version) {
m_cache = cache;
m_array = new ICredentials[table.Count + hostTable.Count];
table.Values.CopyTo(m_array, 0);
hostTable.Values.CopyTo(m_array, table.Count);
m_version = version;
}
// IEnumerator interface
// properties
object IEnumerator.Current {
get {
if (m_index < 0 || m_index >= m_array.Length) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumOpCantHappen));
}
if (m_version != m_cache.m_version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
return m_array[m_index];
}
}
// methods
bool IEnumerator.MoveNext() {
if (m_version != m_cache.m_version) {
throw new InvalidOperationException(SR.GetString(SR.InvalidOperation_EnumFailedVersion));
}
if (++m_index < m_array.Length) {
return true;
}
m_index = m_array.Length;
return false;
}
void IEnumerator.Reset() {
m_index = -1;
}
} // class CredentialEnumerator
} // class CredentialCache
// Abstraction for credentials in password-based
// authentication schemes (basic, digest, NTLM, Kerberos)
// Note this is not applicable to public-key based
// systems such as SSL client authentication
// "Password" here may be the clear text password or it
// could be a one-way hash that is sufficient to
// authenticate, as in HTTP/1.1 digest.
//
// Object representing default credentials
//
internal class SystemNetworkCredential : NetworkCredential {
internal static readonly SystemNetworkCredential defaultCredential = new SystemNetworkCredential();
// We want reference equality to work. Making this private is a good way to guarantee that.
private SystemNetworkCredential() :
base(string.Empty, string.Empty, string.Empty) {
}
}
internal class CredentialHostKey {
internal string Host;
internal string AuthenticationType;
internal int Port;
internal CredentialHostKey(string host, int port, string authenticationType) {
Host = host;
Port = port;
AuthenticationType = authenticationType;
}
internal bool Match(string host, int port, string authenticationType) {
if (host==null || authenticationType==null) {
return false;
}
//
// If the protocols dont match this credential
// is not applicable for the given Uri
//
if (string.Compare(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) != 0) {
return false;
}
if (string.Compare(Host, host, StringComparison.OrdinalIgnoreCase ) != 0) {
return false;
}
if (port != Port) {
return false;
}
GlobalLog.Print("CredentialKey::Match(" + Host.ToString() + ":" + Port.ToString() +" & " + host.ToString() + ":" + port.ToString() + ")");
return true;
}
private int m_HashCode = 0;
private bool m_ComputedHashCode = false;
public override int GetHashCode() {
if (!m_ComputedHashCode) {
//
// compute HashCode on demand
//
m_HashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + Host.ToUpperInvariant().GetHashCode() + Port.GetHashCode();
m_ComputedHashCode = true;
}
return m_HashCode;
}
public override bool Equals(object comparand) {
CredentialHostKey comparedCredentialKey = comparand as CredentialHostKey;
if (comparand==null) {
//
// this covers also the compared==null case
//
return false;
}
bool equals =
(string.Compare(AuthenticationType, comparedCredentialKey.AuthenticationType, StringComparison.OrdinalIgnoreCase ) == 0) &&
(string.Compare(Host, comparedCredentialKey.Host, StringComparison.OrdinalIgnoreCase ) == 0) &&
Port == comparedCredentialKey.Port;
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + comparedCredentialKey.ToString() + ") returns " + equals.ToString());
return equals;
}
public override string ToString() {
return "[" + Host.Length.ToString(NumberFormatInfo.InvariantInfo) + "]:" + Host + ":" + Port.ToString(NumberFormatInfo.InvariantInfo) + ":" + ValidationHelper.ToString(AuthenticationType);
}
} // class CredentialKey
internal class CredentialKey {
internal Uri UriPrefix;
internal int UriPrefixLength = -1;
internal string AuthenticationType;
internal CredentialKey(Uri uriPrefix, string authenticationType) {
UriPrefix = uriPrefix;
UriPrefixLength = UriPrefix.ToString().Length;
AuthenticationType = authenticationType;
}
internal bool Match(Uri uri, string authenticationType) {
if (uri==null || authenticationType==null) {
return false;
}
//
// If the protocols dont match this credential
// is not applicable for the given Uri
//
if (string.Compare(authenticationType, AuthenticationType, StringComparison.OrdinalIgnoreCase) != 0) {
return false;
}
GlobalLog.Print("CredentialKey::Match(" + UriPrefix.ToString() + " & " + uri.ToString() + ")");
return IsPrefix(uri, UriPrefix);
}
//
// IsPrefix (Uri)
//
// Determines whether <prefixUri> is a prefix of this URI. A prefix
// match is defined as:
//
// scheme match
// + host match
// + port match, if any
// + <prefix> path is a prefix of <URI> path, if any
//
// Returns:
// True if <prefixUri> is a prefix of this URI
//
internal bool IsPrefix(Uri uri, Uri prefixUri) {
if (prefixUri.Scheme != uri.Scheme || prefixUri.Host != uri.Host || prefixUri.Port != uri.Port)
return false;
int prefixLen = prefixUri.AbsolutePath.LastIndexOf('/');
if (prefixLen > uri.AbsolutePath.LastIndexOf('/'))
return false;
return String.Compare(uri.AbsolutePath, 0, prefixUri.AbsolutePath, 0, prefixLen, StringComparison.OrdinalIgnoreCase ) == 0;
}
private int m_HashCode = 0;
private bool m_ComputedHashCode = false;
public override int GetHashCode() {
if (!m_ComputedHashCode) {
//
// compute HashCode on demand
//
m_HashCode = AuthenticationType.ToUpperInvariant().GetHashCode() + UriPrefixLength + UriPrefix.GetHashCode();
m_ComputedHashCode = true;
}
return m_HashCode;
}
public override bool Equals(object comparand) {
CredentialKey comparedCredentialKey = comparand as CredentialKey;
if (comparand==null) {
//
// this covers also the compared==null case
//
return false;
}
bool equals =
(string.Compare(AuthenticationType, comparedCredentialKey.AuthenticationType, StringComparison.OrdinalIgnoreCase ) == 0) &&
UriPrefix.Equals(comparedCredentialKey.UriPrefix);
GlobalLog.Print("CredentialKey::Equals(" + ToString() + ", " + comparedCredentialKey.ToString() + ") returns " + equals.ToString());
return equals;
}
public override string ToString() {
return "[" + UriPrefixLength.ToString(NumberFormatInfo.InvariantInfo) + "]:" + ValidationHelper.ToString(UriPrefix) + ":" + ValidationHelper.ToString(AuthenticationType);
}
} // class CredentialKey
} // namespace System.Net
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebApplication1.Areas.HelpPage.ModelDescriptions;
using WebApplication1.Areas.HelpPage.Models;
namespace WebApplication1.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
if (complexTypeDescription != null)
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
namespace FlatRedBall.Glue.StateInterpolation
{
public delegate float TweeningFunction(float timeElapsed, float start, float change, float duration);
public enum InterpolationType
{
Back,
Bounce,
Circular,
Cubic,
Elastic,
Exponential,
Linear,
Quadratic,
Quartic,
Quintic,
Sinusoidal
}
public enum Easing
{
In,
Out,
InOut
}
public class Tweener
{
public static TweeningFunction GetInterpolationFunction(InterpolationType type, Easing easing)
{
switch (type)
{
case InterpolationType.Back:
switch (easing)
{
case Easing.In:
return Back.EaseIn;
case Easing.Out:
return Back.EaseOut;
case Easing.InOut:
return Back.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Bounce:
switch (easing)
{
case Easing.In:
return Bounce.EaseIn;
case Easing.Out:
return Bounce.EaseOut;
case Easing.InOut:
return Bounce.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Circular:
switch (easing)
{
case Easing.In:
return Circular.EaseIn;
case Easing.Out:
return Circular.EaseOut;
case Easing.InOut:
return Circular.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Cubic:
switch (easing)
{
case Easing.In:
return Cubic.EaseIn;
case Easing.Out:
return Cubic.EaseOut;
case Easing.InOut:
return Cubic.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Elastic:
switch (easing)
{
case Easing.In:
return Elastic.EaseIn;
case Easing.Out:
return Elastic.EaseOut;
case Easing.InOut:
return Elastic.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Exponential:
switch (easing)
{
case Easing.In:
return Exponential.EaseIn;
case Easing.Out:
return Exponential.EaseOut;
case Easing.InOut:
return Exponential.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Linear:
switch (easing)
{
case Easing.In:
return Linear.EaseIn;
case Easing.Out:
return Linear.EaseOut;
case Easing.InOut:
return Linear.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Quadratic:
switch (easing)
{
case Easing.In:
return Quadratic.EaseIn;
case Easing.Out:
return Quadratic.EaseOut;
case Easing.InOut:
return Quadratic.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Quartic:
switch (easing)
{
case Easing.In:
return Quartic.EaseIn;
case Easing.Out:
return Quartic.EaseOut;
case Easing.InOut:
return Quartic.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Quintic:
switch (easing)
{
case Easing.In:
return Quintic.EaseIn;
case Easing.Out:
return Quintic.EaseOut;
case Easing.InOut:
return Quintic.EaseInOut;
default:
throw new Exception();
}
case InterpolationType.Sinusoidal:
switch (easing)
{
case Easing.In:
return Sinusoidal.EaseIn;
case Easing.Out:
return Sinusoidal.EaseOut;
case Easing.InOut:
return Sinusoidal.EaseInOut;
default:
throw new Exception();
}
default:
throw new Exception();
}
}
// Added so that we can reuse these
public Tweener()
{
}
public Tweener(float from, float to, float duration, TweeningFunction tweeningFunction)
{
Start(from, to, duration, tweeningFunction);
// Start sets Running to true, so let's set it to false
Running = false;
}
public Tweener(float from, float to, TimeSpan duration, TweeningFunction tweeningFunction)
: this(from, to, (float)duration.TotalSeconds, tweeningFunction)
{
}
#region Properties
private float _position;
public float Position
{
get
{
return _position;
}
protected set
{
_position = value;
}
}
private float _from;
protected float from
{
get
{
return _from;
}
set
{
_from = value;
}
}
private float _change;
protected float change
{
get
{
return _change;
}
set
{
_change = value;
}
}
private float _duration;
protected float duration
{
get
{
return _duration;
}
}
private float _elapsed = 0.0f;
protected float elapsed
{
get
{
return _elapsed;
}
set
{
_elapsed = value;
}
}
private bool _running = true;
public bool Running
{
get { return _running; }
protected set { _running = value; }
}
private TweeningFunction _tweeningFunction;
protected TweeningFunction tweeningFunction
{
get
{
return _tweeningFunction;
}
}
public delegate void PositionChangedHandler(float newPosition);
// Not making this an event because I want users to be able to
// = it instead of only +=
public PositionChangedHandler PositionChanged;
public delegate void EndHandler();
public event EndHandler Ended;
#endregion
#region Methods
public void Update(float time)
{
if (!Running || (elapsed == duration))
{
Running = false;
return;
}
elapsed += time;
elapsed = System.Math.Min(elapsed, duration);
Position = tweeningFunction(elapsed, from, change, duration);
if (PositionChanged != null)
{
PositionChanged(Position);
}
if (elapsed >= duration)
{
elapsed = duration;
Position = from + change;
OnEnd();
}
}
protected void OnEnd()
{
if (Ended != null)
{
Ended();
}
}
public void Start()
{
Running = true;
}
public void Start(float from, float to, float duration, TweeningFunction tweeningFunction)
{
_from = from;
_position = from;
_change = to - from;
_tweeningFunction = tweeningFunction;
_duration = duration;
_elapsed = 0;
Running = true;
}
public void Stop()
{
Running = false;
}
public void Reset()
{
elapsed = 0.0f;
from = Position;
}
public void Reset(float to)
{
change = to - Position;
Reset();
}
public void Reverse()
{
elapsed = 0.0f;
change = -change + (from + change - Position);
from = Position;
}
public override string ToString()
{
#if WINDOWS_8
return String.Format("Tween {0} -> {1} in {2}s. Elapsed {3:##0.##}s",
from,
from + change,
duration,
elapsed);
#else
return String.Format("{0}.{1}. Tween {2} -> {3} in {4}s. Elapsed {5:##0.##}s",
tweeningFunction.Method.DeclaringType.Name,
tweeningFunction.Method.Name,
from,
from + change,
duration,
elapsed);
#endif
}
#endregion
}
}
| |
using EncompassRest.Loans.Enums;
using EncompassRest.Schema;
namespace EncompassRest.Loans
{
/// <summary>
/// PrivacyPolicy
/// </summary>
public sealed partial class PrivacyPolicy : DirtyExtensibleObject, IIdentifiable
{
private DirtyValue<string?>? _additionalRightsDescription;
private DirtyValue<StringEnumValue<AffiliateType>>? _affiliateType;
private DirtyValue<string?>? _affiliateTypeExample1;
private DirtyValue<string?>? _affiliateTypeExample2;
private DirtyValue<string?>? _affiliateTypeExample3;
private DirtyValue<StringEnumValue<AlsoCollectFrom>>? _alsoCollectFrom;
private DirtyValue<int?>? _daysToUse;
private DirtyValue<StringEnumValue<HowToShare>>? _howToShare;
private DirtyValue<string?>? _id;
private DirtyValue<StringEnumValue<YesOrNo>>? _informationShare1;
private DirtyValue<StringEnumValue<YesOrNo>>? _informationShare2;
private DirtyValue<StringEnumValue<YesOrNo>>? _informationShare3;
private DirtyValue<StringEnumValue<YesOrNo>>? _informationShare4;
private DirtyValue<StringEnumValue<YesOrNo>>? _informationShare5;
private DirtyValue<StringEnumValue<YesOrNo>>? _informationShare6;
private DirtyValue<StringEnumValue<YesOrNo>>? _informationShare7;
private DirtyValue<StringEnumValue<InformationTypesWeCollect>>? _informationTypesWeCollect1;
private DirtyValue<StringEnumValue<InformationTypesWeCollect>>? _informationTypesWeCollect2;
private DirtyValue<StringEnumValue<InformationTypesWeCollect>>? _informationTypesWeCollect3;
private DirtyValue<StringEnumValue<InformationTypesWeCollect>>? _informationTypesWeCollect4;
private DirtyValue<StringEnumValue<InformationTypesWeCollect>>? _informationTypesWeCollect5;
private DirtyValue<StringEnumValue<JointMarketType>>? _jointMarketType;
private DirtyValue<string?>? _jointMarketTypeExample1;
private DirtyValue<StringEnumValue<LimitSharing>>? _limitSharing1;
private DirtyValue<StringEnumValue<LimitSharing>>? _limitSharing2;
private DirtyValue<StringEnumValue<LimitSharing>>? _limitSharing3;
private DirtyValue<StringEnumValue<LimitSharing>>? _limitSharing4;
private DirtyValue<StringEnumValue<LimitSharing>>? _limitSharing5;
private DirtyValue<StringEnumValue<LimitSharing>>? _limitSharing6;
private DirtyValue<StringEnumValue<LimitSharing>>? _limitSharing7;
private DirtyValue<StringEnumValue<Month>>? _month;
private DirtyValue<StringEnumValue<NonaffiliateType>>? _nonaffiliateType;
private DirtyValue<string?>? _nonaffiliateTypeExample1;
private DirtyValue<string?>? _notesForProtectPrivacy;
private DirtyValue<string?>? _otherInformation;
private DirtyValue<string?>? _phoneForQuestion;
private DirtyValue<string?>? _phoneToLimit;
private DirtyValue<StringEnumValue<PrintSelection>>? _printSelection;
private DirtyValue<StringEnumValue<ShareInfoWithJointMarketing>>? _shareInfoWithJointMarketing;
private DirtyValue<StringEnumValue<TimesToCollect>>? _timesToCollect1;
private DirtyValue<StringEnumValue<TimesToCollect>>? _timesToCollect2;
private DirtyValue<StringEnumValue<TimesToCollect>>? _timesToCollect3;
private DirtyValue<StringEnumValue<TimesToCollect>>? _timesToCollect4;
private DirtyValue<StringEnumValue<TimesToCollect>>? _timesToCollect5;
private DirtyValue<string?>? _websiteForQuestion;
private DirtyValue<string?>? _websiteToLimit;
private DirtyValue<int?>? _year;
/// <summary>
/// Privacy Policy Information Describe Additional Rights to Limit Sharing [NOTICES.X78]
/// </summary>
public string? AdditionalRightsDescription { get => _additionalRightsDescription; set => SetField(ref _additionalRightsDescription, value); }
/// <summary>
/// Privacy Policy Information Do You Have Affiliates? [NOTICES.X79]
/// </summary>
public StringEnumValue<AffiliateType> AffiliateType { get => _affiliateType; set => SetField(ref _affiliateType, value); }
/// <summary>
/// Privacy Policy Information Do You Have Affiliates Example 1 [NOTICES.X80]
/// </summary>
public string? AffiliateTypeExample1 { get => _affiliateTypeExample1; set => SetField(ref _affiliateTypeExample1, value); }
/// <summary>
/// Privacy Policy Information Do You Have Affiliates Example 2 [NOTICES.X81]
/// </summary>
public string? AffiliateTypeExample2 { get => _affiliateTypeExample2; set => SetField(ref _affiliateTypeExample2, value); }
/// <summary>
/// Privacy Policy Information Do You Have Affiliates Example 3 [NOTICES.X82]
/// </summary>
public string? AffiliateTypeExample3 { get => _affiliateTypeExample3; set => SetField(ref _affiliateTypeExample3, value); }
/// <summary>
/// Privacy Policy Information Institutions that collect personal information from their affiliates and credit bureaus [NOTICES.X94]
/// </summary>
public StringEnumValue<AlsoCollectFrom> AlsoCollectFrom { get => _alsoCollectFrom; set => SetField(ref _alsoCollectFrom, value); }
/// <summary>
/// Privacy Policy Information Number of Days After Providing Notice Can We Begin Sharing Information (must be more than 30) [NOTICES.X91]
/// </summary>
public int? DaysToUse { get => _daysToUse; set => SetField(ref _daysToUse, value); }
/// <summary>
/// Privacy Policy How to Share Customer or Member [NOTICES.X57]
/// </summary>
public StringEnumValue<HowToShare> HowToShare { get => _howToShare; set => SetField(ref _howToShare, value); }
/// <summary>
/// PrivacyPolicy Id
/// </summary>
public string? Id { get => _id; set => SetField(ref _id, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information 1 [NOTICES.X58]
/// </summary>
public StringEnumValue<YesOrNo> InformationShare1 { get => _informationShare1; set => SetField(ref _informationShare1, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information 2 [NOTICES.X59]
/// </summary>
public StringEnumValue<YesOrNo> InformationShare2 { get => _informationShare2; set => SetField(ref _informationShare2, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information 3 [NOTICES.X60]
/// </summary>
public StringEnumValue<YesOrNo> InformationShare3 { get => _informationShare3; set => SetField(ref _informationShare3, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information 4 [NOTICES.X61]
/// </summary>
public StringEnumValue<YesOrNo> InformationShare4 { get => _informationShare4; set => SetField(ref _informationShare4, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information 5 [NOTICES.X62]
/// </summary>
public StringEnumValue<YesOrNo> InformationShare5 { get => _informationShare5; set => SetField(ref _informationShare5, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information 6 [NOTICES.X63]
/// </summary>
public StringEnumValue<YesOrNo> InformationShare6 { get => _informationShare6; set => SetField(ref _informationShare6, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information 7 [NOTICES.X64]
/// </summary>
public StringEnumValue<YesOrNo> InformationShare7 { get => _informationShare7; set => SetField(ref _informationShare7, value); }
/// <summary>
/// Privacy Policy Information Types We Collect 1st Field [NOTICES.X52]
/// </summary>
public StringEnumValue<InformationTypesWeCollect> InformationTypesWeCollect1 { get => _informationTypesWeCollect1; set => SetField(ref _informationTypesWeCollect1, value); }
/// <summary>
/// Privacy Policy Information Types We Collect 2nd Field [NOTICES.X53]
/// </summary>
public StringEnumValue<InformationTypesWeCollect> InformationTypesWeCollect2 { get => _informationTypesWeCollect2; set => SetField(ref _informationTypesWeCollect2, value); }
/// <summary>
/// Privacy Policy Information Types We Collect 3rd Field [NOTICES.X54]
/// </summary>
public StringEnumValue<InformationTypesWeCollect> InformationTypesWeCollect3 { get => _informationTypesWeCollect3; set => SetField(ref _informationTypesWeCollect3, value); }
/// <summary>
/// Privacy Policy Information Types We Collect 4th Field [NOTICES.X55]
/// </summary>
public StringEnumValue<InformationTypesWeCollect> InformationTypesWeCollect4 { get => _informationTypesWeCollect4; set => SetField(ref _informationTypesWeCollect4, value); }
/// <summary>
/// Privacy Policy Information Types We Collect 5th Field [NOTICES.X56]
/// </summary>
public StringEnumValue<InformationTypesWeCollect> InformationTypesWeCollect5 { get => _informationTypesWeCollect5; set => SetField(ref _informationTypesWeCollect5, value); }
/// <summary>
/// Privacy Policy Information Do You Have Joint Marketing? [NOTICES.X85]
/// </summary>
public StringEnumValue<JointMarketType> JointMarketType { get => _jointMarketType; set => SetField(ref _jointMarketType, value); }
/// <summary>
/// Privacy Policy Information Do You Have Joint Marketing Example 1 [NOTICES.X86]
/// </summary>
public string? JointMarketTypeExample1 { get => _jointMarketTypeExample1; set => SetField(ref _jointMarketTypeExample1, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information Limit Sharing 1 [NOTICES.X65]
/// </summary>
public StringEnumValue<LimitSharing> LimitSharing1 { get => _limitSharing1; set => SetField(ref _limitSharing1, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information Limit Sharing 2 [NOTICES.X66]
/// </summary>
public StringEnumValue<LimitSharing> LimitSharing2 { get => _limitSharing2; set => SetField(ref _limitSharing2, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information Limit Sharing 3 [NOTICES.X67]
/// </summary>
public StringEnumValue<LimitSharing> LimitSharing3 { get => _limitSharing3; set => SetField(ref _limitSharing3, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information Limit Sharing 4 [NOTICES.X68]
/// </summary>
public StringEnumValue<LimitSharing> LimitSharing4 { get => _limitSharing4; set => SetField(ref _limitSharing4, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information Limit Sharing 5 [NOTICES.X69]
/// </summary>
public StringEnumValue<LimitSharing> LimitSharing5 { get => _limitSharing5; set => SetField(ref _limitSharing5, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information Limit Sharing 6 [NOTICES.X70]
/// </summary>
public StringEnumValue<LimitSharing> LimitSharing6 { get => _limitSharing6; set => SetField(ref _limitSharing6, value); }
/// <summary>
/// Privacy Policy Reasons We Can Share Your Personal Information Limit Sharing 7 [NOTICES.X71]
/// </summary>
public StringEnumValue<LimitSharing> LimitSharing7 { get => _limitSharing7; set => SetField(ref _limitSharing7, value); }
/// <summary>
/// Privacy Policy Month [NOTICES.X98]
/// </summary>
public StringEnumValue<Month> Month { get => _month; set => SetField(ref _month, value); }
/// <summary>
/// Privacy Policy Information Do You Have Nonaffiliates? [NOTICES.X83]
/// </summary>
public StringEnumValue<NonaffiliateType> NonaffiliateType { get => _nonaffiliateType; set => SetField(ref _nonaffiliateType, value); }
/// <summary>
/// Privacy Policy Information Do You Have Nonaffiliates Example 1 [NOTICES.X84]
/// </summary>
public string? NonaffiliateTypeExample1 { get => _nonaffiliateTypeExample1; set => SetField(ref _nonaffiliateTypeExample1, value); }
/// <summary>
/// Privacy Policy How Does Company Protect My Personal Information [NOTICES.X72]
/// </summary>
public string? NotesForProtectPrivacy { get => _notesForProtectPrivacy; set => SetField(ref _notesForProtectPrivacy, value); }
/// <summary>
/// Privacy Policy Information Other Information [NOTICES.X87]
/// </summary>
public string? OtherInformation { get => _otherInformation; set => SetField(ref _otherInformation, value); }
/// <summary>
/// Privacy Policy Information Phone Number for Question [NOTICES.X92]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? PhoneForQuestion { get => _phoneForQuestion; set => SetField(ref _phoneForQuestion, value); }
/// <summary>
/// Privacy Policy Information Phone Number for Limit Our Sharing [NOTICES.X89]
/// </summary>
[LoanFieldProperty(Format = LoanFieldFormat.PHONE)]
public string? PhoneToLimit { get => _phoneToLimit; set => SetField(ref _phoneToLimit, value); }
/// <summary>
/// Privacy Policy Information Selection [NOTICES.X51]
/// </summary>
public StringEnumValue<PrintSelection> PrintSelection { get => _printSelection; set => SetField(ref _printSelection, value); }
/// <summary>
/// Privacy Policy Information Do You Share Personal Information in Joint Marketing? [NOTICES.X88]
/// </summary>
public StringEnumValue<ShareInfoWithJointMarketing> ShareInfoWithJointMarketing { get => _shareInfoWithJointMarketing; set => SetField(ref _shareInfoWithJointMarketing, value); }
/// <summary>
/// Privacy Policy Information We Collect Customer Personal Information at These Times 1 [NOTICES.X73]
/// </summary>
public StringEnumValue<TimesToCollect> TimesToCollect1 { get => _timesToCollect1; set => SetField(ref _timesToCollect1, value); }
/// <summary>
/// Privacy Policy Information We Collect Customer Personal Information at These Times 2 [NOTICES.X74]
/// </summary>
public StringEnumValue<TimesToCollect> TimesToCollect2 { get => _timesToCollect2; set => SetField(ref _timesToCollect2, value); }
/// <summary>
/// Privacy Policy Information We Collect Customer Personal Information at These Times 3 [NOTICES.X75]
/// </summary>
public StringEnumValue<TimesToCollect> TimesToCollect3 { get => _timesToCollect3; set => SetField(ref _timesToCollect3, value); }
/// <summary>
/// Privacy Policy Information We Collect Customer Personal Information at These Times 4 [NOTICES.X76]
/// </summary>
public StringEnumValue<TimesToCollect> TimesToCollect4 { get => _timesToCollect4; set => SetField(ref _timesToCollect4, value); }
/// <summary>
/// Privacy Policy Information We Collect Customer Personal Information at These Times 5 [NOTICES.X77]
/// </summary>
public StringEnumValue<TimesToCollect> TimesToCollect5 { get => _timesToCollect5; set => SetField(ref _timesToCollect5, value); }
/// <summary>
/// Privacy Policy Information Website for Question [NOTICES.X93]
/// </summary>
public string? WebsiteForQuestion { get => _websiteForQuestion; set => SetField(ref _websiteForQuestion, value); }
/// <summary>
/// Privacy Policy Information Website for Limit Our Sharing [NOTICES.X90]
/// </summary>
public string? WebsiteToLimit { get => _websiteToLimit; set => SetField(ref _websiteToLimit, value); }
/// <summary>
/// Privacy Policy Year [NOTICES.X99]
/// </summary>
public int? Year { get => _year; set => SetField(ref _year, value); }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using MusicStore.WebAPI.Areas.HelpPage.ModelDescriptions;
using MusicStore.WebAPI.Areas.HelpPage.Models;
namespace MusicStore.WebAPI.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Xunit;
namespace Test
{
public class ExchangeTests
{
private static readonly ParallelMergeOptions[] Options = new[] {
ParallelMergeOptions.AutoBuffered,
ParallelMergeOptions.Default,
ParallelMergeOptions.FullyBuffered,
ParallelMergeOptions.NotBuffered
};
/// <summary>
/// Get a set of ranges, running for each count in `counts`, with 1, 2, and 4 counts for partitions.
/// </summary>
/// <param name="counts">The sizes of ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// the second element is the count, and the third is the number of partitions or degrees of parallelism to use.</returns>
public static IEnumerable<object[]> PartitioningData(int[] counts)
{
foreach (object[] results in Sources.Ranges(counts.Cast<int>(), x => new[] { 1, 2, 4 }))
{
yield return results;
}
}
// For each source, run with each buffering option.
/// <summary>
/// Get a set of ranges, and running for each count in `counts`, with each possible ParallelMergeOption
/// </summary>
/// <param name="counts">The sizes of ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// the second element is the count, and the third is the ParallelMergeOption to use.</returns>
public static IEnumerable<object[]> MergeData(int[] counts)
{
foreach (object[] results in Sources.Ranges(counts.Cast<int>(), x => Options))
{
yield return results;
}
}
/// <summary>
///For each count, return an Enumerable source that fails (throws an exception) on that count, with each buffering option.
/// </summary>
/// <param name="counts">The sizes of ranges to return.</param>
/// <returns>Entries for test data.
/// The first element is the Labeled{ParallelQuery{int}} range,
/// the second element is the count, and the third is the ParallelMergeOption to use.</returns>
public static IEnumerable<object[]> ThrowOnCount_AllMergeOptions_MemberData(int[] counts)
{
foreach (int count in counts.Cast<int>())
{
var labeled = Labeled.Label("ThrowOnEnumeration " + count, Enumerables<int>.ThrowOnEnumeration(count).AsParallel().AsOrdered());
foreach (ParallelMergeOptions option in Options)
{
yield return new object[] { labeled, count, option };
}
}
}
// The following tests attempt to test internal behavior,
// but there doesn't appear to be a way to reliably (or automatically) observe it.
// The basic tests are covered elsewhere, although without WithDegreeOfParallelism
// or WithMergeOptions
[Theory]
[MemberData("PartitioningData", (object)(new int[] { 0, 1, 2, 16, 1024 }))]
public static void Partitioning_Default(Labeled<ParallelQuery<int>> labeled, int count, int partitions)
{
int seen = 0;
foreach (int i in labeled.Item.WithDegreeOfParallelism(partitions).Select(i => i))
{
Assert.Equal(seen++, i);
}
}
[Theory]
[OuterLoop]
[MemberData("PartitioningData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Partitioning_Default_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int partitions)
{
Partitioning_Default(labeled, count, partitions);
}
[Theory]
[MemberData("PartitioningData", (object)(new int[] { 0, 1, 2, 16, 1024 }))]
public static void Partitioning_Striped(Labeled<ParallelQuery<int>> labeled, int count, int partitions)
{
int seen = 0;
foreach (int i in labeled.Item.WithDegreeOfParallelism(partitions).Take(count).Select(i => i))
{
Assert.Equal(seen++, i);
}
}
[Theory]
[OuterLoop]
[MemberData("PartitioningData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Partitioning_Striped_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, int partitions)
{
Partitioning_Striped(labeled, count, partitions);
}
[Theory]
[MemberData("MergeData", (object)(new int[] { 0, 1, 2, 16, 1024 }))]
public static void Merge_Ordered(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options)
{
int seen = 0;
foreach (int i in labeled.Item.WithMergeOptions(options).Select(i => i))
{
Assert.Equal(seen++, i);
}
}
[Theory]
[OuterLoop]
[MemberData("MergeData", (object)(new int[] { 1024 * 4, 1024 * 1024 }))]
public static void Merge_Ordered_Longrunning(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options)
{
Merge_Ordered(labeled, count, options);
}
[Theory]
[MemberData("ThrowOnCount_AllMergeOptions_MemberData", (object)(new int[] { 4, 8 }))]
// FailingMergeData has enumerables that throw errors when attempting to perform the nth enumeration.
// This test checks whether the query runs in a pipelined or buffered fashion.
public static void Merge_Ordered_Pipelining(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options)
{
Assert.Equal(0, labeled.Item.WithDegreeOfParallelism(count - 1).WithMergeOptions(options).First());
}
[Theory]
[MemberData("MergeData", (object)(new int[] { 4, 8 }))]
// This test checks whether the query runs in a pipelined or buffered fashion.
public static void Merge_Ordered_Pipelining_Select(Labeled<ParallelQuery<int>> labeled, int count, ParallelMergeOptions options)
{
int countdown = count;
Func<int, int> down = i =>
{
if (Interlocked.Decrement(ref countdown) == 0) throw new DeliberateTestException();
return i;
};
Assert.Equal(0, labeled.Item.WithDegreeOfParallelism(count - 1).WithMergeOptions(options).Select(down).First());
}
[Theory]
[MemberData("Ranges", (object)(new int[] { 2 }), MemberType = typeof(UnorderedSources))]
public static void Merge_ArgumentException(Labeled<ParallelQuery<int>> labeled, int count)
{
ParallelQuery<int> query = labeled.Item;
Assert.Throws<ArgumentException>(() => query.WithMergeOptions((ParallelMergeOptions)4));
}
[Fact]
public static void Merge_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>(() => ((ParallelQuery<int>)null).WithMergeOptions(ParallelMergeOptions.AutoBuffered));
}
// The plinq chunk partitioner takes an IEnumerator over the source, and disposes the
// enumerator when it is finished. If an exception occurs, the calling enumerator disposes
// the source enumerator... but then other worker threads may generate ODEs.
// This test verifies any such ODEs are not reflected in the output exception.
[Theory]
[MemberData("BinaryRanges", new int[] { 16 }, new int[] { 16 }, MemberType = typeof(UnorderedSources))]
public static void PlinqChunkPartitioner_DontEnumerateAfterException(Labeled<ParallelQuery<int>> left, int leftCount,
Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> query =
left.Item.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Select(x => { if (x == 4) throw new DeliberateTestException(); return x; })
.Zip(right.Item, (a, b) => a + b)
.AsParallel().WithExecutionMode(ParallelExecutionMode.ForceParallelism);
AggregateException ae = Assert.Throws<AggregateException>(() => query.ToArray());
Assert.Single(ae.InnerExceptions);
Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e));
}
// The stand-alone chunk partitioner takes an IEnumerator over the source, and
// disposes the enumerator when it is finished. If an exception occurs, the calling
// enumerator disposes the source enumerator... but then other worker threads may generate ODEs.
// This test verifies any such ODEs are not reflected in the output exception.
[Theory]
[MemberData("BinaryRanges", new int[] { 16 }, new int[] { 16 }, MemberType = typeof(UnorderedSources))]
public static void ManualChunkPartitioner_DontEnumerateAfterException(
Labeled<ParallelQuery<int>> left, int leftCount,
Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> query =
Partitioner.Create(left.Item.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.Select(x => { if (x == 4) throw new DeliberateTestException(); return x; })
.Zip(right.Item, (a, b) => a + b))
.AsParallel();
AggregateException ae = Assert.Throws<AggregateException>(() => query.ToArray());
Assert.Single(ae.InnerExceptions);
Assert.All(ae.InnerExceptions, e => Assert.IsType<DeliberateTestException>(e));
}
}
}
| |
//
// Copyright (C) DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Threading;
using Cassandra.IntegrationTests.Policies.Util;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using Cassandra.Tests;
using NUnit.Framework;
#pragma warning disable 618
namespace Cassandra.IntegrationTests.Policies.Tests
{
[TestFixture, Category(TestCategory.Long), Ignore("tests that are not marked with 'short' need to be refactored/deleted")]
public class RetryPolicyTests : TestGlobals
{
/// <summary>
/// Tests DowngradingConsistencyRetryPolicy
/// </summary>
[Test]
public void RetryPolicy_DowngradingConsistency()
{
Builder builder = ClusterBuilder().WithRetryPolicy(DowngradingConsistencyRetryPolicy.Instance);
DowngradingConsistencyRetryPolicyTest(builder);
}
/// <summary>
/// Tests DowngradingConsistencyRetryPolicy with LoggingRetryPolicy
///
/// @test_category connection:retry_policy
/// </summary>
[Test]
public void LoggingRetryPolicy_DowngradingConsistency()
{
Builder builder = ClusterBuilder().WithRetryPolicy(new LoggingRetryPolicy(DowngradingConsistencyRetryPolicy.Instance));
DowngradingConsistencyRetryPolicyTest(builder);
}
/// <summary>
/// Tests DowngradingConsistencyRetryPolicy
///
/// @test_category connection:retry_policy
/// </summary>
public void DowngradingConsistencyRetryPolicyTest(Builder builder)
{
PolicyTestTools policyTestTools = new PolicyTestTools();
ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(3);
testCluster.Builder = builder;
testCluster.InitClient();
policyTestTools.CreateSchema(testCluster.Session, 3);
// FIXME: Race condition where the nodes are not fully up yet and assertQueried reports slightly different numbers
TestUtils.WaitForSchemaAgreement(testCluster.Cluster);
policyTestTools.InitPreparedStatement(testCluster, 12, ConsistencyLevel.All);
policyTestTools.Query(testCluster, 12, ConsistencyLevel.All);
policyTestTools.AssertAchievedConsistencyLevel(ConsistencyLevel.All);
//Kill one node: 2 nodes alive
testCluster.Stop(2);
TestUtils.WaitForDown(testCluster.ClusterIpPrefix + "2", testCluster.Cluster, 20);
//After killing one node, the achieved consistency level should be downgraded
policyTestTools.ResetCoordinators();
policyTestTools.Query(testCluster, 12, ConsistencyLevel.All);
policyTestTools.AssertAchievedConsistencyLevel(ConsistencyLevel.Two);
}
/// <summary>
/// Test AlwaysIgnoreRetryPolicy with Logging enabled
///
/// @test_category connection:retry_policy,outage
/// </summary>
[Test]
public void AlwaysIgnoreRetryPolicyTest()
{
ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(2);
testCluster.Builder = ClusterBuilder()
.WithRetryPolicy(new LoggingRetryPolicy(AlwaysIgnoreRetryPolicy.Instance))
.AddContactPoint(testCluster.ClusterIpPrefix + "1")
.AddContactPoint(testCluster.ClusterIpPrefix + "2");
testCluster.InitClient();
RetryPolicyTest(testCluster);
}
/// <summary>
/// Test AlwaysIgnoreRetryPolicy with Logging enabled
///
/// @test_category connection:retry_policy,outage
/// </summary>
[Test]
public void AlwaysRetryRetryPolicyTest()
{
ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(2);
testCluster.Builder = ClusterBuilder()
.WithRetryPolicy(new LoggingRetryPolicy(AlwaysRetryRetryPolicy.Instance))
.AddContactPoint(testCluster.ClusterIpPrefix + "1")
.AddContactPoint(testCluster.ClusterIpPrefix + "2");
testCluster.InitClient();
RetryPolicyTest(testCluster);
}
/// Tests that retries are performed on the next host with useCurrentHost set to false
///
/// TryNextHostRetryPolicyTest tests that the driver can use the next available node when retrying, instead of reusing
/// the currently attempted node. This test uses a TryNextHostRetryPolicy that is defined with useCurrentHost set to false
/// for each of read, write and unavailable exceptions, and a Cassandra cluster with 2 nodes. It first tests that with both
/// hosts up, the load is balanced evenly and retries are not used. It then pauses one of the nodes each time and verifies
/// that the available node is used. Finally, it pauses both nodes and verfifies that a NoHostAvailableException is raised,
/// and neither host fulfills the query.
///
/// @since 2.7.0
/// @jira_ticket CSHARP-273
/// @expected_result For each query, the rety should use the next available host.
///
/// @test_assumptions
/// - A Cassandra cluster with 2 nodes
/// - A TryNextHostRetryPolicy decision defined, with useCurrentHost set to false
/// @test_category connection:retry_policy
[Test]
public void TryNextHostRetryPolicyTest()
{
ITestCluster testCluster = TestClusterManager.GetNonShareableTestCluster(2);
var socketOptions = new SocketOptions().SetReadTimeoutMillis(2000);
testCluster.Builder = ClusterBuilder()
.WithRetryPolicy(new LoggingRetryPolicy(TryNextHostRetryPolicy.Instance))
.AddContactPoint(testCluster.ClusterIpPrefix + "1")
.AddContactPoint(testCluster.ClusterIpPrefix + "2")
.WithSocketOptions(socketOptions);
testCluster.InitClient();
// Setup cluster
PolicyTestTools policyTestTools = new PolicyTestTools();
policyTestTools.CreateSchema(testCluster.Session, 2);
policyTestTools.InitPreparedStatement(testCluster, 12);
// Try with both hosts
policyTestTools.Query(testCluster, 10);
policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 5);
policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 5);
// Try with host 1
policyTestTools.ResetCoordinators();
testCluster.PauseNode(2);
policyTestTools.Query(testCluster, 10);
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 10);
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 0);
testCluster.ResumeNode(2);
// Try with host 2
policyTestTools.ResetCoordinators();
testCluster.PauseNode(1);
policyTestTools.Query(testCluster, 10);
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 0);
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 10);
// Try with 0 hosts
policyTestTools.ResetCoordinators();
testCluster.PauseNode(2);
Assert.Throws<NoHostAvailableException>(() => policyTestTools.Query(testCluster, 10));
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 1 + ":" + DefaultCassandraPort, 0);
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + 2 + ":" + DefaultCassandraPort, 0);
testCluster.ResumeNode(1);
testCluster.ResumeNode(2);
}
private void RetryPolicyTest(ITestCluster testCluster)
{
PolicyTestTools policyTestTools = new PolicyTestTools();
policyTestTools.TableName = TestUtils.GetUniqueTableName();
policyTestTools.CreateSchema(testCluster.Session, 2);
// Test before state
policyTestTools.InitPreparedStatement(testCluster, 12);
policyTestTools.Query(testCluster, 12);
int clusterPosQueried = 1;
int clusterPosNotQueried = 2;
if (!policyTestTools.Coordinators.ContainsKey(testCluster.ClusterIpPrefix + clusterPosQueried))
{
clusterPosQueried = 2;
clusterPosNotQueried = 1;
}
policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + clusterPosQueried + ":" + DefaultCassandraPort, 1);
// Stop one of the nodes and test
policyTestTools.ResetCoordinators();
testCluster.Stop(clusterPosQueried);
TestUtils.WaitForDown(testCluster.ClusterIpPrefix + clusterPosQueried, testCluster.Cluster, 30);
policyTestTools.Query(testCluster, 120);
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + clusterPosNotQueried + ":" + DefaultCassandraPort, 120);
policyTestTools.AssertQueried(testCluster.ClusterIpPrefix + clusterPosQueried + ":" + DefaultCassandraPort, 0);
// Start the node that was just down, then down the node that was just up
policyTestTools.ResetCoordinators();
testCluster.Start(clusterPosQueried);
TestUtils.WaitForUp(testCluster.ClusterIpPrefix + clusterPosQueried, DefaultCassandraPort, 30);
// Test successful reads
DateTime futureDateTime = DateTime.Now.AddSeconds(120);
while (policyTestTools.Coordinators.Count < 2 && DateTime.Now < futureDateTime)
{
policyTestTools.Query(testCluster, 120);
Thread.Sleep(75);
}
// Ensure that the nodes were contacted
policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + clusterPosQueried + ":" + DefaultCassandraPort, 1);
policyTestTools.AssertQueriedAtLeast(testCluster.ClusterIpPrefix + clusterPosNotQueried + ":" + DefaultCassandraPort, 1);
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using Microsoft.Vsa;
using System.IO;
namespace AED
{
/// <summary>
/// Summary description for ScriptEditor.
/// </summary>
public class ScriptEditor : System.Windows.Forms.Form
{
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.RichTextBox rtbEdit;
private System.Windows.Forms.RichTextBox rtbOutput;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem mniCompile;
private System.Windows.Forms.MenuItem mniRun;
private System.Windows.Forms.Splitter splitter1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem mniOpen;
private System.Windows.Forms.OpenFileDialog openFileDialog;
private System.Windows.Forms.StatusBar stb;
private System.Windows.Forms.StatusBarPanel stbpText;
private System.Windows.Forms.StatusBarPanel stbpLine;
private System.Windows.Forms.StatusBarPanel stbpColumn;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem mniLibraryColorMapper;
private System.Windows.Forms.MenuItem mniLibraryOriginOffsetter;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
///
/// </summary>
/// <param name="se"></param>
/// <param name="strScript"></param>
public ScriptEditor(ScriptEngine se, string strScript)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
// Non-Designer initialization
m_se = se;
m_se.CompileError += new CompileErrorEventHandler(OnCompileError);
Script = strScript;
m_tbwtr = new TextBoxWriter(rtbOutput);
// m_tbwtr.WriteLine("s: {0}, l: {1}", rtbEdit.SelectionStart, rtbEdit.SelectionLength);
}
/// <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.openFileDialog = new System.Windows.Forms.OpenFileDialog();
this.mniOpen = new System.Windows.Forms.MenuItem();
this.stbpColumn = new System.Windows.Forms.StatusBarPanel();
this.splitter1 = new System.Windows.Forms.Splitter();
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.mniCompile = new System.Windows.Forms.MenuItem();
this.mniRun = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.mniLibraryColorMapper = new System.Windows.Forms.MenuItem();
this.mniLibraryOriginOffsetter = new System.Windows.Forms.MenuItem();
this.rtbEdit = new System.Windows.Forms.RichTextBox();
this.stbpLine = new System.Windows.Forms.StatusBarPanel();
this.stb = new System.Windows.Forms.StatusBar();
this.stbpText = new System.Windows.Forms.StatusBarPanel();
this.rtbOutput = new System.Windows.Forms.RichTextBox();
((System.ComponentModel.ISupportInitialize)(this.stbpColumn)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.stbpLine)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.stbpText)).BeginInit();
this.SuspendLayout();
//
// openFileDialog
//
this.openFileDialog.DefaultExt = "js";
this.openFileDialog.Filter = "EcmaScript/JavaScript (*.js)|*.js|All files (*.*)|*.*";
this.openFileDialog.Title = "Open Script";
//
// mniOpen
//
this.mniOpen.Index = 0;
this.mniOpen.Text = "&Open...";
this.mniOpen.Click += new System.EventHandler(this.mniOpen_Click);
//
// stbpColumn
//
this.stbpColumn.MinWidth = 40;
this.stbpColumn.Width = 50;
//
// splitter1
//
this.splitter1.Dock = System.Windows.Forms.DockStyle.Bottom;
this.splitter1.Location = new System.Drawing.Point(0, 284);
this.splitter1.Name = "splitter1";
this.splitter1.Size = new System.Drawing.Size(520, 3);
this.splitter1.TabIndex = 2;
this.splitter1.TabStop = false;
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem2,
this.menuItem1,
this.menuItem3});
//
// menuItem2
//
this.menuItem2.Index = 0;
this.menuItem2.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mniOpen,
this.menuItem4,
this.menuItem5});
this.menuItem2.Text = "&File";
//
// menuItem4
//
this.menuItem4.Enabled = false;
this.menuItem4.Index = 1;
this.menuItem4.Text = "&Save";
//
// menuItem5
//
this.menuItem5.Enabled = false;
this.menuItem5.Index = 2;
this.menuItem5.Text = "Save &As...";
//
// menuItem1
//
this.menuItem1.Index = 1;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mniCompile,
this.mniRun});
this.menuItem1.Text = "Script";
//
// mniCompile
//
this.mniCompile.Index = 0;
this.mniCompile.Shortcut = System.Windows.Forms.Shortcut.F7;
this.mniCompile.Text = "&Compile";
this.mniCompile.Click += new System.EventHandler(this.mniCompile_Click);
//
// mniRun
//
this.mniRun.Index = 1;
this.mniRun.Shortcut = System.Windows.Forms.Shortcut.F5;
this.mniRun.Text = "&Run";
this.mniRun.Click += new System.EventHandler(this.mniRun_Click);
//
// menuItem3
//
this.menuItem3.Index = 2;
this.menuItem3.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mniLibraryColorMapper,
this.mniLibraryOriginOffsetter});
this.menuItem3.Text = "&Library";
//
// mniLibraryColorMapper
//
this.mniLibraryColorMapper.Index = 0;
this.mniLibraryColorMapper.Text = "&Color Mapper";
this.mniLibraryColorMapper.Click += new System.EventHandler(this.mniLibraryColorMapper_Click);
//
// mniLibraryOriginOffsetter
//
this.mniLibraryOriginOffsetter.Index = 1;
this.mniLibraryOriginOffsetter.Text = "&Origin Offsetter";
this.mniLibraryOriginOffsetter.Click += new System.EventHandler(this.mniLibraryOriginOffsetter_Click);
//
// rtbEdit
//
this.rtbEdit.Dock = System.Windows.Forms.DockStyle.Fill;
this.rtbEdit.Name = "rtbEdit";
this.rtbEdit.Size = new System.Drawing.Size(520, 383);
this.rtbEdit.TabIndex = 0;
this.rtbEdit.Text = "";
this.rtbEdit.WordWrap = false;
this.rtbEdit.SelectionChanged += new System.EventHandler(this.rtbEdit_SelectionChanged);
//
// stbpLine
//
this.stbpLine.MinWidth = 40;
this.stbpLine.Width = 50;
//
// stb
//
this.stb.Location = new System.Drawing.Point(0, 383);
this.stb.Name = "stb";
this.stb.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.stbpText,
this.stbpLine,
this.stbpColumn});
this.stb.ShowPanels = true;
this.stb.Size = new System.Drawing.Size(520, 20);
this.stb.TabIndex = 3;
//
// stbpText
//
this.stbpText.AutoSize = System.Windows.Forms.StatusBarPanelAutoSize.Spring;
this.stbpText.Width = 404;
//
// rtbOutput
//
this.rtbOutput.Dock = System.Windows.Forms.DockStyle.Bottom;
this.rtbOutput.Location = new System.Drawing.Point(0, 287);
this.rtbOutput.Name = "rtbOutput";
this.rtbOutput.Size = new System.Drawing.Size(520, 96);
this.rtbOutput.TabIndex = 1;
this.rtbOutput.Text = "";
this.rtbOutput.WordWrap = false;
//
// ScriptEditor
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(520, 403);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.splitter1,
this.rtbOutput,
this.rtbEdit,
this.stb});
this.Menu = this.mainMenu1;
this.Name = "ScriptEditor";
this.Text = "Script Editor";
this.Closing += new System.ComponentModel.CancelEventHandler(this.ScriptEditor_Closing);
((System.ComponentModel.ISupportInitialize)(this.stbpColumn)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.stbpLine)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.stbpText)).EndInit();
this.ResumeLayout(false);
}
#endregion
//
// Non-Windows.Forms state
//
private ScriptEngine m_se;
private TextBoxWriter m_tbwtr;
//
// Public Properties
//
public string Script {
get {
return rtbEdit.Text;
}
set {
rtbEdit.Text = value;
UpdateLineColumnIndicator();
// For some reason this can't be set until after it has been read (inside
// of UpdateLineColumnIndicator in this case). Otherwise a "SelectionStart
// argument (-1) invalid" exception is raised.
rtbEdit.SelectionLength = 0;
}
}
public event EventHandler ScriptEditorClosing;
//
// UI event handlers
//
private void mniCompile_Click(object sender, System.EventArgs e) {
ClearErrors();
ClearOutput();
// UNDONE: clear colored (error) text
bool fSuccess = false;
// try {
fSuccess = m_se.Compile(rtbEdit.Text);
// } catch (Exception ex) {
// WriteLine("Errors found during compile:\n{0}", ex.Message);
// return;
// }
if (fSuccess)
WriteLine("No errors");
}
private void mniRun_Click(object sender, System.EventArgs e) {
ClearErrors();
ClearOutput();
TextWriter twtrConsoleOut = Console.Out;
Console.SetOut(m_tbwtr);
// UNDONE: clear colored (error) text
// try {
m_se.Compile(rtbEdit.Text);
// } catch {
// return;
// }
m_se.Run();
Console.SetOut(twtrConsoleOut);
}
private void mniOpen_Click(object sender, System.EventArgs e) {
if (openFileDialog.ShowDialog() != DialogResult.OK)
return;
rtbEdit.LoadFile(openFileDialog.FileName);
}
// UNDONE: somehow determine where the insertion point really is and use it, not the
// selection start.
private void rtbEdit_SelectionChanged(object sender, System.EventArgs e) {
UpdateLineColumnIndicator();
}
//
// Everything else
//
protected virtual void OnScriptEditorClosing(EventArgs evta) {
if (ScriptEditorClosing != null)
ScriptEditorClosing(this, evta);
m_se.CompileError -= new CompileErrorEventHandler(OnCompileError);
}
private void OnCompileError(object obSender, IVsaError vsaerr) {
WriteLine("({0},{1}): sev {4}, {5} {2:x}: {3}", vsaerr.Line, vsaerr.StartColumn,
vsaerr.Number, vsaerr.Description, vsaerr.Severity, vsaerr.Severity > 0 ? "warning" : "error");
int ichSelStart = rtbEdit.SelectionStart;
int ichSelLength = rtbEdit.SelectionLength;
int ichT = GetCharIndexFromLine(rtbEdit.Text, vsaerr.Line - 1);
rtbEdit.SelectionStart = ichT + vsaerr.StartColumn - 1; // columns are numbered starting at 1
rtbEdit.SelectionLength = vsaerr.EndColumn - vsaerr.StartColumn;
rtbEdit.SelectionColor = Color.FromArgb(255, 0, 128);
rtbEdit.SelectionStart = ichSelStart;
rtbEdit.SelectionLength = ichSelLength;
}
private int GetCharIndexFromLine(string strText, int iLine) {
if (iLine == 0)
return 0;
int cLines = 0;
for (int i = 0; i < strText.Length; i++) {
if (strText[i] == '\n') {
cLines++;
if (cLines == iLine)
return i + 1;
}
}
return 0;
}
private void ClearOutput() {
rtbOutput.Clear();
}
private void ClearErrors() {
string strT = rtbEdit.Text;
int ichSelStart = rtbEdit.SelectionStart;
int ichSelLength = rtbEdit.SelectionLength;
rtbEdit.Text = null;
rtbEdit.Text = strT;
rtbEdit.SelectionStart = ichSelStart;
rtbEdit.SelectionLength = ichSelLength;
}
private void WriteLine(string strFormat, params object[] aobParams) {
Write(strFormat, aobParams);
Write("\n");
}
private void Write(string strFormat, params object[] aobParams) {
string strT = string.Format(strFormat, aobParams);
rtbOutput.Text += strT;
}
private void ScriptEditor_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
OnScriptEditorClosing(EventArgs.Empty);
}
private void UpdateLineColumnIndicator() {
int ichInsertionPoint = rtbEdit.SelectionStart;
int iLine = rtbEdit.GetLineFromCharIndex(ichInsertionPoint) + 1;
stbpLine.Text = "Ln " + iLine;
int ich = ichInsertionPoint;
while (--ich >= 0 && rtbEdit.Text[ich] != '\n');
stbpColumn.Text = "Col " + (ichInsertionPoint - ich);
}
private void mniLibraryColorMapper_Click(object sender, System.EventArgs e) {
rtbEdit.AppendText(@"// Change a bunch of colors in all frames
for (frm in AED.Frames) {
var clrOld = new Array(0,114,232)
var clrNew = new Array(0,116,232)
frm.ReplaceColor(clrOld, clrNew, true)
clrOld = new Array(0,112,232)
clrNew = new Array(0,116,232)
frm.ReplaceColor(clrOld, clrNew, true)
clrOld = new Array(0,96,192)
clrNew = new Array(0,96,196)
frm.ReplaceColor(clrOld, clrNew, true)
clrOld = new Array(0,48,88)
clrNew = new Array(0,48,92)
frm.ReplaceColor(clrOld, clrNew, true)
}
");
}
private void mniLibraryOriginOffsetter_Click(object sender, System.EventArgs e) {
rtbEdit.AppendText(@"// Offset all frames
for (frm in AED.Frames) {
frm.OriginX -= 16;
frm.OriginY -= 15;
}
");
}
}
//
// Wrap a TextBox control in a TextWriter stream so StdOut, etc output can be
// routed to the TextBox.
//
class TextBoxWriter : TextWriter {
private TextBoxBase m_tb = null;
public TextBoxWriter(TextBoxBase tb) {
m_tb = tb;
}
override public void WriteLine(string str) {
m_tb.Text += str + "\n";
}
#if false
override public void WriteLine(string strFormat, params object[] aobParams) {
Write(strFormat, aobParams);
Write("\n");
}
override public void Write(string strFormat, params object[] aobParams) {
string strT = string.Format(strFormat, aobParams);
m_tb.Text += strT;
}
#endif
// Standard property we have to implement (...grumble...)
override public System.Text.Encoding Encoding {
get {
return System.Text.Encoding.ASCII;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using LibGit2Sharp.Tests.TestHelpers;
using Xunit;
using Xunit.Extensions;
namespace LibGit2Sharp.Tests
{
public class FilterSubstitutionCipherFixture : BaseFixture
{
[Fact]
public void SmugdeIsNotCalledForFileWhichDoesNotMatchAnAttributeEntry()
{
const string decodedInput = "This is a substitution cipher";
const string encodedInput = "Guvf vf n fhofgvghgvba pvcure";
var attributes = new List<FilterAttributeEntry> { new FilterAttributeEntry("rot13") };
var filter = new SubstitutionCipherFilter("cipher-filter", attributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".rot13";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, "*.rot13 filter=rot13");
var blob = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
var textDetected = blob.GetContentText();
Assert.Equal(encodedInput, textDetected);
Assert.Equal(1, filter.CleanCalledCount);
Assert.Equal(0, filter.SmudgeCalledCount);
var branch = repo.CreateBranch("delete-files");
repo.Checkout(branch.FriendlyName);
DeleteFile(repo, fileName);
repo.Checkout("master");
var fileContents = ReadTextFromFile(repo, fileName);
Assert.Equal(1, filter.SmudgeCalledCount);
Assert.Equal(decodedInput, fileContents);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Fact]
public void CorrectlyEncodesAndDecodesInput()
{
const string decodedInput = "This is a substitution cipher";
const string encodedInput = "Guvf vf n fhofgvghgvba pvcure";
var attributes = new List<FilterAttributeEntry> { new FilterAttributeEntry("rot13") };
var filter = new SubstitutionCipherFilter("cipher-filter", attributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".rot13";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, "*.rot13 filter=rot13");
var blob = CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
var textDetected = blob.GetContentText();
Assert.Equal(encodedInput, textDetected);
Assert.Equal(1, filter.CleanCalledCount);
Assert.Equal(0, filter.SmudgeCalledCount);
var branch = repo.CreateBranch("delete-files");
repo.Checkout(branch.FriendlyName);
DeleteFile(repo, fileName);
repo.Checkout("master");
var fileContents = ReadTextFromFile(repo, fileName);
Assert.Equal(1, filter.SmudgeCalledCount);
Assert.Equal(decodedInput, fileContents);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Theory]
[InlineData("*.txt", ".bat", 0, 0)]
[InlineData("*.txt", ".txt", 1, 0)]
public void WhenStagedFileDoesNotMatchPathSpecFileIsNotFiltered(string pathSpec, string fileExtension, int cleanCount, int smudgeCount)
{
const string filterName = "rot13";
const string decodedInput = "This is a substitution cipher";
string attributeFileEntry = string.Format("{0} filter={1}", pathSpec, filterName);
var filterForAttributes = new List<FilterAttributeEntry> { new FilterAttributeEntry(filterName) };
var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + fileExtension;
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, attributeFileEntry);
CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
Assert.Equal(cleanCount, filter.CleanCalledCount);
Assert.Equal(smudgeCount, filter.SmudgeCalledCount);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Theory]
[InlineData("rot13", "*.txt filter=rot13", 1)]
[InlineData("rot13", "*.txt filter=fake", 0)]
[InlineData("rot13", "*.bat filter=rot13", 0)]
[InlineData("rot13", "*.txt filter=fake", 0)]
[InlineData("fake", "*.txt filter=fake", 1)]
[InlineData("fake", "*.bat filter=fake", 0)]
[InlineData("rot13", "*.txt filter=rot13 -crlf", 1)]
public void CleanIsCalledIfAttributeEntryMatches(string filterAttribute, string attributeEntry, int cleanCount)
{
const string decodedInput = "This is a substitution cipher";
var filterForAttributes = new List<FilterAttributeEntry> { new FilterAttributeEntry(filterAttribute) };
var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".txt";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, attributeEntry);
CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
Assert.Equal(cleanCount, filter.CleanCalledCount);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
[Theory]
[InlineData("rot13", "*.txt filter=rot13", 1)]
[InlineData("rot13", "*.txt filter=fake", 0)]
[InlineData("rot13", "*.txt filter=rot13 -crlf", 1)]
public void SmudgeIsCalledIfAttributeEntryMatches(string filterAttribute, string attributeEntry, int smudgeCount)
{
const string decodedInput = "This is a substitution cipher";
var filterForAttributes = new List<FilterAttributeEntry> { new FilterAttributeEntry(filterAttribute) };
var filter = new SubstitutionCipherFilter("cipher-filter", filterForAttributes);
var filterRegistration = GlobalSettings.RegisterFilter(filter);
string repoPath = InitNewRepository();
string fileName = Guid.NewGuid() + ".txt";
string configPath = CreateConfigurationWithDummyUser(Constants.Signature);
var repositoryOptions = new RepositoryOptions { GlobalConfigurationLocation = configPath };
using (var repo = new Repository(repoPath, repositoryOptions))
{
CreateAttributesFile(repo, attributeEntry);
CommitOnBranchAndReturnDatabaseBlob(repo, fileName, decodedInput);
var branch = repo.CreateBranch("delete-files");
repo.Checkout(branch.FriendlyName);
DeleteFile(repo, fileName);
repo.Checkout("master");
Assert.Equal(smudgeCount, filter.SmudgeCalledCount);
}
GlobalSettings.DeregisterFilter(filterRegistration);
}
private static string ReadTextFromFile(Repository repo, string fileName)
{
return File.ReadAllText(Path.Combine(repo.Info.WorkingDirectory, fileName));
}
private static void DeleteFile(Repository repo, string fileName)
{
File.Delete(Path.Combine(repo.Info.WorkingDirectory, fileName));
repo.Stage(fileName);
repo.Commit("remove file");
}
private static Blob CommitOnBranchAndReturnDatabaseBlob(Repository repo, string fileName, string input)
{
Touch(repo.Info.WorkingDirectory, fileName, input);
repo.Stage(fileName);
var commit = repo.Commit("new file");
var blob = (Blob)commit.Tree[fileName].Target;
return blob;
}
private static void CreateAttributesFile(IRepository repo, string attributeEntry)
{
Touch(repo.Info.WorkingDirectory, ".gitattributes", attributeEntry);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Security.AccessControl;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Win32;
using NuGet;
using Squirrel.SimpleSplat;
using Squirrel.Shell;
namespace Squirrel
{
public sealed partial class UpdateManager : IUpdateManager, IEnableLogger
{
readonly string rootAppDirectory;
readonly string applicationName;
readonly IFileDownloader urlDownloader;
readonly string updateUrlOrPath;
IDisposable updateLock;
public UpdateManager(string urlOrPath,
string applicationName = null,
string rootDirectory = null,
IFileDownloader urlDownloader = null)
{
Contract.Requires(!String.IsNullOrEmpty(urlOrPath));
Contract.Requires(!String.IsNullOrEmpty(applicationName));
updateUrlOrPath = urlOrPath;
this.applicationName = applicationName ?? UpdateManager.getApplicationName();
this.urlDownloader = urlDownloader ?? new FileDownloader();
if (rootDirectory != null) {
this.rootAppDirectory = Path.Combine(rootDirectory, this.applicationName);
return;
}
this.rootAppDirectory = Path.Combine(rootDirectory ?? GetLocalAppDataDirectory(), this.applicationName);
}
public async Task<UpdateInfo> CheckForUpdate(bool ignoreDeltaUpdates = false, Action<int> progress = null, UpdaterIntention intention = UpdaterIntention.Update)
{
var checkForUpdate = new CheckForUpdateImpl(rootAppDirectory);
await acquireUpdateLock();
return await checkForUpdate.CheckForUpdate(intention, Utility.LocalReleaseFileForAppDir(rootAppDirectory), updateUrlOrPath, ignoreDeltaUpdates, progress, urlDownloader);
}
public async Task DownloadReleases(IEnumerable<ReleaseEntry> releasesToDownload, Action<int> progress = null)
{
var downloadReleases = new DownloadReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
await downloadReleases.DownloadReleases(updateUrlOrPath, releasesToDownload, progress, urlDownloader);
}
public async Task<string> ApplyReleases(UpdateInfo updateInfo, Action<int> progress = null)
{
var applyReleases = new ApplyReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
return await applyReleases.ApplyReleases(updateInfo, false, false, progress);
}
public async Task FullInstall(bool silentInstall = false, Action<int> progress = null)
{
var updateInfo = await CheckForUpdate(intention: UpdaterIntention.Install);
await DownloadReleases(updateInfo.ReleasesToApply);
var applyReleases = new ApplyReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
await applyReleases.ApplyReleases(updateInfo, silentInstall, true, progress);
}
public async Task FullUninstall()
{
var applyReleases = new ApplyReleasesImpl(rootAppDirectory);
await acquireUpdateLock();
this.KillAllExecutablesBelongingToPackage();
await applyReleases.FullUninstall();
}
public Task<RegistryKey> CreateUninstallerRegistryEntry(string uninstallCmd, string quietSwitch)
{
var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory);
return installHelpers.CreateUninstallerRegistryEntry(uninstallCmd, quietSwitch);
}
public Task<RegistryKey> CreateUninstallerRegistryEntry()
{
var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory);
return installHelpers.CreateUninstallerRegistryEntry();
}
public void RemoveUninstallerRegistryEntry()
{
var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory);
installHelpers.RemoveUninstallerRegistryEntry();
}
public void CreateShortcutsForExecutable(string exeName, ShortcutLocation locations, bool updateOnly, string programArguments = null, string icon = null)
{
var installHelpers = new ApplyReleasesImpl(rootAppDirectory);
installHelpers.CreateShortcutsForExecutable(exeName, locations, updateOnly, programArguments, icon);
}
public Dictionary<ShortcutLocation, ShellLink> GetShortcutsForExecutable(string exeName, ShortcutLocation locations, string programArguments = null)
{
var installHelpers = new ApplyReleasesImpl(rootAppDirectory);
return installHelpers.GetShortcutsForExecutable(exeName, locations, programArguments);
}
public void RemoveShortcutsForExecutable(string exeName, ShortcutLocation locations)
{
var installHelpers = new ApplyReleasesImpl(rootAppDirectory);
installHelpers.RemoveShortcutsForExecutable(exeName, locations);
}
public SemanticVersion CurrentlyInstalledVersion(string executable = null)
{
executable = executable ??
Path.GetDirectoryName(typeof(UpdateManager).Assembly.Location);
if (!executable.StartsWith(rootAppDirectory, StringComparison.OrdinalIgnoreCase)) {
return null;
}
var appDirName = executable.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.FirstOrDefault(x => x.StartsWith("app-", StringComparison.OrdinalIgnoreCase));
if (appDirName == null) return null;
return appDirName.ToSemanticVersion();
}
public void KillAllExecutablesBelongingToPackage()
{
var installHelpers = new InstallHelperImpl(applicationName, rootAppDirectory);
installHelpers.KillAllProcessesBelongingToPackage();
}
public string ApplicationName {
get { return applicationName; }
}
public string RootAppDirectory {
get { return rootAppDirectory; }
}
public bool IsInstalledApp {
get { return Assembly.GetExecutingAssembly().Location.StartsWith(RootAppDirectory, StringComparison.OrdinalIgnoreCase); }
}
public void Dispose()
{
var disp = Interlocked.Exchange(ref updateLock, null);
if (disp != null) {
disp.Dispose();
}
}
static bool exiting = false;
public static void RestartApp(string exeToStart = null, string arguments = null)
{
// NB: Here's how this method works:
//
// 1. We're going to pass the *name* of our EXE and the params to
// Update.exe
// 2. Update.exe is going to grab our PID (via getting its parent),
// then wait for us to exit.
// 3. We exit cleanly, dropping any single-instance mutexes or
// whatever.
// 4. Update.exe unblocks, then we launch the app again, possibly
// launching a different version than we started with (this is why
// we take the app's *name* rather than a full path)
exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location);
var argsArg = arguments != null ?
String.Format("-a \"{0}\"", arguments) : "";
exiting = true;
Process.Start(getUpdateExe(), String.Format("--processStartAndWait \"{0}\" {1}", exeToStart, argsArg));
// NB: We have to give update.exe some time to grab our PID, but
// we can't use WaitForInputIdle because we probably don't have
// whatever WaitForInputIdle considers a message loop.
Thread.Sleep(500);
Environment.Exit(0);
}
public static async Task<Process> RestartAppWhenExited(string exeToStart = null, string arguments = null)
{
// NB: Here's how this method works:
//
// 1. We're going to pass the *name* of our EXE and the params to
// Update.exe
// 2. Update.exe is going to grab our PID (via getting its parent),
// then wait for us to exit.
// 3. Return control and new Process back to caller and allow them to Exit as desired.
// 4. After our process exits, Update.exe unblocks, then we launch the app again, possibly
// launching a different version than we started with (this is why
// we take the app's *name* rather than a full path)
exeToStart = exeToStart ?? Path.GetFileName(Assembly.GetEntryAssembly().Location);
var argsArg = arguments != null ?
String.Format("-a \"{0}\"", arguments) : "";
exiting = true;
var updateProcess = Process.Start(getUpdateExe(), String.Format("--processStartAndWait {0} {1}", exeToStart, argsArg));
await Task.Delay(500);
return updateProcess;
}
public static string GetLocalAppDataDirectory(string assemblyLocation = null)
{
// Try to divine our our own install location via reading tea leaves
//
// * We're Update.exe, running in the app's install folder
// * We're Update.exe, running on initial install from SquirrelTemp
// * We're a C# EXE with Squirrel linked in
var assembly = Assembly.GetEntryAssembly();
if (assemblyLocation == null && assembly == null) {
// dunno lol
return Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
}
assemblyLocation = assemblyLocation ?? assembly.Location;
if (Path.GetFileName(assemblyLocation).Equals("update.exe", StringComparison.OrdinalIgnoreCase)) {
// NB: Both the "SquirrelTemp" case and the "App's folder" case
// mean that the root app dir is one up
var oneFolderUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), "..");
return Path.GetFullPath(oneFolderUpFromAppFolder);
}
var twoFoldersUpFromAppFolder = Path.Combine(Path.GetDirectoryName(assemblyLocation), "..\\..");
return Path.GetFullPath(twoFoldersUpFromAppFolder);
}
~UpdateManager()
{
if (updateLock != null && !exiting) {
throw new Exception("You must dispose UpdateManager!");
}
}
Task<IDisposable> acquireUpdateLock()
{
if (updateLock != null) return Task.FromResult(updateLock);
return Task.Run(() => {
var key = Utility.CalculateStreamSHA1(new MemoryStream(Encoding.UTF8.GetBytes(rootAppDirectory)));
IDisposable theLock;
try {
theLock = ModeDetector.InUnitTestRunner() ?
Disposable.Create(() => {}) : new SingleGlobalInstance(key, TimeSpan.FromMilliseconds(2000));
} catch (TimeoutException) {
throw new TimeoutException("Couldn't acquire update lock, another instance may be running updates");
}
var ret = Disposable.Create(() => {
theLock.Dispose();
updateLock = null;
});
updateLock = ret;
return ret;
});
}
/// <summary>
/// Calculates the total percentage of a specific step that should report within a specific range.
/// <para />
/// If a step needs to report between 50 -> 75 %, this method should be used as CalculateProgress(percentage, 50, 75).
/// </summary>
/// <param name="percentageOfCurrentStep">The percentage of the current step, a value between 0 and 100.</param>
/// <param name="stepStartPercentage">The start percentage of the range the current step represents.</param>
/// <param name="stepEndPercentage">The end percentage of the range the current step represents.</param>
/// <returns>The calculated percentage that can be reported about the total progress.</returns>
internal static int CalculateProgress(int percentageOfCurrentStep, int stepStartPercentage, int stepEndPercentage)
{
// Ensure we are between 0 and 100
percentageOfCurrentStep = Math.Max(Math.Min(percentageOfCurrentStep, 100), 0);
var range = stepEndPercentage - stepStartPercentage;
var singleValue = range / 100d;
var totalPercentage = (singleValue * percentageOfCurrentStep) + stepStartPercentage;
return (int)totalPercentage;
}
static string getApplicationName()
{
var fi = new FileInfo(getUpdateExe());
return fi.Directory.Name;
}
static string getUpdateExe()
{
var assembly = Assembly.GetEntryAssembly();
// Are we update.exe?
if (assembly != null &&
Path.GetFileName(assembly.Location).Equals("update.exe", StringComparison.OrdinalIgnoreCase) &&
assembly.Location.IndexOf("app-", StringComparison.OrdinalIgnoreCase) == -1 &&
assembly.Location.IndexOf("SquirrelTemp", StringComparison.OrdinalIgnoreCase) == -1) {
return Path.GetFullPath(assembly.Location);
}
assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
var updateDotExe = Path.Combine(Path.GetDirectoryName(assembly.Location), "..\\Update.exe");
var target = new FileInfo(updateDotExe);
if (!target.Exists) throw new Exception("Update.exe not found, not a Squirrel-installed app?");
return target.FullName;
}
}
}
| |
using System;
using System.Collections;
using System.Web.Caching;
using Umbraco.Core;
using Umbraco.Core.Cache;
using Umbraco.Core.Logging;
using Umbraco.Core.Models;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Repositories;
using umbraco.DataLayer;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
namespace umbraco.BusinessLogic
{
/// <summary>
/// represents a Umbraco back end user
/// </summary>
[Obsolete("Use the UserService instead")]
public class User
{
internal IUser UserEntity;
private int? _lazyId;
private bool? _defaultToLiveEditing;
private readonly Hashtable _notifications = new Hashtable();
private bool _notificationsInitialized = false;
[Obsolete("Obsolete, For querying the database use the new UmbracoDatabase object ApplicationContext.Current.DatabaseContext.Database", false)]
private static ISqlHelper SqlHelper
{
get { return Application.SqlHelper; }
}
internal User(IUser user)
{
UserEntity = user;
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="ID">The ID.</param>
public User(int ID)
{
SetupUser(ID);
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="ID">The ID.</param>
/// <param name="noSetup">if set to <c>true</c> [no setup].</param>
public User(int ID, bool noSetup)
{
_lazyId = ID;
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="Login">The login.</param>
/// <param name="Password">The password.</param>
public User(string Login, string Password)
{
SetupUser(getUserId(Login, Password));
}
/// <summary>
/// Initializes a new instance of the <see cref="User"/> class.
/// </summary>
/// <param name="Login">The login.</param>
public User(string Login)
{
SetupUser(getUserId(Login));
}
private void SetupUser(int ID)
{
UserEntity = ApplicationContext.Current.Services.UserService.GetUserById(ID);
if (UserEntity == null)
{
throw new ArgumentException("No User exists with ID " + ID);
}
}
/// <summary>
/// Used to persist object changes to the database.
/// </summary>
public void Save()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
ApplicationContext.Current.Services.UserService.Save(UserEntity);
OnSaving(EventArgs.Empty);
}
/// <summary>
/// Gets or sets the users name.
/// </summary>
/// <value>The name.</value>
public string Name
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Name;
}
set
{
UserEntity.Name = value;
}
}
/// <summary>
/// Gets or sets the users email.
/// </summary>
/// <value>The email.</value>
public string Email
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Email;
}
set
{
UserEntity.Email = value;
}
}
/// <summary>
/// Gets or sets the users language.
/// </summary>
/// <value>The language.</value>
public string Language
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Language;
}
set
{
UserEntity.Language = value;
}
}
/// <summary>
/// Gets or sets the users password.
/// </summary>
/// <value>The password.</value>
public string Password
{
get
{
return GetPassword();
}
set
{
UserEntity.RawPasswordValue = value;
}
}
/// <summary>
/// Gets the password.
/// </summary>
/// <returns></returns>
public string GetPassword()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.RawPasswordValue;
}
/// <summary>
/// Determines whether this user is an admin.
/// </summary>
/// <returns>
/// <c>true</c> if this user is admin; otherwise, <c>false</c>.
/// </returns>
[Obsolete("Use Umbraco.Core.Models.IsAdmin extension method instead", false)]
public bool IsAdmin()
{
return UserEntity.IsAdmin();
}
[Obsolete("Do not use this method to validate credentials, use the user's membership provider to do authentication. This method will not work if the password format is 'Encrypted'")]
public bool ValidatePassword(string password)
{
var userLogin = ApplicationContext.Current.DatabaseContext.Database.ExecuteScalar<string>(
"SELECT userLogin FROM umbracoUser WHERE userLogin = @login AND UserPasword = @password",
new {login = LoginName, password = password});
return userLogin == this.LoginName;
}
/// <summary>
/// Determines whether this user is the root (super user).
/// </summary>
/// <returns>
/// <c>true</c> if this user is root; otherwise, <c>false</c>.
/// </returns>
public bool IsRoot()
{
return Id == 0;
}
/// <summary>
/// Gets the applications which the user has access to.
/// </summary>
/// <value>The users applications.</value>
public Application[] Applications
{
get
{
return GetApplications().ToArray();
}
}
/// <summary>
/// Get the application which the user has access to as a List
/// </summary>
/// <returns></returns>
public List<Application> GetApplications()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var allApps = Application.getAll();
var apps = new List<Application>();
var sections = UserEntity.AllowedSections;
foreach (var s in sections)
{
var app = allApps.SingleOrDefault(x => x.alias == s);
if (app != null)
apps.Add(app);
}
return apps;
}
/// <summary>
/// Gets or sets the users login name
/// </summary>
/// <value>The loginname.</value>
public string LoginName
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.Username;
}
set
{
if (EnsureUniqueLoginName(value, this) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", value));
UserEntity.Username = value;
}
}
private static bool EnsureUniqueLoginName(string loginName, User currentUser)
{
User[] u = User.getAllByLoginName(loginName);
if (u.Length != 0)
{
if (u[0].Id != currentUser.Id)
return false;
}
return true;
}
/// <summary>
/// Validates the users credentials.
/// </summary>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <returns></returns>
[Obsolete("Do not use this method to validate credentials, use the user's membership provider to do authentication. This method will not work if the password format is 'Encrypted'")]
public static bool validateCredentials(string lname, string passw)
{
return validateCredentials(lname, passw, true);
}
/// <summary>
/// Validates the users credentials.
/// </summary>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <param name="checkForUmbracoConsoleAccess">if set to <c>true</c> [check for umbraco console access].</param>
/// <returns></returns>
[Obsolete("Do not use this method to validate credentials, use the user's membership provider to do authentication. This method will not work if the password format is 'Encrypted'")]
public static bool validateCredentials(string lname, string passw, bool checkForUmbracoConsoleAccess)
{
string consoleCheckSql = "";
if (checkForUmbracoConsoleAccess)
consoleCheckSql = "and userNoConsole = 0 ";
object tmp = SqlHelper.ExecuteScalar<object>(
"select id from umbracoUser where userDisabled = 0 " + consoleCheckSql + " and userLogin = @login and userPassword = @pw",
SqlHelper.CreateParameter("@login", lname),
SqlHelper.CreateParameter("@pw", passw)
);
// Logging
if (tmp == null)
{
LogHelper.Info<User>("Login: '" + lname + "' failed, from IP: " + System.Web.HttpContext.Current.Request.UserHostAddress);
}
return (tmp != null);
}
/// <summary>
/// Gets or sets the type of the user.
/// </summary>
/// <value>The type of the user.</value>
public UserType UserType
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return new UserType(UserEntity.UserType);
}
set
{
UserEntity.UserType = value.UserTypeItem;
}
}
/// <summary>
/// Gets all users
/// </summary>
/// <returns></returns>
public static User[] getAll()
{
int totalRecs;
var users = ApplicationContext.Current.Services.UserService.GetAll(
0, int.MaxValue, out totalRecs);
return users.Select(x => new User(x))
.OrderBy(x => x.Name)
.ToArray();
}
/// <summary>
/// Gets the current user (logged in)
/// </summary>
/// <returns>A user or null</returns>
public static User GetCurrent()
{
try
{
if (BasePages.BasePage.umbracoUserContextID != "")
return GetUser(BasePages.BasePage.GetUserId(BasePages.BasePage.umbracoUserContextID));
else
return null;
}
catch (Exception)
{
return null;
}
}
/// <summary>
/// Gets all users by email.
/// </summary>
/// <param name="email">The email.</param>
/// <returns></returns>
public static User[] getAllByEmail(string email)
{
return getAllByEmail(email, false);
}
/// <summary>
/// Gets all users by email.
/// </summary>
/// <param name="email">The email.</param>
/// <param name="useExactMatch">match exact email address or partial email address.</param>
/// <returns></returns>
public static User[] getAllByEmail(string email, bool useExactMatch)
{
int totalRecs;
if (useExactMatch)
{
return ApplicationContext.Current.Services.UserService.FindByEmail(
email, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact)
.Select(x => new User(x))
.ToArray();
}
else
{
return ApplicationContext.Current.Services.UserService.FindByEmail(
string.Format("%{0}%", email), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard)
.Select(x => new User(x))
.ToArray();
}
}
/// <summary>
/// Gets all users by login name.
/// </summary>
/// <param name="login">The login.</param>
/// <returns></returns>
public static User[] getAllByLoginName(string login)
{
return GetAllByLoginName(login, false).ToArray();
}
/// <summary>
/// Gets all users by login name.
/// </summary>
/// <param name="login">The login.</param>
/// <param name="partialMatch">whether to use a partial match</param>
/// <returns></returns>
public static User[] getAllByLoginName(string login, bool partialMatch)
{
return GetAllByLoginName(login, partialMatch).ToArray();
}
public static IEnumerable<User> GetAllByLoginName(string login, bool partialMatch)
{
int totalRecs;
if (partialMatch)
{
return ApplicationContext.Current.Services.UserService.FindByUsername(
string.Format("%{0}%", login), 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Wildcard)
.Select(x => new User(x))
.ToArray();
}
else
{
return ApplicationContext.Current.Services.UserService.FindByUsername(
login, 0, int.MaxValue, out totalRecs, StringPropertyMatchType.Exact)
.Select(x => new User(x))
.ToArray();
}
}
/// <summary>
/// Create a new user.
/// </summary>
/// <param name="name">The full name.</param>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <param name="ut">The user type.</param>
public static User MakeNew(string name, string lname, string passw, UserType ut)
{
var user = new Umbraco.Core.Models.Membership.User(name, "", lname, passw, ut.UserTypeItem);
ApplicationContext.Current.Services.UserService.Save(user);
var u = new User(user);
u.OnNew(EventArgs.Empty);
return u;
}
/// <summary>
/// Creates a new user.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="lname">The lname.</param>
/// <param name="passw">The passw.</param>
/// <param name="email">The email.</param>
/// <param name="ut">The ut.</param>
public static User MakeNew(string name, string lname, string passw, string email, UserType ut)
{
var user = new Umbraco.Core.Models.Membership.User(name, email, lname, passw, ut.UserTypeItem);
ApplicationContext.Current.Services.UserService.Save(user);
var u = new User(user);
u.OnNew(EventArgs.Empty);
return u;
}
/// <summary>
/// Updates the name, login name and password for the user with the specified id.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="name">The name.</param>
/// <param name="lname">The lname.</param>
/// <param name="email">The email.</param>
/// <param name="ut">The ut.</param>
public static void Update(int id, string name, string lname, string email, UserType ut)
{
if (EnsureUniqueLoginName(lname, GetUser(id)) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", lname));
var found = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (found == null) return;
found.Name = name;
found.Username = lname;
found.Email = email;
found.UserType = ut.UserTypeItem;
ApplicationContext.Current.Services.UserService.Save(found);
}
public static void Update(int id, string name, string lname, string email, bool disabled, bool noConsole, UserType ut)
{
if (EnsureUniqueLoginName(lname, GetUser(id)) == false)
throw new Exception(String.Format("A user with the login '{0}' already exists", lname));
var found = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (found == null) return;
found.Name = name;
found.Username = lname;
found.Email = email;
found.UserType = ut.UserTypeItem;
found.IsApproved = disabled == false;
found.IsLockedOut = noConsole;
ApplicationContext.Current.Services.UserService.Save(found);
}
/// <summary>
/// Updates the membership provider properties
/// </summary>
/// <param name="id">The id.</param>
/// <param name="email"></param>
/// <param name="disabled"></param>
/// <param name="noConsole"></param>
public static void Update(int id, string email, bool disabled, bool noConsole)
{
var found = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (found == null) return;
found.Email = email;
found.IsApproved = disabled == false;
found.IsLockedOut = noConsole;
ApplicationContext.Current.Services.UserService.Save(found);
}
/// <summary>
/// Gets the ID from the user with the specified login name and password
/// </summary>
/// <param name="lname">The login name.</param>
/// <param name="passw">The password.</param>
/// <returns>a user ID</returns>
public static int getUserId(string lname, string passw)
{
var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname);
return found.RawPasswordValue == passw ? found.Id : -1;
}
/// <summary>
/// Gets the ID from the user with the specified login name
/// </summary>
/// <param name="lname">The login name.</param>
/// <returns>a user ID</returns>
public static int getUserId(string lname)
{
var found = ApplicationContext.Current.Services.UserService.GetByUsername(lname);
return found == null ? -1 : found.Id;
}
/// <summary>
/// Deletes this instance.
/// </summary>
[Obsolete("Deleting users are NOT supported as history needs to be kept. Please use the disable() method instead")]
public void delete()
{
//make sure you cannot delete the admin user!
if (this.Id == 0)
throw new InvalidOperationException("The Administrator account cannot be deleted");
OnDeleting(EventArgs.Empty);
ApplicationContext.Current.Services.UserService.Delete(UserEntity, true);
FlushFromCache();
}
/// <summary>
/// Disables this instance.
/// </summary>
public void disable()
{
OnDisabling(EventArgs.Empty);
//delete without the true overload will perform the disable operation
ApplicationContext.Current.Services.UserService.Delete(UserEntity);
}
/// <summary>
/// Gets the users permissions based on a nodes path
/// </summary>
/// <param name="Path">The path.</param>
/// <returns></returns>
public string GetPermissions(string Path)
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var defaultPermissions = UserType.DefaultPermissions;
var cachedPermissions = ApplicationContext.Current.Services.UserService.GetPermissions(UserEntity)
.ToArray();
// NH 4.7.1 changing default permission behavior to default to User Type permissions IF no specific permissions has been
// set for the current node
var nodeId = Path.Contains(",") ? int.Parse(Path.Substring(Path.LastIndexOf(",", StringComparison.Ordinal) + 1)) : int.Parse(Path);
if (cachedPermissions.Any(x => x.EntityId == nodeId))
{
var found = cachedPermissions.First(x => x.EntityId == nodeId);
return string.Join("", found.AssignedPermissions);
}
// exception to everything. If default cruds is empty and we're on root node; allow browse of root node
if (string.IsNullOrEmpty(defaultPermissions) && Path == "-1")
defaultPermissions = "F";
// else return default user type cruds
return defaultPermissions;
}
/// <summary>
/// Initializes the user node permissions
/// </summary>
[Obsolete("This method doesn't do anything whatsoever and will be removed in future versions")]
public void initCruds()
{
}
/// <summary>
/// Gets a users notifications for a specified node path.
/// </summary>
/// <param name="Path">The node path.</param>
/// <returns></returns>
public string GetNotifications(string Path)
{
string notifications = "";
if (_notificationsInitialized == false)
initNotifications();
foreach (string nodeId in Path.Split(','))
{
if (_notifications.ContainsKey(int.Parse(nodeId)))
notifications = _notifications[int.Parse(nodeId)].ToString();
}
return notifications;
}
/// <summary>
/// Clears the internal hashtable containing cached information about notifications for the user
/// </summary>
public void resetNotificationCache()
{
_notificationsInitialized = false;
_notifications.Clear();
}
/// <summary>
/// Initializes the notifications and caches them.
/// </summary>
public void initNotifications()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
var notifications = ApplicationContext.Current.Services.NotificationService.GetUserNotifications(UserEntity);
foreach (var n in notifications.OrderBy(x => x.EntityId))
{
int nodeId = n.EntityId;
if (_notifications.ContainsKey(nodeId) == false)
{
_notifications.Add(nodeId, string.Empty);
}
_notifications[nodeId] += n.Action;
}
_notificationsInitialized = true;
}
/// <summary>
/// Gets the user id.
/// </summary>
/// <value>The id.</value>
public int Id
{
get { return UserEntity.Id; }
}
/// <summary>
/// Clears the list of applications the user has access to, ensure to call Save afterwords
/// </summary>
public void ClearApplications()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
foreach (var s in UserEntity.AllowedSections.ToArray())
{
UserEntity.RemoveAllowedSection(s);
}
}
/// <summary>
/// Clears the list of applications the user has access to.
/// </summary>
[Obsolete("This method will implicitly cause a database save and will reset the current user's dirty property, do not use this method, use the ClearApplications method instead and then call Save() when you are done performing all user changes to persist the chagnes in one transaction")]
public void clearApplications()
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
foreach (var s in UserEntity.AllowedSections.ToArray())
{
UserEntity.RemoveAllowedSection(s);
}
//For backwards compatibility this requires an implicit save
ApplicationContext.Current.Services.UserService.Save(UserEntity);
}
/// <summary>
/// Adds a application to the list of allowed applications, ensure to call Save() afterwords
/// </summary>
/// <param name="appAlias"></param>
public void AddApplication(string appAlias)
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
UserEntity.AddAllowedSection(appAlias);
}
/// <summary>
/// Adds a application to the list of allowed applications
/// </summary>
/// <param name="AppAlias">The app alias.</param>
[Obsolete("This method will implicitly cause a multiple database saves and will reset the current user's dirty property, do not use this method, use the AddApplication method instead and then call Save() when you are done performing all user changes to persist the chagnes in one transaction")]
public void addApplication(string AppAlias)
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
UserEntity.AddAllowedSection(AppAlias);
//For backwards compatibility this requires an implicit save
ApplicationContext.Current.Services.UserService.Save(UserEntity);
}
/// <summary>
/// Gets or sets a value indicating whether the user has access to the Umbraco back end.
/// </summary>
/// <value><c>true</c> if the user has access to the back end; otherwise, <c>false</c>.</value>
public bool NoConsole
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.IsLockedOut;
}
set
{
UserEntity.IsLockedOut = value;
}
}
/// <summary>
/// Gets or sets a value indicating whether this <see cref="User"/> is disabled.
/// </summary>
/// <value><c>true</c> if disabled; otherwise, <c>false</c>.</value>
public bool Disabled
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.IsApproved == false;
}
set
{
UserEntity.IsApproved = value == false;
}
}
/// <summary>
/// <summary>
/// Gets or sets the start content node id.
/// </summary>
/// <value>The start node id.</value>
public int StartNodeId
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.StartContentId;
}
set
{
UserEntity.StartContentId = value;
}
}
/// <summary>
/// Gets or sets the start media id.
/// </summary>
/// <value>The start media id.</value>
public int StartMediaId
{
get
{
if (_lazyId.HasValue) SetupUser(_lazyId.Value);
return UserEntity.StartMediaId;
}
set
{
UserEntity.StartMediaId = value;
}
}
/// <summary>
/// Flushes the user from cache.
/// </summary>
[Obsolete("This method should not be used, cache flushing is handled automatically by event handling in the web application and ensures that all servers are notified, this will not notify all servers in a load balanced environment")]
public void FlushFromCache()
{
OnFlushingFromCache(EventArgs.Empty);
ApplicationContext.Current.ApplicationCache.IsolatedRuntimeCache.ClearCache<IUser>();
}
/// <summary>
/// Gets the user with a specified ID
/// </summary>
/// <param name="id">The id.</param>
/// <returns></returns>
[Obsolete("The legacy user object should no longer be used, use the WebSecurity class to access the current user or the UserService to retrieve a user by id")]
public static User GetUser(int id)
{
var result = ApplicationContext.Current.Services.UserService.GetUserById(id);
if (result == null)
{
throw new ArgumentException("No user found with id " + id);
}
return new User(result);
}
//EVENTS
/// <summary>
/// The save event handler
/// </summary>
public delegate void SavingEventHandler(User sender, EventArgs e);
/// <summary>
/// The new event handler
/// </summary>
public delegate void NewEventHandler(User sender, EventArgs e);
/// <summary>
/// The disable event handler
/// </summary>
public delegate void DisablingEventHandler(User sender, EventArgs e);
/// <summary>
/// The delete event handler
/// </summary>
public delegate void DeletingEventHandler(User sender, EventArgs e);
/// <summary>
/// The Flush User from cache event handler
/// </summary>
public delegate void FlushingFromCacheEventHandler(User sender, EventArgs e);
/// <summary>
/// Occurs when [saving].
/// </summary>
public static event SavingEventHandler Saving;
/// <summary>
/// Raises the <see cref="E:Saving"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnSaving(EventArgs e)
{
if (Saving != null)
Saving(this, e);
}
/// <summary>
/// Occurs when [new].
/// </summary>
public static event NewEventHandler New;
/// <summary>
/// Raises the <see cref="E:New"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnNew(EventArgs e)
{
if (New != null)
New(this, e);
}
/// <summary>
/// Occurs when [disabling].
/// </summary>
public static event DisablingEventHandler Disabling;
/// <summary>
/// Raises the <see cref="E:Disabling"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnDisabling(EventArgs e)
{
if (Disabling != null)
Disabling(this, e);
}
/// <summary>
/// Occurs when [deleting].
/// </summary>
public static event DeletingEventHandler Deleting;
/// <summary>
/// Raises the <see cref="E:Deleting"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnDeleting(EventArgs e)
{
if (Deleting != null)
Deleting(this, e);
}
/// <summary>
/// Occurs when [flushing from cache].
/// </summary>
public static event FlushingFromCacheEventHandler FlushingFromCache;
/// <summary>
/// Raises the <see cref="E:FlushingFromCache"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void OnFlushingFromCache(EventArgs e)
{
if (FlushingFromCache != null)
FlushingFromCache(this, e);
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Semantics;
using Microsoft.Cci;
using Microsoft.Cci.MutableCodeModel;
using System.Diagnostics.Contracts;
using R = Microsoft.CodeAnalysis.Common.Symbols;
using Microsoft.CodeAnalysis.Common;
using Microsoft.CodeAnalysis.Common.Semantics;
namespace CSharp2CCI {
internal class StatementVisitor : Microsoft.CodeAnalysis.CSharp.SyntaxVisitor<IStatement> {
#region Fields
private IMetadataHost host;
CommonSemanticModel semanticModel;
ReferenceMapper mapper;
IMethodDefinition method;
SyntaxTree tree;
ExpressionVisitor expressionVisitor;
#endregion
public StatementVisitor(IMetadataHost host, CommonSemanticModel semanticModel, ReferenceMapper mapper, IMethodDefinition method, ExpressionVisitor expressionVisitor)
{
this.host = host;
this.semanticModel = semanticModel;
this.mapper = mapper;
this.method = method;
this.tree = semanticModel.SyntaxTree as SyntaxTree;
this.expressionVisitor = expressionVisitor;
}
public override IStatement VisitBlock(BlockSyntax node) {
var statements = new List<IStatement>();
BlockStatement bs = new BlockStatement() {
Statements = statements,
};
statements.Add(
new EmptyStatement() { Locations = Helper.SourceLocation(this.tree, node.OpenBraceToken), }
);
foreach (var s in node.Statements) {
var s_prime = this.Visit(s);
statements.Add(s_prime);
}
statements.Add(
new EmptyStatement() { Locations = Helper.SourceLocation(this.tree, node.CloseBraceToken), }
);
return bs;
}
public override IStatement VisitBreakStatement(BreakStatementSyntax node) {
return new BreakStatement();
}
public override IStatement VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node) {
return this.Visit(node.Declaration);
}
public override IStatement VisitElseClause(ElseClauseSyntax node) {
return this.Visit(node.Statement);
}
public override IStatement VisitEmptyStatement(EmptyStatementSyntax node) {
return CodeDummy.LabeledStatement;
}
public override IStatement VisitExpressionStatement(ExpressionStatementSyntax node) {
var s = new ExpressionStatement() {
Expression = this.expressionVisitor.Visit(node.Expression),
Locations = Helper.SourceLocation(this.tree, node),
};
return s;
}
public override IStatement VisitForStatement(ForStatementSyntax node) {
var newInitializers = new List<IStatement>();
if (node.Declaration != null) {
var loopLocals = node.Declaration.Variables;
foreach (var variableDecl in loopLocals) {
var s = (Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol)this.semanticModel.GetDeclaredSymbol(variableDecl);
var local = new LocalDefinition() {
Name = this.host.NameTable.GetNameFor(s.Name),
MethodDefinition = this.method,
Type = this.mapper.Map(s.Type),
};
this.expressionVisitor.RegisterLocal(s, local);
if (variableDecl.Initializer != null) {
var initialValue = variableDecl.Initializer.Value;
newInitializers.Add(
new LocalDeclarationStatement() {
InitialValue = this.expressionVisitor.Visit(initialValue),
LocalVariable = local,
}
);
}
}
}
var forStmt = new ForStatement() {
Body = this.Visit(node.Statement),
InitStatements = newInitializers,
Locations = Helper.SourceLocation(this.tree, node),
};
if (node.Condition != null)
forStmt.Condition = this.expressionVisitor.Visit(node.Condition);
var newIncrementors = new List<IStatement>();
foreach (var incrementor in node.Incrementors){
var incr_prime = this.expressionVisitor.Visit(incrementor);
newIncrementors.Add(
new ExpressionStatement() {
Expression = incr_prime,
});
}
forStmt.IncrementStatements = newIncrementors;
return forStmt;
}
public override IStatement VisitForEachStatement(ForEachStatementSyntax node) {
var s = this.semanticModel.GetDeclaredSymbol(node) as Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol;
if (s != null) {
var local = new LocalDefinition() {
Name = this.host.NameTable.GetNameFor(s.Name),
MethodDefinition = this.method,
Type = this.mapper.Map(s.Type),
};
this.expressionVisitor.RegisterLocal(s, local);
var body = this.Visit(node.Statement);
var foreachStmt = new ForEachStatement() {
Body = this.Visit(node.Statement),
Collection = this.expressionVisitor.Visit(node.Expression),
Variable = local,
Locations = Helper.SourceLocation(this.tree, node),
};
if (!(foreachStmt.Collection.Type is IArrayTypeReference)) {
var msg = String.Format("VisitForEachStatement can't handle the type '{0}'", TypeHelper.GetTypeName(foreachStmt.Collection.Type, NameFormattingOptions.None));
throw new InvalidDataException(msg);
}
return foreachStmt;
}
throw new InvalidDataException("VisitForEachStatement couldn't find something to return");
}
private Dictionary<object, ILabeledStatement> labelTable = new Dictionary<object, ILabeledStatement>();
public override IStatement VisitGotoStatement(GotoStatementSyntax node) {
var e = node.Expression as IdentifierNameSyntax;
ILabeledStatement l;
if (!this.labelTable.TryGetValue(e.Identifier.Value, out l)) {
l = new LabeledStatement() {
Label = this.host.NameTable.GetNameFor(e.GetText().ToString()),
Locations = Helper.SourceLocation(this.tree, node),
};
this.labelTable.Add(e.Identifier.Value, l);
}
return new GotoStatement() {
TargetStatement = l,
};
}
public override IStatement VisitIfStatement(IfStatementSyntax node) {
var e = this.expressionVisitor.Visit(node.Condition);
var thenStmt = this.Visit(node.Statement);
var cond = new ConditionalStatement() {
Condition = e,
Locations = Helper.SourceLocation(this.tree, node), //.Condition),
TrueBranch = thenStmt,
};
IStatement elseStmt = new EmptyStatement();
if (node.Else != null) {
elseStmt = this.Visit(node.Else);
}
cond.FalseBranch = elseStmt;
return cond;
}
public override IStatement VisitLabeledStatement(LabeledStatementSyntax node) {
ILabeledStatement l;
var id = node.Identifier;
if (!this.labelTable.TryGetValue(id.Value, out l)) {
l = new LabeledStatement() {
Label = this.host.NameTable.GetNameFor(id.ValueText),
Locations = Helper.SourceLocation(this.tree, node),
};
this.labelTable.Add(id.Value, l);
}
var s_prime = this.Visit(node.Statement);
return new BlockStatement() {
Statements = new List<IStatement>(){ l, s_prime, },
};
}
public override IStatement VisitReturnStatement(ReturnStatementSyntax node) {
var r = new ReturnStatement() {
Locations = Helper.SourceLocation(this.tree, node),
};
IExpression e = null;
if (node.Expression != null) {
e = this.expressionVisitor.Visit(node.Expression);
r.Expression = e;
}
return r;
}
public override IStatement VisitSwitchStatement(SwitchStatementSyntax node) {
var e = this.expressionVisitor.Visit(node.Expression);
var cases = new List<ISwitchCase>();
foreach (var switchCase in node.Sections) {
var labels = switchCase.Labels;
var i = 0;
foreach (var l in labels) {
var c = new SwitchCase();
if (++i == labels.Count) { // last label gets the body
var stmts = new List<IStatement>();
foreach (var s in switchCase.Statements) {
stmts.Add(this.Visit(s));
}
c.Body = stmts;
}
if (l.CaseOrDefaultKeyword.Kind == SyntaxKind.DefaultKeyword) {
c.Expression = CodeDummy.Constant;
} else {
// Default case is represented by a dummy Expression, so just don't set the Expression property
System.Diagnostics.Debug.Assert(l.Value != null);
var switchCaseExpression = this.expressionVisitor.Visit(l.Value);
c.Expression = (ICompileTimeConstant)switchCaseExpression;
}
cases.Add(c);
}
}
var switchStmt = new SwitchStatement() {
Cases = cases,
Expression = e,
Locations = Helper.SourceLocation(this.tree, node),
};
return switchStmt;
}
// TODO: Wait until Roslyn gets this implemented
public override IStatement VisitSwitchSection(SwitchSectionSyntax node) {
throw new InvalidDataException("VisitSwitchSection: should never be reached, should be handled as part of VisitSwitchStatement");
}
// TODO: Wait until Roslyn gets this implemented
public override IStatement VisitTryStatement(TryStatementSyntax node) {
var catches = new List<ICatchClause>();
foreach (var c in node.Catches) {
var c_prime = new CatchClause() {
//Body = MkBlockStatement(this.Visit(c.Block, arg)),
};
if (c.Declaration != null) {
var cDecl = c.Declaration;
}
}
var tcf = new TryCatchFinallyStatement() {
CatchClauses = catches,
Locations = Helper.SourceLocation(this.tree, node),
TryBody = Helper.MkBlockStatement(this.Visit(node.Block)),
};
if (node.Finally != null) {
tcf.FinallyBody = Helper.MkBlockStatement(this.Visit(node.Finally.Block));
}
return tcf;
}
public override IStatement VisitVariableDeclaration(VariableDeclarationSyntax node) {
ITypeReference t = null;
if (!node.Type.IsVar) {
var o = this.semanticModel.GetTypeInfo(node.Type);
t = this.mapper.Map(o.Type);
}
var decls = new List<IStatement>();
foreach (var v in node.Variables) {
var s = (Microsoft.CodeAnalysis.CSharp.Symbols.LocalSymbol) this.semanticModel.GetDeclaredSymbol(v);
IExpression initialValue = null;
if (v.Initializer != null) {
var evc = v.Initializer.Value;
initialValue = this.expressionVisitor.Visit(evc);
}
var local = new LocalDefinition() {
Name = this.host.NameTable.GetNameFor(s.Name),
MethodDefinition = this.method,
};
this.expressionVisitor.RegisterLocal(s, local);
if (t != null) {
local.Type = t;
} else if (initialValue != null) {
local.Type = initialValue.Type;
}
var ldc = new LocalDeclarationStatement() {
InitialValue = initialValue != null ? initialValue : null,
LocalVariable = local,
Locations = Helper.SourceLocation(this.tree, node),
};
decls.Add(ldc);
}
if (decls.Count == 1) {
return decls[0];
} else {
var bs = new BlockStatement() {
Statements = decls,
};
return bs;
}
}
public override IStatement VisitWhileStatement(WhileStatementSyntax node) {
var e = this.expressionVisitor.Visit(node.Condition);
var s = this.Visit(node.Statement);
return new WhileDoStatement() {
Body = s,
Condition = e,
Locations = Helper.SourceLocation(this.tree, node.Condition),
};
}
public override IStatement VisitThrowStatement(ThrowStatementSyntax node)
{
var e = this.expressionVisitor.Visit(node.Expression);
return new ThrowStatement()
{
Exception = e,
Locations = Helper.SourceLocation(this.tree, node.Expression),
};
}
public override IStatement DefaultVisit(SyntaxNode node) {
// If you hit this, it means there was some sort of CS construct
// that we haven't written a conversion routine for. Simply add
// it above and rerun.
var typeName = node.GetType().ToString();
var msg = String.Format("Was unable to convert a {0} node to CCI", typeName);
throw new ConverterException(msg);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace AIM.Service.Administrative.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Maintenance.cs" company="The Watcher">
// Copyright (c) The Watcher Partial Rights Reserved.
// This software is licensed under the MIT license. See license.txt for details.
// </copyright>
// <summary>
// Code Named: VG-Ripper
// Function : Extracts Images posted on RiP forums and attempts to fetch them to disk.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Ripper
{
#region
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Ripper.Core.Components;
#endregion
/// <summary>
/// Maintenance Class.
/// </summary>
public class Maintenance
{
#region Constants and Fields
/// <summary>
/// Gets or sets the instance.
/// </summary>
public static Maintenance Instance { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Gets the instance.
/// </summary>
/// <returns>
/// The get instance.
/// </returns>
public static Maintenance GetInstance()
{
return Instance ?? (Instance = new Maintenance());
}
/// <summary>
/// Count The Images from xml.
/// </summary>
/// <param name="xmlPayload">
/// The xml payload.
/// </param>
/// <returns>
/// Returns How Many Images the Post contains
/// </returns>
public List<string> GetAllPostIds(string xmlPayload)
{
var postIds = new List<string>();
try
{
var dataSet = new DataSet();
dataSet.ReadXml(new StringReader(xmlPayload));
postIds.AddRange(from DataRow row in dataSet.Tables["post"].Rows select row["id"].ToString());
}
catch (Exception)
{
return postIds;
}
return postIds;
}
/// <summary>
/// Count The Images from xml.
/// </summary>
/// <param name="xmlPayload">
/// The xml payload.
/// </param>
/// <returns>
/// Returns How Many Images the Post contains
/// </returns>
public int CountImagesFromXML(string xmlPayload)
{
try
{
var dataSet = new DataSet();
dataSet.ReadXml(new StringReader(xmlPayload));
foreach (DataRow row in dataSet.Tables["post"].Rows)
{
return Convert.ToInt32(row["imageCount"]);
}
}
catch (Exception)
{
return 0;
}
return 0;
}
/// <summary>
/// The extract forum title from xml.
/// </summary>
/// <param name="xmlPayload">
/// The xml payload.
/// </param>
/// <returns>
/// Returns the Forum Title
/// </returns>
public string ExtractForumTitleFromXML(string xmlPayload)
{
string forumTitle = string.Empty;
try
{
var dataSet = new DataSet();
dataSet.ReadXml(new StringReader(xmlPayload));
foreach (DataRow row in dataSet.Tables["forum"].Rows)
{
forumTitle = row["title"].ToString();
}
}
catch (Exception)
{
return string.Empty;
}
Utility.RemoveIllegalCharecters(forumTitle);
return forumTitle;
}
/// <summary>
/// The extract post title from xml.
/// </summary>
/// <param name="xmlPayload">
/// The xml payload.
/// </param>
/// <returns>
/// Returns the Post Title
/// </returns>
public string ExtractPostTitleFromXML(string xmlPayload)
{
var postTitle = string.Empty;
try
{
var dataSet = new DataSet();
dataSet.ReadXml(new StringReader(xmlPayload));
foreach (DataRow row in dataSet.Tables["post"].Rows)
{
postTitle = row["title"].ToString();
if (postTitle == string.Empty)
{
postTitle = string.Format("post# {0}", row["id"]);
}
else if (postTitle == string.Format("Re: {0}", this.ExtractTopicTitleFromXML(xmlPayload)))
{
postTitle = string.Format("post# {0}", row["id"]);
}
}
}
catch (Exception)
{
return string.Empty;
}
Utility.RemoveIllegalCharecters(postTitle);
return postTitle;
}
/// <summary>
/// Extract the Current Post Title if there is any
/// if not use PostId As Title
/// </summary>
/// <param name="content">
/// The content.
/// </param>
/// <param name="url">
/// The url.
/// </param>
/// <returns>
/// The extract post title from html.
/// </returns>
public string ExtractPostTitleFromHtml(string content, string url)
{
var postId = url.Substring(url.IndexOf("p=", StringComparison.Ordinal) + 2);
var check =
string.Format(
@"<h2 class=\""title icon\"">\r\n\t\t\t\t\t(?<inner>[^\r]*)\r\n\t\t\t\t</h2>\r\n\t\t\t\t\r\n\r\n\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t<div class=\""content\"">\r\n\t\t\t\t\t<div id=\""post_message_{0}\"">",
postId);
var check2 =
string.Format(
@"<h2 class=\""title icon\"">\r\n\t\t\t\t\t(?<inner>[^\r]*)\r\n\t\t\t\t</h2>\r\n\t\t\t\t\r\n\r\n\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t\t\r\n\t\t\t\t\t\t\r\n\t\t\t\t<div class=\""content\"">\r\n\t\t\t\t\t<div id=\""post_message_{0}\"">",
postId);
var match = Regex.Match(content, check, RegexOptions.Compiled);
var postTitle = string.Empty;
if (!match.Success)
{
match = Regex.Match(content, check2, RegexOptions.Compiled);
if (!match.Success)
{
return postTitle;
}
}
postTitle = match.Groups["inner"].Value.Trim();
if (postTitle == string.Empty)
{
postTitle = string.Format("post# {0}", postId);
}
else if (postTitle == string.Format("Re: {0}", this.ExtractTopicTitleFromHtml(content)))
{
postTitle = string.Format("post# {0}", postId);
}
// Remove Topic Icons if found
if (postTitle.Contains("<img"))
{
postTitle = postTitle.Substring(postTitle.IndexOf(" /> ", StringComparison.Ordinal) + 4);
}
return Utility.ReplaceHexWithAscii(postTitle);
}
/// <summary>
/// Extracts the topic title from XML.
/// </summary>
/// <param name="xmlPayload">The xml payload.</param>
/// <returns>
/// Returns the topic Title
/// </returns>
public string ExtractTopicTitleFromXML(string xmlPayload)
{
var title = string.Empty;
try
{
var dataSet = new DataSet();
dataSet.ReadXml(new StringReader(xmlPayload));
foreach (DataRow row in dataSet.Tables["thread"].Rows)
{
title = row["title"].ToString();
}
}
catch (Exception)
{
return string.Empty;
}
return Utility.RemoveIllegalCharecters(title);
}
/// <summary>
/// Extract Current Page Title
/// </summary>
/// <param name="page">The page.</param>
/// <returns>
/// The get rip page title.
/// </returns>
public string ExtractTopicTitleFromHtml(string page)
{
var match = Regex.Match(
page,
@"<title>(?<inner>[^<]*)</title>",
RegexOptions.Compiled);
if (!match.Success)
{
return string.Empty;
}
var title = match.Groups["inner"].Value;
if (title.Contains(" - Page"))
{
title = title.Remove(title.IndexOf(" - Page", StringComparison.Ordinal));
}
return title.Trim();
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Net.Mail;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Client;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
public class ScriptProtectionModule
{
#region Declares
private IConfig m_config;
private bool allowHTMLLinking = true;
//Threat Level for scripts.
private ThreatLevel m_MaxThreatLevel = 0;
//List of all enabled APIs for scripts
private List<string> EnabledAPIs = new List<string>();
//Which owners have access to which functions
private Dictionary<string, List<UUID> > m_FunctionPerms = new Dictionary<string, List<UUID> >();
//Keeps track of whether the source has been compiled before
public Dictionary<string, string> PreviouslyCompiled = new Dictionary<string, string>();
public Dictionary<UUID, UUID> ScriptsItems = new Dictionary<UUID, UUID>();
public Dictionary<UUID, Dictionary<UUID, ScriptData>> Scripts = new Dictionary<UUID, Dictionary<UUID, ScriptData>>();
public bool AllowHTMLLinking
{
get
{
return allowHTMLLinking;
}
}
#endregion
#region Constructor
public ScriptProtectionModule(IConfig config)
{
m_config = config;
EnabledAPIs = new List<string>(config.GetString("AllowedAPIs", "LSL").Split(','));
allowHTMLLinking = config.GetBoolean("AllowHTMLLinking", true);
GetThreatLevel();
}
#endregion
#region ThreatLevels
public ThreatLevel GetThreatLevel()
{
if(m_MaxThreatLevel != 0)
return m_MaxThreatLevel;
string risk = m_config.GetString("FunctionThreatLevel", "VeryLow");
switch (risk)
{
case "None":
m_MaxThreatLevel = ThreatLevel.None;
break;
case "VeryLow":
m_MaxThreatLevel = ThreatLevel.VeryLow;
break;
case "Low":
m_MaxThreatLevel = ThreatLevel.Low;
break;
case "Moderate":
m_MaxThreatLevel = ThreatLevel.Moderate;
break;
case "High":
m_MaxThreatLevel = ThreatLevel.High;
break;
case "VeryHigh":
m_MaxThreatLevel = ThreatLevel.VeryHigh;
break;
case "Severe":
m_MaxThreatLevel = ThreatLevel.Severe;
break;
default:
break;
}
return m_MaxThreatLevel;
}
public bool CheckAPI(string Name)
{
if (!EnabledAPIs.Contains(Name))
return false;
return true;
}
public void CheckThreatLevel(ThreatLevel level, string function, ISceneChildEntity m_host, string API)
{
List<UUID> FunctionPerms = new List<UUID>();
if (!m_FunctionPerms.TryGetValue(function, out FunctionPerms))
{
string perm = m_config.GetString("Allow_" + function, "");
if (perm == "")
{
FunctionPerms = null;// a null value is default
}
else
{
bool allowed;
if (bool.TryParse(perm, out allowed))
{
// Boolean given
if (allowed)
{
FunctionPerms = new List<UUID>();
FunctionPerms.Add(UUID.Zero);
}
else
FunctionPerms = new List<UUID>(); // Empty list = none
}
else
{
FunctionPerms = new List<UUID>();
string[] ids = perm.Split(new char[] {','});
foreach (string id in ids)
{
string current = id.Trim();
UUID uuid;
if (UUID.TryParse(current, out uuid))
{
if (uuid != UUID.Zero)
FunctionPerms.Add(uuid);
}
}
}
m_FunctionPerms[function] = FunctionPerms;
}
}
// If the list is null, then the value was true / undefined
// Threat level governs permissions in this case
//
// If the list is non-null, then it is a list of UUIDs allowed
// to use that particular function. False causes an empty
// list and therefore means "no one"
//
// To allow use by anyone, the list contains UUID.Zero
//
if (FunctionPerms == null) // No list = true
{
if (level > m_MaxThreatLevel)
Error("Runtime Error: ",
String.Format(
"{0} permission denied. Allowed threat level is {1} but function threat level is {2}.",
function, m_MaxThreatLevel, level));
}
else
{
if (!FunctionPerms.Contains(UUID.Zero))
{
if (!FunctionPerms.Contains(m_host.OwnerID))
Error("Runtime Error: ",
String.Format("{0} permission denied. Prim owner is not in the list of users allowed to execute this function.",
function));
}
}
}
internal void Error(string surMessage, string msg)
{
throw new Exception(surMessage + msg);
}
#endregion
#region Previously Compiled Scripts
/// <summary>
/// Reset all lists (if hard), if not hard, just reset previously compiled
/// </summary>
/// <param name="hard"></param>
public void Reset(bool hard)
{
lock (PreviouslyCompiled)
{
PreviouslyCompiled.Clear();
}
if (hard)
{
lock (ScriptsItems)
{
ScriptsItems.Clear();
}
lock (Scripts)
{
Scripts.Clear();
}
}
}
public void AddPreviouslyCompiled (string source, ScriptData ID)
{
//string key = source.Length.ToString() + source.GetHashCode().ToString();
string key = Util.Md5Hash (source);
lock (PreviouslyCompiled)
{
if (!PreviouslyCompiled.ContainsKey (key))
{
//PreviouslyCompiled.Add (source, ID.AssemblyName);
PreviouslyCompiled.Add (key, ID.AssemblyName);
}
}
}
public void RemovePreviouslyCompiled (string source)
{
//string key = source.Length.ToString() + source.GetHashCode().ToString();
string key = Util.Md5Hash (source);
lock (PreviouslyCompiled)
{
if (PreviouslyCompiled.ContainsKey (key))
{
PreviouslyCompiled.Remove (key);
//PreviouslyCompiled.Remove (source);
}
}
}
public string TryGetPreviouslyCompiledScript (string source)
{
//string key = source.Length.ToString() + source.GetHashCode().ToString();
string key = Util.Md5Hash (source);
string assemblyName = "";
PreviouslyCompiled.TryGetValue (key, out assemblyName);
//PreviouslyCompiled.TryGetValue (source, out assemblyName);
return assemblyName;
}
public ScriptData GetScript(UUID primID, UUID itemID)
{
Dictionary<UUID, ScriptData> Instances;
lock (Scripts)
{
if (Scripts.TryGetValue(primID, out Instances))
{
ScriptData ID = null;
Instances.TryGetValue(itemID, out ID);
return ID;
}
}
return null;
}
public ScriptData GetScript(UUID itemID)
{
lock (ScriptsItems)
{
UUID primID;
if (ScriptsItems.TryGetValue(itemID, out primID))
return GetScript(primID, itemID);
return null;
}
}
public ScriptData[] GetScripts(UUID primID)
{
Dictionary<UUID, ScriptData> Instances;
lock (Scripts)
{
if (Scripts.TryGetValue(primID, out Instances))
return new List<ScriptData>(Instances.Values).ToArray();
}
return null;
}
public void AddNewScript(ScriptData ID)
{
lock (ScriptsItems)
{
if(ID.Part != null)
ScriptsItems[ID.ItemID] = ID.Part.UUID;
}
lock (Scripts)
{
Dictionary<UUID, ScriptData> Instances = new Dictionary<UUID, ScriptData>();
if (!Scripts.TryGetValue(ID.Part.UUID, out Instances))
Instances = new Dictionary<UUID, ScriptData>();
Instances[ID.ItemID] = ID;
Scripts[ID.Part.UUID] = Instances;
}
}
public ScriptData[] GetAllScripts()
{
List<ScriptData> Ids = new List<ScriptData>();
lock (Scripts)
{
foreach (Dictionary<UUID, ScriptData> Instances in Scripts.Values)
{
foreach (ScriptData ID in Instances.Values)
{
Ids.Add(ID);
}
}
}
return Ids.ToArray();
}
public void RemoveScript(ScriptData Data)
{
lock (ScriptsItems)
{
ScriptsItems.Remove(Data.ItemID);
}
lock (Scripts)
{
Dictionary<UUID, ScriptData> Instances = new Dictionary<UUID, ScriptData>();
if (Scripts.ContainsKey(Data.Part.UUID))
{
Instances = Scripts[Data.Part.UUID];
Instances.Remove(Data.ItemID);
}
Scripts[Data.Part.UUID] = Instances;
}
}
#endregion
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
namespace OpenMetaverse.GUI
{
/// <summary>
/// ListView GUI component for viewing a client's friend list
/// </summary>
public class FriendList : ListView
{
private GridClient _Client;
private ColumnSorter _ColumnSorter = new ColumnSorter();
public delegate void FriendDoubleClickCallback(FriendInfo friend);
/// <summary>
/// Triggered when the user double clicks on a friend in the list
/// </summary>
public event FriendDoubleClickCallback OnFriendDoubleClick;
/// <summary>
/// Gets or sets the GridClient associated with this control
/// </summary>
public GridClient Client
{
get { return _Client; }
set { if (value != null) InitializeClient(value); }
}
/// <summary>
/// TreeView control for an unspecified client's friend list
/// </summary>
public FriendList()
{
ColumnHeader header1 = this.Columns.Add("Friend");
header1.Width = this.Width - 20;
ColumnHeader header2 = this.Columns.Add(" ");
header2.Width = 40;
_ColumnSorter.SortColumn = 1;
_ColumnSorter.Ascending = false;
this.DoubleBuffered = true;
this.ListViewItemSorter = _ColumnSorter;
this.View = View.Details;
this.ColumnClick += new ColumnClickEventHandler(FriendList_ColumnClick);
this.DoubleClick += new System.EventHandler(FriendList_DoubleClick);
}
/// <summary>
/// TreeView control for the specified client's friend list
/// </summary>
public FriendList(GridClient client) : this ()
{
InitializeClient(client);
}
private void InitializeClient(GridClient client)
{
_Client = client;
_Client.Friends.OnFriendNamesReceived += new FriendsManager.FriendNamesReceived(Friends_OnFriendNamesReceived);
_Client.Friends.OnFriendOffline += new FriendsManager.FriendOfflineEvent(Friends_OnFriendOffline);
_Client.Friends.OnFriendOnline += new FriendsManager.FriendOnlineEvent(Friends_OnFriendOnline);
_Client.Network.OnLogin += new NetworkManager.LoginCallback(Network_OnLogin);
}
private void RefreshFriends()
{
if (this.InvokeRequired) this.BeginInvoke((MethodInvoker)delegate { RefreshFriends(); });
else
{
Client.Friends.FriendList.ForEach(delegate(FriendInfo friend)
{
string key = friend.UUID.ToString();
string onlineText;
string name = friend.Name == null ? "(loading...)" : friend.Name;
int image;
Color color;
if (friend.IsOnline)
{
image = 1;
onlineText = "*";
color = Color.FromKnownColor(KnownColor.ControlText);
}
else
{
image = 0;
onlineText = " ";
color = Color.FromKnownColor(KnownColor.GrayText);
}
if (!this.Items.ContainsKey(key))
{
this.Items.Add(key, name, image);
this.Items[key].SubItems.Add(onlineText);
}
else
{
if (this.Items[key].Text == string.Empty || friend.Name != null)
this.Items[key].Text = name;
this.Items[key].SubItems[1].Text = onlineText;
}
this.Items[key].ForeColor = color;
this.Items[key].ImageIndex = image;
this.Items[key].Tag = friend;
});
}
}
private void Friends_OnFriendOffline(FriendInfo friend)
{
RefreshFriends();
}
private void Friends_OnFriendOnline(FriendInfo friend)
{
RefreshFriends();
}
private void Friends_OnFriendNamesReceived(Dictionary<UUID, string> names)
{
RefreshFriends();
}
private void FriendList_ColumnClick(object sender, ColumnClickEventArgs e)
{
_ColumnSorter.SortColumn = e.Column;
if ((_ColumnSorter.Ascending = (this.Sorting == SortOrder.Ascending))) this.Sorting = SortOrder.Descending;
else this.Sorting = SortOrder.Ascending;
this.ListViewItemSorter = _ColumnSorter;
}
private void FriendList_DoubleClick(object sender, System.EventArgs e)
{
if (OnFriendDoubleClick != null)
{
ListView list = (ListView)sender;
if (list.SelectedItems.Count > 0 && list.SelectedItems[0].Tag is FriendInfo)
{
FriendInfo friend = (FriendInfo)list.SelectedItems[0].Tag;
try { OnFriendDoubleClick(friend); }
catch (Exception ex) { Logger.Log(ex.Message, Helpers.LogLevel.Error, Client, ex); }
}
}
}
private void Network_OnLogin(LoginStatus login, string message)
{
if (login == LoginStatus.Success) RefreshFriends();
}
private class ColumnSorter : IComparer
{
public bool Ascending = true;
public int SortColumn = 0;
public int Compare(object a, object b)
{
ListViewItem itemA = (ListViewItem)a;
ListViewItem itemB = (ListViewItem)b;
if (SortColumn == 1)
{
string onlineA = itemA.SubItems.Count < 2 ? string.Empty : itemA.SubItems[1].Text;
string onlineB = itemB.SubItems.Count < 2 ? string.Empty : itemB.SubItems[1].Text;
if (Ascending) return string.Compare(onlineA + itemA.Text, onlineB + itemB.Text);
else return -string.Compare(onlineA + itemA.Text, onlineB + itemB.Text);
}
else
{
if (Ascending) return string.Compare(itemA.Text, itemB.Text);
else return -string.Compare(itemA.Text, itemB.Text);
}
}
}
}
}
| |
//
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Microsoft.WindowsAzure;
namespace Microsoft.Azure.Management.Resources
{
public static partial class DeploymentOperationsExtensions
{
/// <summary>
/// Cancel a currently running template deployment.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static OperationResponse Cancel(this IDeploymentOperations operations, string resourceGroupName, string deploymentName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).CancelAsync(resourceGroupName, deploymentName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Cancel a currently running template deployment.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<OperationResponse> CancelAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName)
{
return operations.CancelAsync(resourceGroupName, deploymentName, CancellationToken.None);
}
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Additional parameters supplied to the operation.
/// </param>
/// <returns>
/// Template deployment operation create result.
/// </returns>
public static DeploymentOperationsCreateResult CreateOrUpdate(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, BasicDeployment parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).CreateOrUpdateAsync(resourceGroupName, deploymentName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a named template deployment using a template.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Additional parameters supplied to the operation.
/// </param>
/// <returns>
/// Template deployment operation create result.
/// </returns>
public static Task<DeploymentOperationsCreateResult> CreateOrUpdateAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, BasicDeployment parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, deploymentName, parameters, CancellationToken.None);
}
/// <summary>
/// Get a deployment.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <returns>
/// Template deployment information.
/// </returns>
public static DeploymentGetResult Get(this IDeploymentOperations operations, string resourceGroupName, string deploymentName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).GetAsync(resourceGroupName, deploymentName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a deployment.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to get. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <returns>
/// Template deployment information.
/// </returns>
public static Task<DeploymentGetResult> GetAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName)
{
return operations.GetAsync(resourceGroupName, deploymentName, CancellationToken.None);
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to filter by. The name is
/// case insensitive.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all
/// deployments.
/// </param>
/// <returns>
/// List of deployments.
/// </returns>
public static DeploymentListResult List(this IDeploymentOperations operations, string resourceGroupName, DeploymentListParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).ListAsync(resourceGroupName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group to filter by. The name is
/// case insensitive.
/// </param>
/// <param name='parameters'>
/// Optional. Query parameters. If null is passed returns all
/// deployments.
/// </param>
/// <returns>
/// List of deployments.
/// </returns>
public static Task<DeploymentListResult> ListAsync(this IDeploymentOperations operations, string resourceGroupName, DeploymentListParameters parameters)
{
return operations.ListAsync(resourceGroupName, parameters, CancellationToken.None);
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List of deployments.
/// </returns>
public static DeploymentListResult ListNext(this IDeploymentOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get a list of deployments.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <returns>
/// List of deployments.
/// </returns>
public static Task<DeploymentListResult> ListNextAsync(this IDeploymentOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
/// <summary>
/// Validate a deployment template.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Deployment to validate.
/// </param>
/// <returns>
/// Information from validate template deployment response.
/// </returns>
public static DeploymentValidateResponse Validate(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, BasicDeployment parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IDeploymentOperations)s).ValidateAsync(resourceGroupName, deploymentName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Validate a deployment template.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Resources.IDeploymentOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group. The name is case
/// insensitive.
/// </param>
/// <param name='deploymentName'>
/// Required. The name of the deployment.
/// </param>
/// <param name='parameters'>
/// Required. Deployment to validate.
/// </param>
/// <returns>
/// Information from validate template deployment response.
/// </returns>
public static Task<DeploymentValidateResponse> ValidateAsync(this IDeploymentOperations operations, string resourceGroupName, string deploymentName, BasicDeployment parameters)
{
return operations.ValidateAsync(resourceGroupName, deploymentName, parameters, CancellationToken.None);
}
}
}
| |
#region Using Directives
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
#endregion Using Directives
namespace ScintillaNET
{
/// <summary>
/// Manages commands, which are actions in ScintillaNET that can be bound to key combinations.
/// </summary>
[TypeConverterAttribute(typeof(System.ComponentModel.ExpandableObjectConverter))]
public class Commands : TopLevelHelper
{
#region Fields
private Dictionary<KeyBinding, List<BindableCommand>> _boundCommands = new Dictionary<KeyBinding, List<BindableCommand>>();
private CommandComparer _commandComparer = new CommandComparer();
// Hmmm.. This is getting more and more hackyish
internal bool StopProcessingCommands = false;
private bool _allowDuplicateBindings = true;
#endregion Fields
#region Methods
/// <summary>
/// Adds a key combination to a Command
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
/// <param name="command">Command to execute</param>
public void AddBinding(char shortcut, BindableCommand command)
{
AddBinding(Utilities.GetKeys(shortcut), Keys.None, command);
}
/// <summary>
/// Adds a key combination to a Command
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
/// <param name="command">Command to execute</param>
public void AddBinding(char shortcut, Keys modifiers, BindableCommand command)
{
AddBinding(Utilities.GetKeys(shortcut), modifiers, command);
}
/// <summary>
/// Adds a key combination to a Command
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
/// <param name="command">Command to execute</param>
public void AddBinding(Keys shortcut, BindableCommand command)
{
AddBinding(shortcut, Keys.None, command);
}
/// <summary>
/// Adds a key combination to a Command
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
/// <param name="command">Command to execute</param>
public void AddBinding(Keys shortcut, Keys modifiers, BindableCommand command)
{
KeyBinding kb = new KeyBinding(shortcut, modifiers);
if (!_boundCommands.ContainsKey(kb))
_boundCommands.Add(kb, new List<BindableCommand>());
List<BindableCommand> l = _boundCommands[kb];
if (_allowDuplicateBindings || !l.Contains(command))
l.Add(command);
}
/// <summary>
/// Executes a Command
/// </summary>
/// <param name="command">Any <see cref="BindableCommand"/></param>
/// <returns>Value to indicate whether other bound commands should continue to execute</returns>
public bool Execute(BindableCommand command)
{
if ((int)command < 10000)
{
NativeScintilla.SendMessageDirect((uint)command, IntPtr.Zero, IntPtr.Zero);
return true;
}
switch (command)
{
case BindableCommand.AutoCShow:
Scintilla.AutoComplete.Show();
return true;
case BindableCommand.AcceptActiveSnippets:
return Scintilla.Snippets.AcceptActiveSnippets();
case BindableCommand.CancelActiveSnippets:
return Scintilla.Snippets.CancelActiveSnippets();
case BindableCommand.DoSnippetCheck:
return Scintilla.Snippets.DoSnippetCheck();
case BindableCommand.NextSnippetRange:
return Scintilla.Snippets.NextSnippetRange();
case BindableCommand.PreviousSnippetRange:
return Scintilla.Snippets.PreviousSnippetRange();
case BindableCommand.DropMarkerCollect:
Scintilla.DropMarkers.Collect();
return false;
case BindableCommand.DropMarkerDrop:
Scintilla.DropMarkers.Drop();
return true;
case BindableCommand.Print:
Scintilla.Printing.Print();
return true;
case BindableCommand.PrintPreview:
Scintilla.Printing.PrintPreview();
return true;
case BindableCommand.ShowFind:
Scintilla.FindReplace.ShowFind();
return true;
case BindableCommand.ShowReplace:
Scintilla.FindReplace.ShowReplace();
return true;
case BindableCommand.FindNext:
Scintilla.FindReplace.Window.FindNext();
return true;
case BindableCommand.FindPrevious:
Scintilla.FindReplace.Window.FindPrevious();
return true;
case BindableCommand.IncrementalSearch:
Scintilla.FindReplace.IncrementalSearch();
return true;
case BindableCommand.LineComment:
Scintilla.Lexing.LineComment();
return true;
case BindableCommand.LineUncomment:
Scintilla.Lexing.LineUncomment();
return true;
case BindableCommand.DocumentNavigateForward:
Scintilla.DocumentNavigation.NavigateForward();
return true;
case BindableCommand.DocumentNavigateBackward:
Scintilla.DocumentNavigation.NavigateBackward();
return true;
case BindableCommand.ToggleLineComment:
Scintilla.Lexing.ToggleLineComment();
return true;
case BindableCommand.StreamComment:
Scintilla.Lexing.StreamComment();
return true;
case BindableCommand.ShowSnippetList:
Scintilla.Snippets.ShowSnippetList();
return true;
case BindableCommand.ShowGoTo:
Scintilla.GoTo.ShowGoToDialog();
break;
}
return false;
}
/// <summary>
/// Returns a list of Commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
/// <returns>List of Commands bound to a keyboard shortcut</returns>
private List<BindableCommand> GetCommands(char shortcut)
{
return GetCommands(Utilities.GetKeys(shortcut), Keys.None);
}
/// <summary>
/// Returns a list of Commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
/// <returns>List of Commands bound to a keyboard shortcut</returns>
private List<BindableCommand> GetCommands(char shortcut, Keys modifiers)
{
return GetCommands(Utilities.GetKeys(shortcut), modifiers);
}
/// <summary>
/// Returns a list of Commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
/// <returns>List of Commands bound to a keyboard shortcut</returns>
private List<BindableCommand> GetCommands(Keys shortcut)
{
return GetCommands(shortcut, Keys.None);
}
/// <summary>
/// Returns a list of Commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
/// <returns>List of Commands bound to a keyboard shortcut</returns>
private List<BindableCommand> GetCommands(Keys shortcut, Keys modifiers)
{
KeyBinding kb = new KeyBinding(shortcut, modifiers);
if (!_boundCommands.ContainsKey(kb))
return new List<BindableCommand>();
return _boundCommands[kb];
}
/// <summary>
/// Returns a list of KeyBindings bound to a given command
/// </summary>
/// <param name="command">Command to execute</param>
/// <returns>List of KeyBindings bound to the given command</returns>
public List<KeyBinding> GetKeyBindings(BindableCommand command)
{
List<KeyBinding> ret = new List<KeyBinding>();
foreach (KeyValuePair<KeyBinding, List<BindableCommand>> item in _boundCommands)
{
if (item.Value.Contains(command))
ret.Add(item.Key);
}
return ret;
}
internal bool ProcessKey(KeyEventArgs e)
{
StopProcessingCommands = false;
KeyBinding kb = new KeyBinding(e.KeyCode, e.Modifiers);
if (!_boundCommands.ContainsKey(kb))
return false;
List<BindableCommand> cmds = _boundCommands[kb];
if (cmds.Count == 0)
return false;
cmds.Sort(_commandComparer);
bool ret = false;
foreach (BindableCommand cmd in cmds)
{
ret |= Execute(cmd);
if (StopProcessingCommands)
return ret;
}
return ret;
}
/// <summary>
/// Removes all key command bindings
/// </summary>
/// <remarks>
/// Performing this action will make ScintillaNET virtually unusable until you assign new command bindings.
/// This removes even basic functionality like arrow keys, common clipboard commands, home/_end, etc.
/// </remarks>
public void RemoveAllBindings()
{
_boundCommands.Clear();
}
/// <summary>
/// Removes all commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
public void RemoveBinding(char shortcut)
{
RemoveBinding(Utilities.GetKeys(shortcut), Keys.None);
}
/// <summary>
/// Removes a keyboard shortcut / command combination
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
/// <param name="command">Command to execute</param>
public void RemoveBinding(char shortcut, BindableCommand command)
{
RemoveBinding(Utilities.GetKeys(shortcut), Keys.None, command);
}
/// <summary>
/// Removes all commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
public void RemoveBinding(char shortcut, Keys modifiers)
{
RemoveBinding(Utilities.GetKeys(shortcut), modifiers);
}
/// <summary>
/// Removes a keyboard shortcut / command combination
/// </summary>
/// <param name="shortcut">Character corresponding to a (keyboard) key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
/// <param name="command">Command to execute</param>
public void RemoveBinding(char shortcut, Keys modifiers, BindableCommand command)
{
RemoveBinding(Utilities.GetKeys(shortcut), modifiers, command);
}
/// <summary>
/// Removes all commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
public void RemoveBinding(Keys shortcut)
{
RemoveBinding(shortcut, Keys.None);
}
/// <summary>
/// Removes a keyboard shortcut / command combination
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
/// <param name="command">Command to execute</param>
public void RemoveBinding(Keys shortcut, BindableCommand command)
{
RemoveBinding(shortcut, Keys.None, command);
}
/// <summary>
/// Removes all commands bound to a keyboard shortcut
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
public void RemoveBinding(Keys shortcut, Keys modifiers)
{
_boundCommands.Remove(new KeyBinding(shortcut, modifiers));
}
/// <summary>
/// Removes a keyboard shortcut / command combination
/// </summary>
/// <param name="shortcut">Key to trigger command</param>
/// <param name="modifiers">Shift, alt, ctrl</param>
/// <param name="command">Command to execute</param>
public void RemoveBinding(Keys shortcut, Keys modifiers, BindableCommand command)
{
KeyBinding kb = new KeyBinding(shortcut, modifiers);
if (!_boundCommands.ContainsKey(kb))
return;
_boundCommands[kb].Remove(command);
}
private void ResetAllowDuplicateBindings()
{
_allowDuplicateBindings = true;
}
internal bool ShouldSerialize()
{
return ShouldSerializeAllowDuplicateBindings();
}
private bool ShouldSerializeAllowDuplicateBindings()
{
return !_allowDuplicateBindings;
}
#endregion Methods
#region Properties
/// <summary>
/// Gets/Sets if a key combination can be bound to more than one command. (default is true)
/// </summary>
/// <remarks>
/// When set to false only the first command bound to a key combination is kept.
/// Subsequent requests are ignored.
/// </remarks>
public bool AllowDuplicateBindings
{
get
{
return _allowDuplicateBindings;
}
set
{
_allowDuplicateBindings = value;
}
}
#endregion Properties
#region Constructors
internal Commands(Scintilla scintilla) : base(scintilla)
{
// Ha Ha Ha Ha all your commands are belong to us!
NativeScintilla.ClearAllCmdKeys();
// The reason we're doing this is because ScintillaNET is going to own
// all the command bindings. There are two reasons for this: #1 it makes
// it easier to handle ScintillaNET specific commands, we don't have to
// do special logic if its a native command vs. ScintillaNET extension.
// #2 Scintilla's built in support for commands binding only allows 1
// command per key combination. Our key handling allows for any number
// of commands to be bound to a keyboard combination.
// Other future enhancements that I want to do in the future are:
// Visual Studioesque Key/Chord commands like Ctrl+D, w
// Binding contexts. This is another CodeRush inspired idea where
// commands can only execute if a given context is satisfied (or not).
// Some examples are "At beginning of line", "In comment",
// "Autocomplete window active", "In Snippet Range".
// OK in order for these commands to play nice with each other some of them
// have to have knowledge of each other AND they have to execute in a certain
// order.
// Since all the native Scintilla Commands already know how to work together
// properly they all have the same order. But our commands have to execute first
_commandComparer.CommandOrder.Add(BindableCommand.AutoCShow, 100);
_commandComparer.CommandOrder.Add(BindableCommand.AutoCComplete, 100);
_commandComparer.CommandOrder.Add(BindableCommand.AutoCCancel, 100);
_commandComparer.CommandOrder.Add(BindableCommand.DoSnippetCheck, 200);
_commandComparer.CommandOrder.Add(BindableCommand.AcceptActiveSnippets, 200);
_commandComparer.CommandOrder.Add(BindableCommand.CancelActiveSnippets, 200);
_commandComparer.CommandOrder.Add(BindableCommand.NextSnippetRange, 200);
_commandComparer.CommandOrder.Add(BindableCommand.PreviousSnippetRange, 200);
AddBinding(Keys.Down , Keys.None, BindableCommand.LineDown);
AddBinding(Keys.Down , Keys.Shift, BindableCommand.LineDownExtend);
AddBinding(Keys.Down , Keys.Control, BindableCommand.LineScrollDown);
AddBinding(Keys.Down , Keys.Alt | Keys.Shift, BindableCommand.LineDownRectExtend);
AddBinding(Keys.Up , Keys.None, BindableCommand.LineUp);
AddBinding(Keys.Up , Keys.Shift, BindableCommand.LineUpExtend);
AddBinding(Keys.Up , Keys.Control, BindableCommand.LineScrollUp);
AddBinding(Keys.Up , Keys.Alt | Keys.Shift, BindableCommand.LineUpRectExtend);
AddBinding('[', Keys.Control, BindableCommand.ParaUp);
AddBinding('[' , Keys.Control | Keys.Shift, BindableCommand.ParaUpExtend);
AddBinding(']' , Keys.Control, BindableCommand.ParaDown);
AddBinding(']' , Keys.Control | Keys.Shift, BindableCommand.ParaDownExtend);
AddBinding(Keys.Left , Keys.None, BindableCommand.CharLeft);
AddBinding(Keys.Left , Keys.Shift, BindableCommand.CharLeftExtend);
AddBinding(Keys.Left , Keys.Control, BindableCommand.WordLeft);
AddBinding(Keys.Left , Keys.Control | Keys.Shift, BindableCommand.WordLeftExtend);
AddBinding(Keys.Left , Keys.Alt | Keys.Shift, BindableCommand.CharLeftRectExtend);
AddBinding(Keys.Right , Keys.None, BindableCommand.CharRight);
AddBinding(Keys.Right , Keys.Shift, BindableCommand.CharRightExtend);
AddBinding(Keys.Right , Keys.Control, BindableCommand.WordRight);
AddBinding(Keys.Right , Keys.Control | Keys.Shift, BindableCommand.WordRightExtend);
AddBinding(Keys.Right , Keys.Alt | Keys.Shift, BindableCommand.CharRightRectExtend);
AddBinding('/' , Keys.Control, BindableCommand.WordPartLeft);
AddBinding('/' , Keys.Control | Keys.Shift, BindableCommand.WordPartLeftExtend);
AddBinding('\\' , Keys.Control, BindableCommand.WordPartRight);
AddBinding('\\' , Keys.Control | Keys.Shift, BindableCommand.WordPartRightExtend);
AddBinding(Keys.Home , Keys.None, BindableCommand.VCHome);
AddBinding(Keys.Home , Keys.Shift, BindableCommand.VCHomeExtend);
AddBinding(Keys.Home , Keys.Control, BindableCommand.DocumentStart);
AddBinding(Keys.Home , Keys.Control | Keys.Shift, BindableCommand.DocumentStartExtend);
AddBinding(Keys.Home , Keys.Alt, BindableCommand.HomeDisplay);
AddBinding(Keys.Home , Keys.Alt | Keys.Shift, BindableCommand.VCHomeRectExtend);
AddBinding(Keys.End , Keys.None, BindableCommand.LineEnd);
AddBinding(Keys.End , Keys.Shift, BindableCommand.LineEndExtend);
AddBinding(Keys.End , Keys.Control, BindableCommand.DocumentEnd);
AddBinding(Keys.End , Keys.Control | Keys.Shift, BindableCommand.DocumentEndExtend);
AddBinding(Keys.End , Keys.Alt, BindableCommand.LineEndDisplay);
AddBinding(Keys.End , Keys.Alt | Keys.Shift, BindableCommand.LineEndRectExtend);
AddBinding(Keys.PageUp , Keys.None, BindableCommand.PageUp);
AddBinding(Keys.PageUp , Keys.Shift, BindableCommand.PageUpExtend);
AddBinding(Keys.PageUp , Keys.Alt | Keys.Shift, BindableCommand.PageUpRectExtend);
AddBinding(Keys.PageDown , Keys.None, BindableCommand.PageDown);
AddBinding(Keys.PageDown , Keys.Shift, BindableCommand.PageDownExtend);
AddBinding(Keys.PageDown , Keys.Alt | Keys.Shift, BindableCommand.PageDownRectExtend);
AddBinding(Keys.Delete , Keys.None, BindableCommand.Clear);
AddBinding(Keys.Delete , Keys.Shift, BindableCommand.Cut);
AddBinding(Keys.Delete , Keys.Control, BindableCommand.DelWordRight);
AddBinding(Keys.Delete , Keys.Control | Keys.Shift, BindableCommand.DelLineRight);
AddBinding(Keys.Insert , Keys.None, BindableCommand.EditToggleOvertype);
AddBinding(Keys.Insert , Keys.Shift, BindableCommand.Paste);
AddBinding(Keys.Insert , Keys.Control, BindableCommand.Copy);
AddBinding(Keys.Escape , Keys.None, BindableCommand.Cancel);
AddBinding(Keys.Back , Keys.None, BindableCommand.DeleteBack);
AddBinding(Keys.Back , Keys.Shift, BindableCommand.DeleteBack);
AddBinding(Keys.Back , Keys.Control, BindableCommand.DelWordLeft);
AddBinding(Keys.Back , Keys.Alt, BindableCommand.Undo);
AddBinding(Keys.Back , Keys.Control | Keys.Shift, BindableCommand.DelLineLeft);
AddBinding(Keys.Z, Keys.Control, BindableCommand.Undo);
AddBinding(Keys.Y, Keys.Control, BindableCommand.Redo);
AddBinding(Keys.X, Keys.Control, BindableCommand.Cut);
AddBinding(Keys.C, Keys.Control, BindableCommand.Copy);
AddBinding(Keys.V, Keys.Control, BindableCommand.Paste);
AddBinding(Keys.A, Keys.Control, BindableCommand.SelectAll);
AddBinding(Keys.Tab , Keys.None, BindableCommand.Tab);
AddBinding(Keys.Tab , Keys.Shift, BindableCommand.BackTab);
AddBinding(Keys.Enter , Keys.None, BindableCommand.NewLine);
AddBinding(Keys.Enter , Keys.Shift, BindableCommand.NewLine);
AddBinding(Keys.Add , Keys.Control, BindableCommand.ZoomIn);
AddBinding(Keys.Subtract , Keys.Control, BindableCommand.ZoomOut);
AddBinding(Keys.Divide, Keys.Control, BindableCommand.SetZoom);
AddBinding(Keys.L, Keys.Control, BindableCommand.LineCut);
AddBinding(Keys.L, Keys.Control | Keys.Shift, BindableCommand.LineDelete);
AddBinding(Keys.T , Keys.Control | Keys.Shift, BindableCommand.LineCopy);
AddBinding(Keys.T, Keys.Control, BindableCommand.LineTranspose);
AddBinding(Keys.D, Keys.Control, BindableCommand.SelectionDuplicate);
AddBinding(Keys.U, Keys.Control, BindableCommand.LowerCase);
AddBinding(Keys.U, Keys.Control | Keys.Shift, BindableCommand.UpperCase);
AddBinding(Keys.Space, Keys.Control, BindableCommand.AutoCShow);
AddBinding(Keys.Tab, BindableCommand.DoSnippetCheck);
AddBinding(Keys.Tab, BindableCommand.NextSnippetRange);
AddBinding(Keys.Tab, Keys.Shift, BindableCommand.PreviousSnippetRange);
AddBinding(Keys.Escape, BindableCommand.CancelActiveSnippets);
AddBinding(Keys.Enter, BindableCommand.AcceptActiveSnippets);
AddBinding(Keys.P, Keys.Control, BindableCommand.Print);
AddBinding(Keys.P, Keys.Control | Keys.Shift, BindableCommand.PrintPreview);
AddBinding(Keys.F, Keys.Control, BindableCommand.ShowFind);
AddBinding(Keys.H, Keys.Control, BindableCommand.ShowReplace);
AddBinding(Keys.F3, BindableCommand.FindNext);
AddBinding(Keys.F3, Keys.Shift, BindableCommand.FindPrevious);
AddBinding(Keys.I, Keys.Control, BindableCommand.IncrementalSearch);
AddBinding(Keys.Q, Keys.Control, BindableCommand.LineComment);
AddBinding(Keys.Q, Keys.Control | Keys.Shift, BindableCommand.LineUncomment);
AddBinding('-', Keys.Control, BindableCommand.DocumentNavigateBackward);
AddBinding('-', Keys.Control | Keys.Shift, BindableCommand.DocumentNavigateForward);
AddBinding(Keys.J, Keys.Control, BindableCommand.ShowSnippetList);
AddBinding(Keys.M, Keys.Control, BindableCommand.DropMarkerDrop);
AddBinding(Keys.Escape, BindableCommand.DropMarkerCollect);
AddBinding(Keys.G, Keys.Control, BindableCommand.ShowGoTo);
}
#endregion Constructors
#region Types
private class CommandComparer : IComparer<BindableCommand>
{
#region Fields
private Dictionary<BindableCommand, int> _commandOrder = new Dictionary<BindableCommand, int>();
#endregion Fields
#region Methods
public int Compare(BindableCommand x, BindableCommand y)
{
return GetCommandOrder(y).CompareTo(GetCommandOrder(x));
}
private int GetCommandOrder(BindableCommand cmd)
{
if (!_commandOrder.ContainsKey(cmd))
return 0;
return _commandOrder[cmd];
}
#endregion Methods
#region Properties
public Dictionary<BindableCommand, int> CommandOrder
{
get
{
return _commandOrder;
}
set
{
_commandOrder = value;
}
}
#endregion Properties
}
#endregion Types
}
}
| |
using System;
using System.Collections.Generic;
using Midori.Runtime;
using WarmHeap;
namespace TestGCDeepObject
{
class TestGCDeepObject
{
class RegionLinkedList<T>
{
class Node
{
public Node Next;
public Node Prev;
public T Data;
public Node(T Val)
{
Data = Val;
}
public Node(Region region, T Val)
{
Data = Val;
}
}
Node Head;
public RegionLinkedList()
{
}
public RegionLinkedList(Region region)
{
}
public void InsertFirst(T newVal)
{
if (Head == null)
{
Head = new Node(newVal);
}
else
{
Node node = new Node(newVal);
node.Next = Head;
Head.Prev = node;
Head = node;
}
}
public void InsertFirst(Region region, T newVal)
{
if (Head == null)
{
Head = new Node(region, newVal);
}
else
{
Node node = new Node(region, newVal);
node.Next = Head;
Head.Prev = node;
Head = node;
}
}
}
class TestClass1
{
int m_count;
public TestClass1(int count)
{
m_count = count;
}
public TestClass1(Region region, int count)
{
m_count = count;
}
}
class DeepListList
{
RegionLinkedList<RegionLinkedList<TestClass1>> list;
public DeepListList(int count)
{
list = new RegionLinkedList<RegionLinkedList<TestClass1>>();
for (int i = 0; i < count; ++i)
{
RegionLinkedList<TestClass1> tmpList =
new RegionLinkedList<TestClass1>();
for (int j = 0; j < count; ++j)
{
tmpList.InsertFirst(new TestClass1(10));
}
list.InsertFirst(tmpList);
}
}
public DeepListList(Region region, int count)
{
list = new RegionLinkedList<RegionLinkedList<TestClass1>>(region);
for (int i = 0; i < count; ++i)
{
RegionLinkedList<TestClass1> tmpList =
new RegionLinkedList<TestClass1>(region);
for (int j = 0; j < count; ++j)
{
tmpList.InsertFirst(region, new TestClass1(region, 10));
}
list.InsertFirst(region, tmpList);
}
}
}
class DeepDictionaryList
{
RegionLinkedList<Dictionary<int, TestClass1>> list;
public DeepDictionaryList(int count)
{
list = new RegionLinkedList<Dictionary<int, TestClass1>>();
for (int i = 0; i < count; ++i)
{
Dictionary<int, TestClass1> tmpDict =
new Dictionary<int, TestClass1>();
for (int j = 0; j < count; ++j)
{
tmpDict.Add(j, new TestClass1(10));
}
list.InsertFirst(tmpDict);
}
}
}
class ClassList
{
RegionLinkedList<TestClass1> m_test1;
public ClassList(int count)
{
m_test1 = new RegionLinkedList<TestClass1>();
for (int i = 0; i < count; ++i)
{
m_test1.InsertFirst(new TestClass1(10));
}
}
public ClassList(Region region, int count)
{
m_test1 = new RegionLinkedList<TestClass1>(region);
for (int i = 0; i < count; ++i)
{
m_test1.InsertFirst(region, new TestClass1(region, 10));
}
}
}
class ClassDictionary
{
Dictionary<int, TestClass1> m_test1 = new Dictionary<int, TestClass1>();
public ClassDictionary(int count)
{
for (int i = 0; i < count; ++i)
{
m_test1.Add(i, new TestClass1(10));
}
}
}
public static void Print(Int64 cycles)
{
Int64 frequency = RegionAllocator.NativeGetPerformanceFrequency();
Console.WriteLine("Cycles: {0}\n", cycles);
cycles *= 1000000000;
double duration = (double)cycles / (double)frequency;
Console.WriteLine("Time(ns): {0}\n", duration);
}
public static void Print(double cycles)
{
Int64 frequency = RegionAllocator.NativeGetPerformanceFrequency();
Console.WriteLine("Cycles: {0}\n", cycles);
cycles *= 1000000000.0;
double duration = cycles / (double)frequency;
Console.WriteLine("Time(ns): {0}\n", duration);
}
static void allocateInRegion(int num_iterations, int num_objects,
string classType)
{
if (classType == "dict")
{
Console.WriteLine("Can not allocate dict in region.");
return;
}
else if (classType == "list")
{
Int64 start = RegionAllocator.NativeGetPerformanceCounter();
Region region = RegionAllocator.AllocateRegion(10000000);
DeepListList d_list;
for (int i = 0; i < num_iterations; i++)
{
d_list = new DeepListList(region, num_objects);
}
Int64 end = RegionAllocator.NativeGetPerformanceCounter();
Print(end - start);
}
else
{
Console.WriteLine("Unexpected class type");
}
}
static void allocateInRegionContext(int num_iterations, int num_objects,
string classType)
{
Region region = RegionAllocator.AllocateRegion(10000000);
if (classType == "dict")
{
Int64 start = RegionAllocator.NativeGetPerformanceCounter();
using (RegionContext regContext = RegionContext.Create(region))
{
DeepDictionaryList d_dict;
for (int i = 0; i < num_iterations; i++)
{
d_dict = new DeepDictionaryList(num_objects);
}
}
Int64 end = RegionAllocator.NativeGetPerformanceCounter();
Print(end - start);
}
else if (classType == "list")
{
Int64 start = RegionAllocator.NativeGetPerformanceCounter();
using (RegionContext regContext = RegionContext.Create(region))
{
DeepListList d_list;
for (int i = 0; i < num_iterations; i++)
{
d_list = new DeepListList(num_objects);
}
}
Int64 end = RegionAllocator.NativeGetPerformanceCounter();
Print(end - start);
}
else
{
Console.WriteLine("Unexpected class type");
}
}
static void allocate(int num_iterations, int num_objects, string classType)
{
if (classType == "dict")
{
Int64 start = RegionAllocator.NativeGetPerformanceCounter();
DeepDictionaryList d_dict;
for (int i = 0; i < num_iterations; i++)
{
d_dict = new DeepDictionaryList(num_objects);
}
Int64 end = RegionAllocator.NativeGetPerformanceCounter();
Print(end - start);
}
else if (classType == "list")
{
Int64 start = RegionAllocator.NativeGetPerformanceCounter();
DeepListList d_list;
for (int i = 0; i < num_iterations; i++)
{
d_list = new DeepListList(num_objects);
}
Int64 end = RegionAllocator.NativeGetPerformanceCounter();
Print(end - start);
}
else
{
Console.WriteLine("Unexpected class type");
}
}
static void Main(string[] args)
{
RegionAllocator.Initialize();
HeapWarmer heapWarmer = new HeapWarmer();
if (args.Length != 4 && args.Length != 5)
{
Console.WriteLine("Unexpected number of arguments. Please specify: region|regioncontext|nonregion num_iterations num_objs dict|list");
return;
}
if (args.Length == 5 && args[4] == "warm")
{
heapWarmer.WarmHeap(1000);
}
System.GC.Collect();
int num_iterations = Convert.ToInt32(args[1]);
int num_objects = Convert.ToInt32(args[2]);
if (args[0] == "region")
{
allocateInRegion(num_iterations, num_objects, args[3]);
}
else if (args[0] == "regioncontext")
{
allocateInRegionContext(num_iterations, num_objects, args[3]);
}
else if (args[0] == "nonregion")
{
allocate(num_iterations, num_objects, args[3]);
}
else
{
Console.WriteLine("Unexpected region type");
}
RegionAllocator.PrintStatistics();
}
}
}
| |
using Microsoft.TeamFoundation.DistributedTask.WebApi;
using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines;
using Microsoft.VisualStudio.Services.Agent.Util;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.Services.Agent.Worker
{
[ServiceLocator(Default = typeof(TaskManager))]
public interface ITaskManager : IAgentService
{
Task DownloadAsync(IExecutionContext executionContext, IEnumerable<Pipelines.JobStep> steps);
Definition Load(Pipelines.TaskStep task);
}
public sealed class TaskManager : AgentService, ITaskManager
{
public async Task DownloadAsync(IExecutionContext executionContext, IEnumerable<Pipelines.JobStep> steps)
{
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(steps, nameof(steps));
executionContext.Output(StringUtil.Loc("EnsureTasksExist"));
IEnumerable<Pipelines.TaskStep> tasks = steps.OfType<Pipelines.TaskStep>();
//remove duplicate, disabled and built-in tasks
IEnumerable<Pipelines.TaskStep> uniqueTasks =
from task in tasks
group task by new
{
task.Reference.Id,
task.Reference.Version
}
into taskGrouping
select taskGrouping.First();
if (uniqueTasks.Count() == 0)
{
executionContext.Debug("There is no required tasks need to download.");
return;
}
foreach (var task in uniqueTasks.Select(x => x.Reference))
{
if (task.Id == Pipelines.PipelineConstants.CheckoutTask.Id && task.Version == Pipelines.PipelineConstants.CheckoutTask.Version)
{
Trace.Info("Skip download checkout task.");
continue;
}
await DownloadAsync(executionContext, task);
}
}
public Definition Load(Pipelines.TaskStep task)
{
// Validate args.
Trace.Entering();
ArgUtil.NotNull(task, nameof(task));
if (task.Reference.Id == Pipelines.PipelineConstants.CheckoutTask.Id && task.Reference.Version == Pipelines.PipelineConstants.CheckoutTask.Version)
{
var checkoutTask = new Definition()
{
Directory = HostContext.GetDirectory(WellKnownDirectory.Tasks),
Data = new DefinitionData()
{
Author = Pipelines.PipelineConstants.CheckoutTask.Author,
Description = Pipelines.PipelineConstants.CheckoutTask.Description,
FriendlyName = Pipelines.PipelineConstants.CheckoutTask.FriendlyName,
HelpMarkDown = Pipelines.PipelineConstants.CheckoutTask.HelpMarkDown,
Inputs = Pipelines.PipelineConstants.CheckoutTask.Inputs.ToArray(),
Execution = StringUtil.ConvertFromJson<ExecutionData>(StringUtil.ConvertToJson(Pipelines.PipelineConstants.CheckoutTask.Execution)),
PostJobExecution = StringUtil.ConvertFromJson<ExecutionData>(StringUtil.ConvertToJson(Pipelines.PipelineConstants.CheckoutTask.PostJobExecution))
}
};
return checkoutTask;
}
// Initialize the definition wrapper object.
var definition = new Definition() { Directory = GetDirectory(task.Reference) };
// Deserialize the JSON.
string file = Path.Combine(definition.Directory, Constants.Path.TaskJsonFile);
Trace.Info($"Loading task definition '{file}'.");
string json = File.ReadAllText(file);
definition.Data = JsonConvert.DeserializeObject<DefinitionData>(json);
// Replace the macros within the handler data sections.
foreach (HandlerData handlerData in (definition.Data?.Execution?.All as IEnumerable<HandlerData> ?? new HandlerData[0]))
{
handlerData?.ReplaceMacros(HostContext, definition);
}
return definition;
}
private async Task DownloadAsync(IExecutionContext executionContext, Pipelines.TaskStepDefinitionReference task)
{
Trace.Entering();
ArgUtil.NotNull(executionContext, nameof(executionContext));
ArgUtil.NotNull(task, nameof(task));
ArgUtil.NotNullOrEmpty(task.Version, nameof(task.Version));
var taskServer = HostContext.GetService<ITaskServer>();
// first check to see if we already have the task
string destDirectory = GetDirectory(task);
Trace.Info($"Ensuring task exists: ID '{task.Id}', version '{task.Version}', name '{task.Name}', directory '{destDirectory}'.");
if (File.Exists(destDirectory + ".completed"))
{
executionContext.Debug($"Task '{task.Name}' already downloaded at '{destDirectory}'.");
return;
}
// delete existing task folder.
Trace.Verbose("Deleting task destination folder: {0}", destDirectory);
IOUtil.DeleteDirectory(destDirectory, CancellationToken.None);
// Inform the user that a download is taking place. The download could take a while if
// the task zip is large. It would be nice to print the localized name, but it is not
// available from the reference included in the job message.
executionContext.Output(StringUtil.Loc("DownloadingTask0", task.Name));
string zipFile;
var version = new TaskVersion(task.Version);
//download and extract task in a temp folder and rename it on success
string tempDirectory = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Tasks), "_temp_" + Guid.NewGuid());
try
{
Directory.CreateDirectory(tempDirectory);
zipFile = Path.Combine(tempDirectory, string.Format("{0}.zip", Guid.NewGuid()));
//open zip stream in async mode
using (FileStream fs = new FileStream(zipFile, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true))
{
using (Stream result = await taskServer.GetTaskContentZipAsync(task.Id, version, executionContext.CancellationToken))
{
//81920 is the default used by System.IO.Stream.CopyTo and is under the large object heap threshold (85k).
await result.CopyToAsync(fs, 81920, executionContext.CancellationToken);
await fs.FlushAsync(executionContext.CancellationToken);
}
}
Directory.CreateDirectory(destDirectory);
ZipFile.ExtractToDirectory(zipFile, destDirectory);
Trace.Verbose("Create watermark file indicate task download succeed.");
File.WriteAllText(destDirectory + ".completed", DateTime.UtcNow.ToString());
executionContext.Debug($"Task '{task.Name}' has been downloaded into '{destDirectory}'.");
Trace.Info("Finished getting task.");
}
finally
{
try
{
//if the temp folder wasn't moved -> wipe it
if (Directory.Exists(tempDirectory))
{
Trace.Verbose("Deleting task temp folder: {0}", tempDirectory);
IOUtil.DeleteDirectory(tempDirectory, CancellationToken.None); // Don't cancel this cleanup and should be pretty fast.
}
}
catch (Exception ex)
{
//it is not critical if we fail to delete the temp folder
Trace.Warning("Failed to delete temp folder '{0}'. Exception: {1}", tempDirectory, ex);
executionContext.Warning(StringUtil.Loc("FailedDeletingTempDirectory0Message1", tempDirectory, ex.Message));
}
}
}
private string GetDirectory(Pipelines.TaskStepDefinitionReference task)
{
ArgUtil.NotEmpty(task.Id, nameof(task.Id));
ArgUtil.NotNull(task.Name, nameof(task.Name));
ArgUtil.NotNullOrEmpty(task.Version, nameof(task.Version));
return Path.Combine(
HostContext.GetDirectory(WellKnownDirectory.Tasks),
$"{task.Name}_{task.Id}",
task.Version);
}
}
public sealed class Definition
{
public DefinitionData Data { get; set; }
public string Directory { get; set; }
}
public sealed class DefinitionData
{
public string FriendlyName { get; set; }
public string Description { get; set; }
public string HelpMarkDown { get; set; }
public string Author { get; set; }
public OutputVariable[] OutputVariables { get; set; }
public TaskInputDefinition[] Inputs { get; set; }
public ExecutionData PreJobExecution { get; set; }
public ExecutionData Execution { get; set; }
public ExecutionData PostJobExecution { get; set; }
}
public sealed class OutputVariable
{
public string Name { get; set; }
public string Description { get; set; }
}
public sealed class ExecutionData
{
private readonly List<HandlerData> _all = new List<HandlerData>();
private AzurePowerShellHandlerData _azurePowerShell;
private NodeHandlerData _node;
private PowerShellHandlerData _powerShell;
private PowerShell3HandlerData _powerShell3;
private PowerShellExeHandlerData _powerShellExe;
private ProcessHandlerData _process;
private AgentPluginHandlerData _agentPlugin;
[JsonIgnore]
public List<HandlerData> All => _all;
#if !OS_WINDOWS
[JsonIgnore]
#endif
public AzurePowerShellHandlerData AzurePowerShell
{
get
{
return _azurePowerShell;
}
set
{
_azurePowerShell = value;
Add(value);
}
}
public NodeHandlerData Node
{
get
{
return _node;
}
set
{
_node = value;
Add(value);
}
}
#if !OS_WINDOWS
[JsonIgnore]
#endif
public PowerShellHandlerData PowerShell
{
get
{
return _powerShell;
}
set
{
_powerShell = value;
Add(value);
}
}
#if !OS_WINDOWS
[JsonIgnore]
#endif
public PowerShell3HandlerData PowerShell3
{
get
{
return _powerShell3;
}
set
{
_powerShell3 = value;
Add(value);
}
}
#if !OS_WINDOWS
[JsonIgnore]
#endif
public PowerShellExeHandlerData PowerShellExe
{
get
{
return _powerShellExe;
}
set
{
_powerShellExe = value;
Add(value);
}
}
#if !OS_WINDOWS
[JsonIgnore]
#endif
public ProcessHandlerData Process
{
get
{
return _process;
}
set
{
_process = value;
Add(value);
}
}
public AgentPluginHandlerData AgentPlugin
{
get
{
return _agentPlugin;
}
set
{
_agentPlugin = value;
Add(value);
}
}
private void Add(HandlerData data)
{
if (data != null)
{
_all.Add(data);
}
}
}
public abstract class HandlerData
{
public Dictionary<string, string> Inputs { get; }
public string[] Platforms { get; set; }
[JsonIgnore]
public abstract int Priority { get; }
public string Target
{
get
{
return GetInput(nameof(Target));
}
set
{
SetInput(nameof(Target), value);
}
}
public HandlerData()
{
Inputs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
}
public bool PreferredOnCurrentPlatform()
{
#if OS_WINDOWS
const string CurrentPlatform = "windows";
return Platforms?.Any(x => string.Equals(x, CurrentPlatform, StringComparison.OrdinalIgnoreCase)) ?? false;
#else
return false;
#endif
}
public void ReplaceMacros(IHostContext context, Definition definition)
{
var handlerVariables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
handlerVariables["currentdirectory"] = definition.Directory;
VarUtil.ExpandValues(context, source: handlerVariables, target: Inputs);
}
protected string GetInput(string name)
{
string value;
if (Inputs.TryGetValue(name, out value))
{
return value ?? string.Empty;
}
return string.Empty;
}
protected void SetInput(string name, string value)
{
Inputs[name] = value;
}
}
public sealed class NodeHandlerData : HandlerData
{
public override int Priority => 1;
public string WorkingDirectory
{
get
{
return GetInput(nameof(WorkingDirectory));
}
set
{
SetInput(nameof(WorkingDirectory), value);
}
}
}
public sealed class PowerShell3HandlerData : HandlerData
{
public override int Priority => 2;
}
public sealed class PowerShellHandlerData : HandlerData
{
public string ArgumentFormat
{
get
{
return GetInput(nameof(ArgumentFormat));
}
set
{
SetInput(nameof(ArgumentFormat), value);
}
}
public override int Priority => 3;
public string WorkingDirectory
{
get
{
return GetInput(nameof(WorkingDirectory));
}
set
{
SetInput(nameof(WorkingDirectory), value);
}
}
}
public sealed class AzurePowerShellHandlerData : HandlerData
{
public string ArgumentFormat
{
get
{
return GetInput(nameof(ArgumentFormat));
}
set
{
SetInput(nameof(ArgumentFormat), value);
}
}
public override int Priority => 4;
public string WorkingDirectory
{
get
{
return GetInput(nameof(WorkingDirectory));
}
set
{
SetInput(nameof(WorkingDirectory), value);
}
}
}
public sealed class PowerShellExeHandlerData : HandlerData
{
public string ArgumentFormat
{
get
{
return GetInput(nameof(ArgumentFormat));
}
set
{
SetInput(nameof(ArgumentFormat), value);
}
}
public string FailOnStandardError
{
get
{
return GetInput(nameof(FailOnStandardError));
}
set
{
SetInput(nameof(FailOnStandardError), value);
}
}
public string InlineScript
{
get
{
return GetInput(nameof(InlineScript));
}
set
{
SetInput(nameof(InlineScript), value);
}
}
public override int Priority => 5;
public string ScriptType
{
get
{
return GetInput(nameof(ScriptType));
}
set
{
SetInput(nameof(ScriptType), value);
}
}
public string WorkingDirectory
{
get
{
return GetInput(nameof(WorkingDirectory));
}
set
{
SetInput(nameof(WorkingDirectory), value);
}
}
}
public sealed class ProcessHandlerData : HandlerData
{
public string ArgumentFormat
{
get
{
return GetInput(nameof(ArgumentFormat));
}
set
{
SetInput(nameof(ArgumentFormat), value);
}
}
public string ModifyEnvironment
{
get
{
return GetInput(nameof(ModifyEnvironment));
}
set
{
SetInput(nameof(ModifyEnvironment), value);
}
}
public override int Priority => 6;
public string WorkingDirectory
{
get
{
return GetInput(nameof(WorkingDirectory));
}
set
{
SetInput(nameof(WorkingDirectory), value);
}
}
}
public sealed class AgentPluginHandlerData : HandlerData
{
public override int Priority => 0;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
namespace System
{
public static class Console
{
private const int DefaultConsoleBufferSize = 256; // default size of buffer used in stream readers/writers
private static readonly object InternalSyncObject = new object(); // for synchronizing changing of Console's static fields
private static TextReader _in;
private static TextWriter _out, _error;
private static ConsoleCancelEventHandler _cancelCallbacks;
private static ConsolePal.ControlCHandlerRegistrar _registrar;
private static T EnsureInitialized<T>(ref T field, Func<T> initializer) where T : class
{
lock (InternalSyncObject)
{
T result = Volatile.Read(ref field);
if (result == null)
{
result = initializer();
Volatile.Write(ref field, result);
}
return result;
}
}
public static TextReader In
{
get
{
return Volatile.Read(ref _in) ?? EnsureInitialized(ref _in, () =>
{
Stream inputStream = OpenStandardInput();
return SyncTextReader.GetSynchronizedTextReader(inputStream == Stream.Null ?
StreamReader.Null :
new StreamReader(
stream: inputStream,
encoding: ConsolePal.InputEncoding,
detectEncodingFromByteOrderMarks: false,
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true));
});
}
}
public static TextWriter Out
{
get { return Volatile.Read(ref _out) ?? EnsureInitialized(ref _out, () => CreateOutputWriter(OpenStandardOutput())); }
}
public static TextWriter Error
{
get { return Volatile.Read(ref _error) ?? EnsureInitialized(ref _error, () => CreateOutputWriter(OpenStandardError())); }
}
private static TextWriter CreateOutputWriter(Stream outputStream)
{
return SyncTextWriter.GetSynchronizedTextWriter(outputStream == Stream.Null ?
StreamWriter.Null :
new StreamWriter(
stream: outputStream,
encoding: ConsolePal.OutputEncoding,
bufferSize: DefaultConsoleBufferSize,
leaveOpen: true) { AutoFlush = true });
}
private static StrongBox<bool> _isStdInRedirected;
private static StrongBox<bool> _isStdOutRedirected;
private static StrongBox<bool> _isStdErrRedirected;
public static bool IsInputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdInRedirected) ??
EnsureInitialized(ref _isStdInRedirected, () => new StrongBox<bool>(ConsolePal.IsInputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsOutputRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdOutRedirected) ??
EnsureInitialized(ref _isStdOutRedirected, () => new StrongBox<bool>(ConsolePal.IsOutputRedirectedCore()));
return redirected.Value;
}
}
public static bool IsErrorRedirected
{
get
{
StrongBox<bool> redirected = Volatile.Read(ref _isStdErrRedirected) ??
EnsureInitialized(ref _isStdErrRedirected, () => new StrongBox<bool>(ConsolePal.IsErrorRedirectedCore()));
return redirected.Value;
}
}
public static ConsoleColor BackgroundColor
{
get { return ConsolePal.BackgroundColor; }
set { ConsolePal.BackgroundColor = value; }
}
public static ConsoleColor ForegroundColor
{
get { return ConsolePal.ForegroundColor; }
set { ConsolePal.ForegroundColor = value; }
}
public static void ResetColor()
{
ConsolePal.ResetColor();
}
public static int WindowWidth
{
get
{
return ConsolePal.WindowWidth;
}
set
{
ConsolePal.WindowWidth = value;
}
}
public static bool CursorVisible
{
get
{
return ConsolePal.CursorVisible;
}
set
{
ConsolePal.CursorVisible = value;
}
}
public static event ConsoleCancelEventHandler CancelKeyPress
{
add
{
lock (InternalSyncObject)
{
_cancelCallbacks += value;
// If we haven't registered our control-C handler, do it.
if (_registrar == null)
{
_registrar = new ConsolePal.ControlCHandlerRegistrar();
_registrar.Register();
}
}
}
remove
{
lock (InternalSyncObject)
{
_cancelCallbacks -= value;
if (_registrar != null && _cancelCallbacks == null)
{
_registrar.Unregister();
_registrar = null;
}
}
}
}
public static Stream OpenStandardInput()
{
return ConsolePal.OpenStandardInput();
}
public static Stream OpenStandardOutput()
{
return ConsolePal.OpenStandardOutput();
}
public static Stream OpenStandardError()
{
return ConsolePal.OpenStandardError();
}
public static void SetIn(TextReader newIn)
{
CheckNonNull(newIn, "newIn");
newIn = SyncTextReader.GetSynchronizedTextReader(newIn);
lock (InternalSyncObject) { _in = newIn; }
}
public static void SetOut(TextWriter newOut)
{
CheckNonNull(newOut, "newOut");
newOut = SyncTextWriter.GetSynchronizedTextWriter(newOut);
lock (InternalSyncObject) { _out = newOut; }
}
public static void SetError(TextWriter newError)
{
CheckNonNull(newError, "newError");
newError = SyncTextWriter.GetSynchronizedTextWriter(newError);
lock (InternalSyncObject) { _error = newError; }
}
private static void CheckNonNull(object obj, string paramName)
{
if (obj == null)
throw new ArgumentNullException(paramName);
}
//
// Give a hint to the code generator to not inline the common console methods. The console methods are
// not performance critical. It is unnecessary code bloat to have them inlined.
//
// Moreover, simple repros for codegen bugs are often console-based. It is tedious to manually filter out
// the inlined console writelines from them.
//
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static int Read()
{
return In.Read();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static String ReadLine()
{
return In.ReadLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine()
{
Out.WriteLine();
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer)
{
Out.WriteLine(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(char[] buffer, int index, int count)
{
Out.WriteLine(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(decimal value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, Object arg0, Object arg1, Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void WriteLine(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.WriteLine(format, null, null); // faster than Out.WriteLine(format, (Object)arg);
else
Out.WriteLine(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, Object arg0, Object arg1, Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String format, params Object[] arg)
{
if (arg == null) // avoid ArgumentNullException from String.Format
Out.Write(format, null, null); // faster than Out.Write(format, (Object)arg);
else
Out.Write(format, arg);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(bool value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer)
{
Out.Write(buffer);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(char[] buffer, int index, int count)
{
Out.Write(buffer, index, count);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(double value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(decimal value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(float value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(uint value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(ulong value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(Object value)
{
Out.Write(value);
}
[MethodImplAttribute(MethodImplOptions.NoInlining)]
public static void Write(String value)
{
Out.Write(value);
}
private sealed class ControlCDelegateData
{
private readonly ConsoleSpecialKey _controlKey;
private readonly ConsoleCancelEventHandler _cancelCallbacks;
internal bool Cancel;
internal bool DelegateStarted;
internal ControlCDelegateData(ConsoleSpecialKey controlKey, ConsoleCancelEventHandler cancelCallbacks)
{
_controlKey = controlKey;
_cancelCallbacks = cancelCallbacks;
}
// This is the worker delegate that is called on the Threadpool thread to fire the actual events. It sets the DelegateStarted flag so
// the thread that queued the work to the threadpool knows it has started (since it does not want to block indefinitely on the task
// to start).
internal void HandleBreakEvent()
{
DelegateStarted = true;
var args = new ConsoleCancelEventArgs(_controlKey);
_cancelCallbacks(null, args);
Cancel = args.Cancel;
}
}
internal static bool HandleBreakEvent(ConsoleSpecialKey controlKey)
{
// The thread that this gets called back on has a very small stack on some systems. There is
// not enough space to handle a managed exception being caught and thrown. So, run a task
// on the threadpool for the actual event callback.
// To avoid the race condition between remove handler and raising the event
ConsoleCancelEventHandler cancelCallbacks = Console._cancelCallbacks;
if (cancelCallbacks == null)
{
return false;
}
var delegateData = new ControlCDelegateData(controlKey, cancelCallbacks);
Task callBackTask = Task.Factory.StartNew(
d => ((ControlCDelegateData)d).HandleBreakEvent(),
delegateData,
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
TaskScheduler.Default);
// Block until the delegate is done. We need to be robust in the face of the task not executing
// but we also want to get control back immediately after it is done and we don't want to give the
// handler a fixed time limit in case it needs to display UI. Wait on the task twice, once with a
// timout and a second time without if we are sure that the handler actually started.
TimeSpan controlCWaitTime = new TimeSpan(0, 0, 30); // 30 seconds
callBackTask.Wait(controlCWaitTime);
if (!delegateData.DelegateStarted)
{
Debug.Assert(false, "The task to execute the handler did not start within 30 seconds.");
return false;
}
callBackTask.Wait();
return delegateData.Cancel;
}
}
}
| |
using System;
using UnityEngine;
public class NgMaterial
{
public static bool IsMaterialColor(Material mat)
{
string[] array = new string[]
{
"_Color",
"_TintColor",
"_EmisColor"
};
if (mat != null)
{
string[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
string propertyName = array2[i];
if (mat.HasProperty(propertyName))
{
return true;
}
}
}
return false;
}
public static string GetMaterialColorName(Material mat)
{
string[] array = new string[]
{
"_Color",
"_TintColor",
"_EmisColor"
};
if (mat != null)
{
string[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
string text = array2[i];
if (mat.HasProperty(text))
{
return text;
}
}
}
return null;
}
public static Color GetMaterialColor(Material mat)
{
return NgMaterial.GetMaterialColor(mat, Color.white);
}
public static Color GetMaterialColor(Material mat, Color defaultColor)
{
string[] array = new string[]
{
"_Color",
"_TintColor",
"_EmisColor"
};
if (mat != null)
{
string[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
string propertyName = array2[i];
if (mat.HasProperty(propertyName))
{
return mat.GetColor(propertyName);
}
}
}
return defaultColor;
}
public static void SetMaterialColor(Material mat, Color color)
{
string[] array = new string[]
{
"_Color",
"_TintColor",
"_EmisColor"
};
if (mat != null)
{
string[] array2 = array;
for (int i = 0; i < array2.Length; i++)
{
string propertyName = array2[i];
if (mat.HasProperty(propertyName))
{
mat.SetColor(propertyName, color);
}
}
}
}
public static bool IsSameMaterial(Material mat1, Material mat2, bool bCheckAddress)
{
return (!bCheckAddress || !(mat1 != mat2)) && !(mat2 == null) && !(mat1.shader != mat2.shader) && !(mat1.mainTexture != mat2.mainTexture) && !(mat1.mainTextureOffset != mat2.mainTextureOffset) && !(mat1.mainTextureScale != mat2.mainTextureScale) && NgMaterial.IsSameColorProperty(mat1, mat2, "_Color") && NgMaterial.IsSameColorProperty(mat1, mat2, "_TintColor") && NgMaterial.IsSameColorProperty(mat1, mat2, "_EmisColor") && NgMaterial.IsSameFloatProperty(mat1, mat2, "_InvFade") && NgMaterial.IsMaskTexture(mat1) == NgMaterial.IsMaskTexture(mat2) && (!NgMaterial.IsMaskTexture(mat1) || !(NgMaterial.GetMaskTexture(mat1) != NgMaterial.GetMaskTexture(mat2)));
}
public static void CopyMaterialArgument(Material srcMat, Material tarMat)
{
tarMat.mainTexture = srcMat.mainTexture;
tarMat.mainTextureOffset = srcMat.mainTextureOffset;
tarMat.mainTextureScale = srcMat.mainTextureScale;
if (NgMaterial.IsMaskTexture(srcMat) && NgMaterial.IsMaskTexture(tarMat))
{
NgMaterial.SetMaskTexture(tarMat, NgMaterial.GetMaskTexture(srcMat));
}
NgMaterial.SetMaterialColor(tarMat, NgMaterial.GetMaterialColor(srcMat, new Color(0.5f, 0.5f, 0.5f, 0.5f)));
}
public static bool IsSameColorProperty(Material mat1, Material mat2, string propertyName)
{
bool flag = mat1.HasProperty(propertyName);
bool flag2 = mat2.HasProperty(propertyName);
if (flag && flag2)
{
return mat1.GetColor(propertyName) == mat2.GetColor(propertyName);
}
return !flag && !flag2;
}
public static void CopyColorProperty(Material srcMat, Material tarMat, string propertyName)
{
bool flag = srcMat.HasProperty(propertyName);
bool flag2 = tarMat.HasProperty(propertyName);
if (flag && flag2)
{
tarMat.SetColor(propertyName, srcMat.GetColor(propertyName));
}
}
public static bool IsSameFloatProperty(Material mat1, Material mat2, string propertyName)
{
bool flag = mat1.HasProperty(propertyName);
bool flag2 = mat2.HasProperty(propertyName);
if (flag && flag2)
{
return mat1.GetFloat(propertyName) == mat2.GetFloat(propertyName);
}
return !flag && !flag2;
}
public static Texture GetTexture(Material mat, bool bMask)
{
if (mat == null)
{
return null;
}
if (!bMask)
{
return mat.mainTexture;
}
if (NgMaterial.IsMaskTexture(mat))
{
return mat.GetTexture("_Mask");
}
return null;
}
public static void SetMaskTexture(Material mat, bool bMask, Texture newTexture)
{
if (mat == null)
{
return;
}
if (bMask)
{
NgMaterial.SetMaskTexture(mat, newTexture);
}
else
{
mat.mainTexture = newTexture;
}
}
public static bool IsMaskTexture(Material tarMat)
{
return tarMat.HasProperty("_Mask");
}
public static void SetMaskTexture(Material tarMat, Texture maskTex)
{
tarMat.SetTexture("_Mask", maskTex);
}
public static Texture GetMaskTexture(Material mat)
{
if (mat == null || !mat.HasProperty("_Mask"))
{
return null;
}
return mat.GetTexture("_Mask");
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Numerics;
using System.Linq;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type decimal with 3 columns and 3 rows.
/// </summary>
[Serializable]
[DataContract(Namespace = "mat")]
[StructLayout(LayoutKind.Sequential)]
public struct decmat3 : IReadOnlyList<decimal>, IEquatable<decmat3>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
[DataMember]
public decimal m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
[DataMember]
public decimal m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
[DataMember]
public decimal m02;
/// <summary>
/// Column 1, Rows 0
/// </summary>
[DataMember]
public decimal m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
[DataMember]
public decimal m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
[DataMember]
public decimal m12;
/// <summary>
/// Column 2, Rows 0
/// </summary>
[DataMember]
public decimal m20;
/// <summary>
/// Column 2, Rows 1
/// </summary>
[DataMember]
public decimal m21;
/// <summary>
/// Column 2, Rows 2
/// </summary>
[DataMember]
public decimal m22;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public decmat3(decimal m00, decimal m01, decimal m02, decimal m10, decimal m11, decimal m12, decimal m20, decimal m21, decimal m22)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
this.m20 = m20;
this.m21 = m21;
this.m22 = m22;
}
/// <summary>
/// Constructs this matrix from a decmat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0m;
this.m20 = 0m;
this.m21 = 0m;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a decmat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0m;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a decmat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0m;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0m;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a decmat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = 0m;
this.m21 = 0m;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a decmat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a decmat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a decmat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = 0m;
this.m21 = 0m;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a decmat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a decmat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decmat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
this.m20 = m.m20;
this.m21 = m.m21;
this.m22 = m.m22;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decvec2 c0, decvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0m;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0m;
this.m20 = 0m;
this.m21 = 0m;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decvec2 c0, decvec2 c1, decvec2 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0m;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0m;
this.m20 = c2.x;
this.m21 = c2.y;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decvec3 c0, decvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m20 = 0m;
this.m21 = 0m;
this.m22 = 1m;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public decmat3(decvec3 c0, decvec3 c1, decvec3 c2)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
this.m20 = c2.x;
this.m21 = c2.y;
this.m22 = c2.z;
}
/// <summary>
/// Creates a rotation matrix from a decquat.
/// </summary>
public decmat3(decquat q)
: this(q.ToMat3)
{
}
#endregion
#region Explicit Operators
/// <summary>
/// Creates a rotation matrix from a decquat.
/// </summary>
public static explicit operator decmat3(decquat q) => q.ToMat3;
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public decimal[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 }, { m20, m21, m22 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public decimal[] Values1D => new[] { m00, m01, m02, m10, m11, m12, m20, m21, m22 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public decvec3 Column0
{
get
{
return new decvec3(m00, m01, m02);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public decvec3 Column1
{
get
{
return new decvec3(m10, m11, m12);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
}
}
/// <summary>
/// Gets or sets the column nr 2
/// </summary>
public decvec3 Column2
{
get
{
return new decvec3(m20, m21, m22);
}
set
{
m20 = value.x;
m21 = value.y;
m22 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public decvec3 Row0
{
get
{
return new decvec3(m00, m10, m20);
}
set
{
m00 = value.x;
m10 = value.y;
m20 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public decvec3 Row1
{
get
{
return new decvec3(m01, m11, m21);
}
set
{
m01 = value.x;
m11 = value.y;
m21 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public decvec3 Row2
{
get
{
return new decvec3(m02, m12, m22);
}
set
{
m02 = value.x;
m12 = value.y;
m22 = value.z;
}
}
/// <summary>
/// Creates a quaternion from the rotational part of this matrix.
/// </summary>
public decquat ToQuaternion => decquat.FromMat3(this);
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static decmat3 Zero { get; } = new decmat3(0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m, 0m);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static decmat3 Ones { get; } = new decmat3(1m, 1m, 1m, 1m, 1m, 1m, 1m, 1m, 1m);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static decmat3 Identity { get; } = new decmat3(1m, 0m, 0m, 0m, 1m, 0m, 0m, 0m, 1m);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static decmat3 AllMaxValue { get; } = new decmat3(decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue, decimal.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static decmat3 DiagonalMaxValue { get; } = new decmat3(decimal.MaxValue, 0m, 0m, 0m, decimal.MaxValue, 0m, 0m, 0m, decimal.MaxValue);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static decmat3 AllMinValue { get; } = new decmat3(decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue, decimal.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static decmat3 DiagonalMinValue { get; } = new decmat3(decimal.MinValue, 0m, 0m, 0m, decimal.MinValue, 0m, 0m, 0m, decimal.MinValue);
/// <summary>
/// Predefined all-MinusOne matrix
/// </summary>
public static decmat3 AllMinusOne { get; } = new decmat3(decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne, decimal.MinusOne);
/// <summary>
/// Predefined diagonal-MinusOne matrix
/// </summary>
public static decmat3 DiagonalMinusOne { get; } = new decmat3(decimal.MinusOne, 0m, 0m, 0m, decimal.MinusOne, 0m, 0m, 0m, decimal.MinusOne);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<decimal> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m10;
yield return m11;
yield return m12;
yield return m20;
yield return m21;
yield return m22;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (3 x 3 = 9).
/// </summary>
public int Count => 9;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public decimal this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m10;
case 4: return m11;
case 5: return m12;
case 6: return m20;
case 7: return m21;
case 8: return m22;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m10 = value; break;
case 4: this.m11 = value; break;
case 5: this.m12 = value; break;
case 6: this.m20 = value; break;
case 7: this.m21 = value; break;
case 8: this.m22 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public decimal this[int col, int row]
{
get
{
return this[col * 3 + row];
}
set
{
this[col * 3 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(decmat3 rhs) => ((((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && (m10.Equals(rhs.m10) && m11.Equals(rhs.m11))) && ((m12.Equals(rhs.m12) && m20.Equals(rhs.m20)) && (m21.Equals(rhs.m21) && m22.Equals(rhs.m22))));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is decmat3 && Equals((decmat3) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(decmat3 lhs, decmat3 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(decmat3 lhs, decmat3 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode()) * 397) ^ m20.GetHashCode()) * 397) ^ m21.GetHashCode()) * 397) ^ m22.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public decmat3 Transposed => new decmat3(m00, m10, m20, m01, m11, m21, m02, m12, m22);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public decimal MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m10), m11), m12), m20), m21), m22);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public decimal MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m10), m11), m12), m20), m21), m22);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public decimal Length => (decimal)(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))).Sqrt();
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public decimal LengthSqr => ((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public decimal Sum => ((((m00 + m01) + m02) + (m10 + m11)) + ((m12 + m20) + (m21 + m22)));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public decimal Norm => (decimal)(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))).Sqrt();
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public decimal Norm1 => ((((Math.Abs(m00) + Math.Abs(m01)) + Math.Abs(m02)) + (Math.Abs(m10) + Math.Abs(m11))) + ((Math.Abs(m12) + Math.Abs(m20)) + (Math.Abs(m21) + Math.Abs(m22))));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public decimal Norm2 => (decimal)(((((m00*m00 + m01*m01) + m02*m02) + (m10*m10 + m11*m11)) + ((m12*m12 + m20*m20) + (m21*m21 + m22*m22)))).Sqrt();
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public decimal NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(Math.Abs(m00), Math.Abs(m01)), Math.Abs(m02)), Math.Abs(m10)), Math.Abs(m11)), Math.Abs(m12)), Math.Abs(m20)), Math.Abs(m21)), Math.Abs(m22));
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow(((((Math.Pow((double)Math.Abs(m00), p) + Math.Pow((double)Math.Abs(m01), p)) + Math.Pow((double)Math.Abs(m02), p)) + (Math.Pow((double)Math.Abs(m10), p) + Math.Pow((double)Math.Abs(m11), p))) + ((Math.Pow((double)Math.Abs(m12), p) + Math.Pow((double)Math.Abs(m20), p)) + (Math.Pow((double)Math.Abs(m21), p) + Math.Pow((double)Math.Abs(m22), p)))), 1 / p);
/// <summary>
/// Returns determinant of this matrix.
/// </summary>
public decimal Determinant => m00 * (m11 * m22 - m21 * m12) - m10 * (m01 * m22 - m21 * m02) + m20 * (m01 * m12 - m11 * m02);
/// <summary>
/// Returns the adjunct of this matrix.
/// </summary>
public decmat3 Adjugate => new decmat3(m11 * m22 - m21 * m12, -m01 * m22 + m21 * m02, m01 * m12 - m11 * m02, -m10 * m22 + m20 * m12, m00 * m22 - m20 * m02, -m00 * m12 + m10 * m02, m10 * m21 - m20 * m11, -m00 * m21 + m20 * m01, m00 * m11 - m10 * m01);
/// <summary>
/// Returns the inverse of this matrix (use with caution).
/// </summary>
public decmat3 Inverse => Adjugate / Determinant;
/// <summary>
/// Executes a matrix-matrix-multiplication decmat3 * decmat2x3 -> decmat2x3.
/// </summary>
public static decmat2x3 operator*(decmat3 lhs, decmat2x3 rhs) => new decmat2x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12));
/// <summary>
/// Executes a matrix-matrix-multiplication decmat3 * decmat3 -> decmat3.
/// </summary>
public static decmat3 operator*(decmat3 lhs, decmat3 rhs) => new decmat3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22));
/// <summary>
/// Executes a matrix-matrix-multiplication decmat3 * decmat4x3 -> decmat4x3.
/// </summary>
public static decmat4x3 operator*(decmat3 lhs, decmat4x3 rhs) => new decmat4x3(((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01) + lhs.m20 * rhs.m02), ((lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01) + lhs.m21 * rhs.m02), ((lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01) + lhs.m22 * rhs.m02), ((lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11) + lhs.m20 * rhs.m12), ((lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11) + lhs.m21 * rhs.m12), ((lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11) + lhs.m22 * rhs.m12), ((lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21) + lhs.m20 * rhs.m22), ((lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21) + lhs.m21 * rhs.m22), ((lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21) + lhs.m22 * rhs.m22), ((lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31) + lhs.m20 * rhs.m32), ((lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31) + lhs.m21 * rhs.m32), ((lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31) + lhs.m22 * rhs.m32));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static decvec3 operator*(decmat3 m, decvec3 v) => new decvec3(((m.m00 * v.x + m.m10 * v.y) + m.m20 * v.z), ((m.m01 * v.x + m.m11 * v.y) + m.m21 * v.z), ((m.m02 * v.x + m.m12 * v.y) + m.m22 * v.z));
/// <summary>
/// Executes a matrix-matrix-divison A / B == A * B^-1 (use with caution).
/// </summary>
public static decmat3 operator/(decmat3 A, decmat3 B) => A * B.Inverse;
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static decmat3 CompMul(decmat3 A, decmat3 B) => new decmat3(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12, A.m20 * B.m20, A.m21 * B.m21, A.m22 * B.m22);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static decmat3 CompDiv(decmat3 A, decmat3 B) => new decmat3(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12, A.m20 / B.m20, A.m21 / B.m21, A.m22 / B.m22);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static decmat3 CompAdd(decmat3 A, decmat3 B) => new decmat3(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12, A.m20 + B.m20, A.m21 + B.m21, A.m22 + B.m22);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static decmat3 CompSub(decmat3 A, decmat3 B) => new decmat3(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12, A.m20 - B.m20, A.m21 - B.m21, A.m22 - B.m22);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static decmat3 operator+(decmat3 lhs, decmat3 rhs) => new decmat3(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12, lhs.m20 + rhs.m20, lhs.m21 + rhs.m21, lhs.m22 + rhs.m22);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static decmat3 operator+(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs, lhs.m20 + rhs, lhs.m21 + rhs, lhs.m22 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static decmat3 operator+(decimal lhs, decmat3 rhs) => new decmat3(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12, lhs + rhs.m20, lhs + rhs.m21, lhs + rhs.m22);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static decmat3 operator-(decmat3 lhs, decmat3 rhs) => new decmat3(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12, lhs.m20 - rhs.m20, lhs.m21 - rhs.m21, lhs.m22 - rhs.m22);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static decmat3 operator-(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs, lhs.m20 - rhs, lhs.m21 - rhs, lhs.m22 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static decmat3 operator-(decimal lhs, decmat3 rhs) => new decmat3(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12, lhs - rhs.m20, lhs - rhs.m21, lhs - rhs.m22);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static decmat3 operator/(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs, lhs.m20 / rhs, lhs.m21 / rhs, lhs.m22 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static decmat3 operator/(decimal lhs, decmat3 rhs) => new decmat3(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12, lhs / rhs.m20, lhs / rhs.m21, lhs / rhs.m22);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static decmat3 operator*(decmat3 lhs, decimal rhs) => new decmat3(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs, lhs.m20 * rhs, lhs.m21 * rhs, lhs.m22 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static decmat3 operator*(decimal lhs, decmat3 rhs) => new decmat3(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12, lhs * rhs.m20, lhs * rhs.m21, lhs * rhs.m22);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat3 operator<(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12, lhs.m20 < rhs.m20, lhs.m21 < rhs.m21, lhs.m22 < rhs.m22);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3 operator<(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs, lhs.m20 < rhs, lhs.m21 < rhs, lhs.m22 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat3 operator<(decimal lhs, decmat3 rhs) => new bmat3(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12, lhs < rhs.m20, lhs < rhs.m21, lhs < rhs.m22);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat3 operator<=(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12, lhs.m20 <= rhs.m20, lhs.m21 <= rhs.m21, lhs.m22 <= rhs.m22);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator<=(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs, lhs.m20 <= rhs, lhs.m21 <= rhs, lhs.m22 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator<=(decimal lhs, decmat3 rhs) => new bmat3(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12, lhs <= rhs.m20, lhs <= rhs.m21, lhs <= rhs.m22);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat3 operator>(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12, lhs.m20 > rhs.m20, lhs.m21 > rhs.m21, lhs.m22 > rhs.m22);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3 operator>(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs, lhs.m20 > rhs, lhs.m21 > rhs, lhs.m22 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat3 operator>(decimal lhs, decmat3 rhs) => new bmat3(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12, lhs > rhs.m20, lhs > rhs.m21, lhs > rhs.m22);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat3 operator>=(decmat3 lhs, decmat3 rhs) => new bmat3(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12, lhs.m20 >= rhs.m20, lhs.m21 >= rhs.m21, lhs.m22 >= rhs.m22);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator>=(decmat3 lhs, decimal rhs) => new bmat3(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs, lhs.m20 >= rhs, lhs.m21 >= rhs, lhs.m22 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat3 operator>=(decimal lhs, decmat3 rhs) => new bmat3(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12, lhs >= rhs.m20, lhs >= rhs.m21, lhs >= rhs.m22);
}
}
| |
using System;
using System.Collections.Generic;
using Sandbox.Common.ObjectBuilders;
using Sandbox.ModAPI;
using VRage.Game.Components;
using VRage.Game.ModAPI;
using VRage.ModAPI;
using VRage.ObjectBuilders;
using VRageMath;
namespace Digi.Exploration
{
[MySessionComponentDescriptor(MyUpdateOrder.BeforeSimulation)]
public class EEM_CleanUp : MySessionComponentBase
{
public override void LoadData()
{
Log.SetUp("EEM", 531659576); // mod name and workshop ID
}
private bool init = false;
private int skip = SKIP_UPDATES;
private const int SKIP_UPDATES = 100;
public static int rangeSq = -1;
public static readonly List<IMyPlayer> players = new List<IMyPlayer>();
public static readonly HashSet<IMyCubeGrid> grids = new HashSet<IMyCubeGrid>();
public static readonly List<IMySlimBlock> blocks = new List<IMySlimBlock>(); // never filled
public void Init()
{
init = true;
Log.Init();
MyAPIGateway.Session.SessionSettings.MaxDrones = Constants.FORCE_MAX_DRONES;
}
protected override void UnloadData()
{
init = false;
Log.Close();
players.Clear();
grids.Clear();
blocks.Clear();
}
public override void UpdateBeforeSimulation()
{
if(!MyAPIGateway.Multiplayer.IsServer) // only server-side/SP
return;
if(!init)
{
if(MyAPIGateway.Session == null)
return;
Init();
}
if(++skip >= SKIP_UPDATES)
{
try
{
skip = 0;
// the range used to check player distance from ships before removing them
rangeSq = Math.Max(MyAPIGateway.Session.SessionSettings.ViewDistance, Constants.CLEANUP_MIN_RANGE);
rangeSq *= rangeSq;
players.Clear();
MyAPIGateway.Players.GetPlayers(players);
if(Constants.CLEANUP_DEBUG)
Log.Info("player list updated; view range updated: " + Math.Round(Math.Sqrt(rangeSq), 1));
}
catch(Exception e)
{
Log.Error(e);
}
}
}
public static void GetAttachedGrids(IMyCubeGrid grid)
{
grids.Clear();
RecursiveGetAttachedGrids(grid);
}
private static void RecursiveGetAttachedGrids(IMyCubeGrid grid)
{
grid.GetBlocks(blocks, GetAttachedGridsLoopBlocks);
}
private static bool GetAttachedGridsLoopBlocks(IMySlimBlock slim) // should always return false!
{
var block = slim.FatBlock;
if(block == null)
return false;
if(Constants.CLEANUP_CONNECTOR_CONNECTED)
{
var connector = block as IMyShipConnector;
if(connector != null)
{
var otherGrid = connector.OtherConnector?.CubeGrid;
if(otherGrid != null && !grids.Contains(otherGrid))
{
grids.Add(otherGrid);
RecursiveGetAttachedGrids(otherGrid);
}
return false;
}
}
var rotorBase = block as IMyMotorStator;
if(rotorBase != null)
{
var otherGrid = rotorBase.TopGrid;
if(otherGrid != null && !grids.Contains(otherGrid))
{
grids.Add(otherGrid);
RecursiveGetAttachedGrids(otherGrid);
}
return false;
}
var rotorTop = block as IMyMotorRotor;
if(rotorTop != null)
{
var otherGrid = rotorTop.Base?.CubeGrid;
if(otherGrid != null && !grids.Contains(otherGrid))
{
grids.Add(otherGrid);
RecursiveGetAttachedGrids(otherGrid);
}
return false;
}
var pistonBase = block as IMyPistonBase;
if(pistonBase != null)
{
var otherGrid = pistonBase.TopGrid;
if(otherGrid != null && !grids.Contains(otherGrid))
{
grids.Add(otherGrid);
RecursiveGetAttachedGrids(otherGrid);
}
return false;
}
var pistonTop = block as IMyPistonTop;
if(pistonTop != null)
{
var otherGrid = pistonTop.Piston?.CubeGrid;
if(otherGrid != null && !grids.Contains(otherGrid))
{
grids.Add(otherGrid);
RecursiveGetAttachedGrids(otherGrid);
}
return false;
}
return false;
}
}
[MyEntityComponentDescriptor(typeof(MyObjectBuilder_RemoteControl), true)]
public class EEM_RC : MyGameLogicComponent
{
public override void Init(MyObjectBuilder_EntityBase objectBuilder)
{
Entity.NeedsUpdate |= MyEntityUpdateEnum.EACH_100TH_FRAME;
}
public override void UpdateAfterSimulation100()
{
try
{
if(!MyAPIGateway.Multiplayer.IsServer) // only server-side/SP
return;
var rc = (IMyRemoteControl)Entity;
var grid = rc.CubeGrid;
if(grid.Physics == null || !rc.IsWorking || !Constants.NPC_FACTIONS.Contains(rc.GetOwnerFactionTag()))
{
if(Constants.CLEANUP_DEBUG)
Log.Info(grid.DisplayName + " (" + grid.EntityId + " @ " + grid.WorldMatrix.Translation + ") is not valid; " + (grid.Physics == null ? "Phys=null" : "Phys OK") + "; " + (rc.IsWorking ? "RC OK" : "RC Not working!") + "; " + (!Constants.NPC_FACTIONS.Contains(rc.GetOwnerFactionTag()) ? "Owner faction tag is not in NPC list (" + rc.GetOwnerFactionTag() + ")" : "Owner Faction OK"));
return;
}
if(!rc.CustomData.Contains(Constants.CLEANUP_RC_TAG))
{
if(Constants.CLEANUP_DEBUG)
Log.Info(grid.DisplayName + " (" + grid.EntityId + " @ " + grid.WorldMatrix.Translation + ") RC does not contain the " + Constants.CLEANUP_RC_TAG + "tag!");
return;
}
if(Constants.CLEANUP_RC_EXTRA_TAGS.Length > 0)
{
bool hasExtraTag = false;
foreach(var tag in Constants.CLEANUP_RC_EXTRA_TAGS)
{
if(rc.CustomData.Contains(tag))
{
hasExtraTag = true;
break;
}
}
if(!hasExtraTag)
{
if(Constants.CLEANUP_DEBUG)
Log.Info(grid.DisplayName + " (" + grid.EntityId + " @ " + grid.WorldMatrix.Translation + ") RC does not contain one of the extra tags!");
return;
}
}
if(Constants.CLEANUP_DEBUG)
Log.Info("Checking RC '" + rc.CustomName + "' from grid '" + grid.DisplayName + "' (" + grid.EntityId + ") for any nearby players...");
var rangeSq = EEM_CleanUp.rangeSq;
var gridCenter = grid.WorldAABB.Center;
if(rangeSq <= 0)
{
if(Constants.CLEANUP_DEBUG)
Log.Info("- WARNING: Range not assigned yet, ignoring grid for now.");
return;
}
// check if any player is within range of the ship
foreach(var player in EEM_CleanUp.players)
{
if(Vector3D.DistanceSquared(player.GetPosition(), gridCenter) <= rangeSq)
{
if(Constants.CLEANUP_DEBUG)
Log.Info(" - player '" + player.DisplayName + "' is within " + Math.Round(Math.Sqrt(rangeSq), 1) + "m of it, not removing.");
return;
}
}
if(Constants.CLEANUP_DEBUG)
Log.Info(" - no player is within " + Math.Round(Math.Sqrt(rangeSq), 1) + "m of it, removing...");
Log.Info("NPC ship '" + grid.DisplayName + "' (" + grid.EntityId + ") removed.");
EEM_CleanUp.GetAttachedGrids(grid); // this gets all connected grids and places them in Exploration.grids (it clears it first)
foreach(var g in EEM_CleanUp.grids)
{
g.Close(); // this only works server-side
Log.Info(" - subgrid '" + g.DisplayName + "' (" + g.EntityId + ") removed.");
}
grid.Close(); // this only works server-side
}
catch(Exception e)
{
Log.Error(e);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Xunit;
namespace System.Linq.Parallel.Tests
{
[OuterLoop]
public static partial class ParallelQueryCombinationTests
{
private const int DefaultStart = 8;
private const int DefaultSize = 16;
private const int CountFactor = 8;
private const int GroupFactor = 8;
private static readonly Operation DefaultSource = (start, count, ignore) => ParallelEnumerable.Range(start, count);
private static readonly Labeled<Operation> LabeledDefaultSource = Label("Default", DefaultSource);
private static readonly Labeled<Operation> Failing = Label("ThrowOnFirstEnumeration", (start, count, source) => Enumerables<int>.ThrowOnEnumeration().AsParallel());
private static IEnumerable<Labeled<Operation>> UnorderedRangeSources()
{
// The difference between this and the existing sources is more control is needed over the range creation.
// Specifically, start/count won't be known until the nesting level is resolved at runtime.
yield return Label("ParallelEnumerable.Range", (start, count, ignore) => ParallelEnumerable.Range(start, count));
yield return Label("Enumerable.Range", (start, count, ignore) => Enumerable.Range(start, count).AsParallel());
yield return Label("Array", (start, count, ignore) => Enumerable.Range(start, count).ToArray().AsParallel());
yield return Label("Partitioner", (start, count, ignore) => Partitioner.Create(Enumerable.Range(start, count).ToArray()).AsParallel());
yield return Label("List", (start, count, ignore) => Enumerable.Range(start, count).ToList().AsParallel());
yield return Label("ReadOnlyCollection", (start, count, ignore) => new ReadOnlyCollection<int>(Enumerable.Range(start, count).ToList()).AsParallel());
}
private static IEnumerable<Labeled<Operation>> RangeSources()
{
foreach (Labeled<Operation> source in UnorderedRangeSources())
{
yield return source.AsOrdered();
foreach (Labeled<Operation> ordering in OrderOperators())
{
yield return source.Append(ordering);
}
}
}
private static IEnumerable<Labeled<Operation>> OrderOperators()
{
yield return Label("OrderBy", (start, count, source) => source(start, count).OrderBy(x => x));
yield return Label("OrderByDescending", (start, count, source) => source(start, count).OrderByDescending(x => -x));
yield return Label("ThenBy", (start, count, source) => source(start, count).OrderBy(x => 0).ThenBy(x => x));
yield return Label("ThenByDescending", (start, count, source) => source(start, count).OrderBy(x => 0).ThenByDescending(x => -x));
}
private static IEnumerable<Labeled<Operation>> ReverseOrderOperators()
{
yield return Label("OrderBy-Reversed", (start, count, source) => source(start, count).OrderBy(x => x, ReverseComparer.Instance));
yield return Label("OrderByDescending-Reversed", (start, count, source) => source(start, count).OrderByDescending(x => -x, ReverseComparer.Instance));
yield return Label("ThenBy-Reversed", (start, count, source) => source(start, count).OrderBy(x => 0).ThenBy(x => x, ReverseComparer.Instance));
yield return Label("ThenByDescending-Reversed", (start, count, source) => source(start, count).OrderBy(x => 0).ThenByDescending(x => -x, ReverseComparer.Instance));
}
public static IEnumerable<object[]> OrderFailingOperators()
{
foreach (Labeled<Operation> operation in new[] {
Label("OrderBy", (start, count, s) => s(start, count).OrderBy<int, int>(x => {throw new DeliberateTestException(); })),
Label("OrderBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => x, new FailingComparer())),
Label("OrderByDescending", (start, count, s) => s(start, count).OrderByDescending<int, int>(x => {throw new DeliberateTestException(); })),
Label("OrderByDescending-Comparer", (start, count, s) => s(start, count).OrderByDescending(x => x, new FailingComparer())),
Label("ThenBy", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy<int, int>(x => {throw new DeliberateTestException(); })),
Label("ThenBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy(x => x, new FailingComparer())),
Label("ThenByDescending", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending<int, int>(x => {throw new DeliberateTestException(); })),
Label("ThenByDescending-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending(x => x, new FailingComparer())),
})
{
yield return new object[] { LabeledDefaultSource, operation };
}
foreach (Labeled<Operation> operation in OrderOperators())
{
yield return new object[] { Failing, operation };
}
}
public static IEnumerable<object[]> OrderCancelingOperators()
{
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("OrderBy-Comparer", (source, cancel) => source.OrderBy(x => x, new CancelingComparer(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("OrderByDescending-Comparer", (source, cancel) => source.OrderByDescending(x => x, new CancelingComparer(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("ThenBy-Comparer", (source, cancel) => source.OrderBy(x => 0).ThenBy(x => x, new CancelingComparer(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("ThenByDescending-Comparer", (source, cancel) => source.OrderBy(x => 0).ThenByDescending(x => x, new CancelingComparer(cancel))) };
}
public static IEnumerable<object[]> UnaryOperations()
{
yield return new object[] { Label("Cast", (start, count, source) => source(start, count).Cast<int>()) };
yield return new object[] { Label("DefaultIfEmpty", (start, count, source) => source(start, count).DefaultIfEmpty()) };
yield return new object[] { Label("Distinct", (start, count, source) => source(start * 2, count * 2).Select(x => x / 2).Distinct(new ModularCongruenceComparer(count))) };
yield return new object[] { Label("OfType", (start, count, source) => source(start, count).OfType<int>()) };
yield return new object[] { Label("Reverse", (start, count, source) => source(start, count).Reverse()) };
yield return new object[] { Label("GroupBy", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, new ModularCongruenceComparer(count)).Select(g => g.Key + start)) };
yield return new object[] { Label("GroupBy-ElementSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, new ModularCongruenceComparer(count)).Select(g => g.Min() - 1)) };
yield return new object[] { Label("GroupBy-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, (key, g) => key + start, new ModularCongruenceComparer(count))) };
yield return new object[] { Label("GroupBy-ElementSelector-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, (key, g) => g.Min() - 1, new ModularCongruenceComparer(count))) };
yield return new object[] { Label("Select", (start, count, source) => source(start - count, count).Select(x => x + count)) };
yield return new object[] { Label("Select-Index", (start, count, source) => source(start - count, count).Select((x, index) => x + count)) };
yield return new object[] { Label("SelectMany", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor)))) };
yield return new object[] { Label("SelectMany-Index", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor)))) };
yield return new object[] { Label("SelectMany-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element)) };
yield return new object[] { Label("SelectMany-Index-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element)) };
yield return new object[] { Label("Where", (start, count, source) => source(start - count / 2, count * 2).Where(x => x >= start && x < start + count)) };
yield return new object[] { Label("Where-Index", (start, count, source) => source(start - count / 2, count * 2).Where((x, index) => x >= start && x < start + count)) };
}
public static IEnumerable<object[]> UnaryUnorderedOperators()
{
foreach (Labeled<Operation> source in UnorderedRangeSources())
{
foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0]))
{
yield return new object[] { source, operation };
}
}
}
private static IEnumerable<Labeled<Operation>> SkipTakeOperations()
{
// Take/Skip-based operations require ordered input, or will disobey
// the [start, start + count) convention expected in tests.
yield return Label("Skip", (start, count, source) => source(start - count, count * 2).Skip(count));
yield return Label("SkipWhile", (start, count, source) => source(start - count, count * 2).SkipWhile(x => x < start));
yield return Label("SkipWhile-Index", (start, count, source) => source(start - count, count * 2).SkipWhile((x, index) => x < start));
yield return Label("Take", (start, count, source) => source(start, count * 2).Take(count));
yield return Label("TakeWhile", (start, count, source) => source(start, count * 2).TakeWhile(x => x < start + count));
yield return Label("TakeWhile-Index", (start, count, source) => source(start, count * 2).TakeWhile((x, index) => x < start + count));
}
public static IEnumerable<object[]> SkipTakeOperators()
{
foreach (Labeled<Operation> source in RangeSources())
{
foreach (Labeled<Operation> operation in SkipTakeOperations())
{
yield return new object[] { source, operation };
}
}
}
public static IEnumerable<object[]> UnaryOperators()
{
// Apply an ordered source to each operation
foreach (Labeled<Operation> source in RangeSources())
{
foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0]).Where(op => !op.ToString().Contains("Reverse")))
{
yield return new object[] { source, operation };
}
}
Labeled<Operation> reverse = UnaryOperations().Select(i => (Labeled<Operation>)i[0]).Where(op => op.ToString().Contains("Reverse")).Single();
foreach (Labeled<Operation> source in UnorderedRangeSources())
{
foreach (Labeled<Operation> ordering in ReverseOrderOperators())
{
yield return new object[] { source.Append(ordering), reverse };
}
}
// Apply ordering to the output of each operation
foreach (Labeled<Operation> source in UnorderedRangeSources())
{
foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0]))
{
foreach (Labeled<Operation> ordering in OrderOperators())
{
yield return new object[] { source, operation.Append(ordering) };
}
}
}
foreach (object[] parms in SkipTakeOperators())
{
yield return parms;
}
}
public static IEnumerable<object[]> UnaryFailingOperators()
{
foreach (Labeled<Operation> operation in new[] {
Label("Distinct", (start, count, s) => s(start, count).Distinct(new FailingEqualityComparer<int>())),
Label("GroupBy", (start, count, s) => s(start, count).GroupBy<int, int>(x => {throw new DeliberateTestException(); }).Select(g => g.Key)),
Label("GroupBy-Comparer", (start, count, s) => s(start, count).GroupBy(x => x, new FailingEqualityComparer<int>()).Select(g => g.Key)),
Label("GroupBy-ElementSelector", (start, count, s) => s(start, count).GroupBy<int, int, int>(x => x, x => { throw new DeliberateTestException(); }).Select(g => g.Key)),
Label("GroupBy-ResultSelector", (start, count, s) => s(start, count).GroupBy<int, int, int, int>(x => x, x => x, (x, g) => { throw new DeliberateTestException(); })),
Label("Select", (start, count, s) => s(start, count).Select<int, int>(x => {throw new DeliberateTestException(); })),
Label("Select-Index", (start, count, s) => s(start, count).Select<int, int>((x, index) => {throw new DeliberateTestException(); })),
Label("SelectMany", (start, count, s) => s(start, count).SelectMany<int, int>(x => {throw new DeliberateTestException(); })),
Label("SelectMany-Index", (start, count, s) => s(start, count).SelectMany<int, int>((x, index) => {throw new DeliberateTestException(); })),
Label("SelectMany-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>(x => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })),
Label("SelectMany-Index-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>((x, index) => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })),
Label("SkipWhile", (start, count, s) => s(start, count).SkipWhile(x => {throw new DeliberateTestException(); })),
Label("SkipWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })),
Label("TakeWhile", (start, count, s) => s(start, count).TakeWhile(x => {throw new DeliberateTestException(); })),
Label("TakeWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })),
Label("Where", (start, count, s) => s(start, count).Where(x => {throw new DeliberateTestException(); })),
Label("Where-Index", (start, count, s) => s(start, count).Where((x, index) => {throw new DeliberateTestException(); })),
})
{
yield return new object[] { LabeledDefaultSource, operation };
}
foreach (Labeled<Operation> operation in UnaryOperations().Select(i => i[0]).Cast<Labeled<Operation>>().Concat(SkipTakeOperations()))
{
yield return new object[] { Failing, operation };
}
}
public static IEnumerable<object[]> UnaryCancelingOperators()
{
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Distinct", (source, cancel) => source.Distinct(new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupBy-Comparer", (source, cancel) => source.GroupBy(x => x, new CancelingEqualityComparer<int>(cancel)).Select(g => g.Key)) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany", (source, cancel) => source.SelectMany(x => { cancel(); return new[] { x }; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-Index", (source, cancel) => source.SelectMany((x, index) => { cancel(); return new[] { x }; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-ResultSelector", (source, cancel) => source.SelectMany(x => new[] { x }, (group, elem) => { cancel(); return elem; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-Index-ResultSelector", (source, cancel) => source.SelectMany((x, index) => new[] { x }, (group, elem) => { cancel(); return elem; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SkipWhile", (source, cancel) => source.SkipWhile(x => { cancel(); return true; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SkipWhile-Index", (source, cancel) => source.SkipWhile((x, index) => { cancel(); return true; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("TakeWhile", (source, cancel) => source.TakeWhile(x => { cancel(); return true; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("TakeWhile-Index", (source, cancel) => source.TakeWhile((x, index) => { cancel(); return true; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Where", (source, cancel) => source.Where(x => { cancel(); return true; })) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Where-Index", (source, cancel) => source.Where((x, index) => { cancel(); return true; })) };
}
private static IEnumerable<Labeled<Operation>> BinaryOperations(Labeled<Operation> otherSource)
{
string label = otherSource.ToString();
Operation other = otherSource.Item;
yield return Label("Concat-Right:" + label, (start, count, source) => source(start, count / 2).Concat(other(start + count / 2, count / 2 + count % 2)));
yield return Label("Concat-Left:" + label, (start, count, source) => other(start, count / 2).Concat(source(start + count / 2, count / 2 + count % 2)));
// Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined for unordered collections.
yield return Label("Except-Right:" + label, (start, count, source) => source(start, count + count / 2).Except(other(start + count, count), new ModularCongruenceComparer(count * 2)));
yield return Label("Except-Left:" + label, (start, count, source) => other(start, count + count / 2).Except(source(start + count, count), new ModularCongruenceComparer(count * 2)));
yield return Label("GroupJoin-Right:" + label, (start, count, source) => source(start, count).GroupJoin(other(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count)));
yield return Label("GroupJoin-Left:" + label, (start, count, source) => other(start, count).GroupJoin(source(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count)));
// Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined.
yield return Label("Intersect-Right:" + label, (start, count, source) => source(start, count + count / 2).Intersect(other(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2)));
yield return Label("Intersect-Left:" + label, (start, count, source) => other(start, count + count / 2).Intersect(source(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2)));
yield return Label("Join-Right:" + label, (start, count, source) => source(0, count).Join(other(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count)));
yield return Label("Join-Left:" + label, (start, count, source) => other(0, count).Join(source(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count)));
yield return Label("Union-Right:" + label, (start, count, source) => source(start, count * 3 / 4).Union(other(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count)));
yield return Label("Union-Left:" + label, (start, count, source) => other(start, count * 3 / 4).Union(source(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count)));
// When both sources are unordered any element can be matched to any other, so a different check is required.
yield return Label("Zip-Unordered-Right:" + label, (start, count, source) => source(0, count).Zip(other(start * 2, count), (x, y) => x + start));
yield return Label("Zip-Unordered-Left:" + label, (start, count, source) => other(start * 2, count).Zip(source(0, count), (x, y) => y + start));
}
public static IEnumerable<object[]> BinaryOperations()
{
return BinaryOperations(LabeledDefaultSource).Select(op => new object[] { op });
}
public static IEnumerable<object[]> BinaryUnorderedOperators()
{
foreach (Labeled<Operation> source in UnorderedRangeSources())
{
// Operations having multiple paths to check.
foreach (Labeled<Operation> operation in BinaryOperations(LabeledDefaultSource))
{
yield return new object[] { source, operation };
}
}
}
public static IEnumerable<object[]> BinaryOperators()
{
foreach (Labeled<Operation> source in RangeSources())
{
// Each binary can work differently, depending on which of the two source queries (or both) is ordered.
// For most, only the ordering of the first query is important
foreach (Labeled<Operation> operation in BinaryOperations(LabeledDefaultSource).Where(op => !(op.ToString().StartsWith("Union") || op.ToString().StartsWith("Zip") || op.ToString().StartsWith("Concat")) && op.ToString().Contains("Right")))
{
yield return new object[] { source, operation };
}
// For Concat and Union, both sources must be ordered
foreach (var operation in BinaryOperations(RangeSources().First()).Where(op => op.ToString().StartsWith("Concat") || op.ToString().StartsWith("Union")))
{
yield return new object[] { source, operation };
}
// Zip is the same as Concat, but has a special check for matching indices (as compared to unordered)
foreach (Labeled<Operation> operation in new[] {
Label("Zip-Ordered-Right", (start, count, s) => s(0, count).Zip(DefaultSource(start * 2, count).AsOrdered(), (x, y) => (x + y) / 2)),
Label("Zip-Ordered-Left", (start, count, s) => DefaultSource(start * 2, count).AsOrdered().Zip(s(0, count), (x, y) => (x + y) / 2))
})
{
yield return new object[] { source, operation };
}
}
// Ordering the output should always be safe
foreach (object[] parameters in BinaryUnorderedOperators())
{
foreach (Labeled<Operation> ordering in OrderOperators())
{
yield return new[] { parameters[0], ((Labeled<Operation>)parameters[1]).Append(ordering) };
}
}
}
public static IEnumerable<object[]> BinaryFailingOperators()
{
Labeled<Operation> failing = Label("Failing", (start, count, s) => s(start, count).Select<int, int>(x => { throw new DeliberateTestException(); }));
foreach (Labeled<Operation> operation in BinaryOperations(LabeledDefaultSource))
{
yield return new object[] { LabeledDefaultSource.Append(failing), operation };
yield return new object[] { Failing, operation };
}
foreach (Labeled<Operation> operation in new[]
{
Label("Except-Fail", (start, count, s) => s(start, count).Except(DefaultSource(start, count), new FailingEqualityComparer<int>())),
Label("GroupJoin-Fail", (start, count, s) => s(start, count).GroupJoin(DefaultSource(start, count), x => x, y => y, (x, g) => x, new FailingEqualityComparer<int>())),
Label("Intersect-Fail", (start, count, s) => s(start, count).Intersect(DefaultSource(start, count), new FailingEqualityComparer<int>())),
Label("Join-Fail", (start, count, s) => s(start, count).Join(DefaultSource(start, count), x => x, y => y, (x, y) => x, new FailingEqualityComparer<int>())),
Label("Union-Fail", (start, count, s) => s(start, count).Union(DefaultSource(start, count), new FailingEqualityComparer<int>())),
Label("Zip-Fail", (start, count, s) => s(start, count).Zip<int, int, int>(DefaultSource(start, count), (x, y) => { throw new DeliberateTestException(); })),
})
{
yield return new object[] { LabeledDefaultSource, operation };
}
}
public static IEnumerable<object[]> BinaryCancelingOperators()
{
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Except", (source, cancel) => source.Except(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Except-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Except(source, new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupJoin", (source, cancel) => source.GroupJoin(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, g) => x, new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupJoin-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).GroupJoin(source, x => x, y => y, (x, g) => x, new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Intersect", (source, cancel) => source.Intersect(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Intersect-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Intersect(source, new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Join", (source, cancel) => source.Join(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, y) => x, new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Join-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Join(source, x => x, y => y, (x, y) => x, new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Union", (source, cancel) => source.Union(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))) };
yield return new object[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Union-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Union(source, new CancelingEqualityComparer<int>(cancel))) };
}
public delegate ParallelQuery<int> Operation(int start, int count, Operation source = null);
public static Labeled<Operation> Label(string label, Operation item)
{
return Labeled.Label(label, item);
}
public static Labeled<Operation> Append(this Labeled<Operation> item, Labeled<Operation> next)
{
Operation op = item.Item;
Operation nxt = next.Item;
return Label(item.ToString() + "|" + next.ToString(), (start, count, source) => nxt(start, count, (s, c, ignore) => op(s, c, source)));
}
public static Labeled<Operation> AsOrdered(this Labeled<Operation> query)
{
return query.Append(Label("AsOrdered", (start, count, source) => source(start, count).AsOrdered()));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using RestSharp;
using Systran.NlpClientLib.Client;
using Systran.NlpClientLib.Model;
namespace Systran.NlpClientLib.Api {
public interface ITranscriptionApi {
/// <summary>
/// Supported Languages List of languages pairs in which Transcription is supported. This list can be limited to a specific source language or target language.
/// </summary>
/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>TranscriptionSupportedLanguagesResponse</returns>
TranscriptionSupportedLanguagesResponse NlpTranscriptionSupportedLanguagesGet (string Source, string Target, string Callback);
/// <summary>
/// Supported Languages List of languages pairs in which Transcription is supported. This list can be limited to a specific source language or target language.
/// </summary>
/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>TranscriptionSupportedLanguagesResponse</returns>
Task<TranscriptionSupportedLanguagesResponse> NlpTranscriptionSupportedLanguagesGetAsync (string Source, string Target, string Callback);
/// <summary>
/// Transcribe Transcribe text from a source language to a target language.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>string</returns>
string NlpTranscriptionTranscribeGet (string InputFile, string Input, string Source, string Target, int? Profile, string Callback);
/// <summary>
/// Transcribe Transcribe text from a source language to a target language.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>string</returns>
Task<string> NlpTranscriptionTranscribeGetAsync (string InputFile, string Input, string Source, string Target, int? Profile, string Callback);
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public class TranscriptionApi : ITranscriptionApi {
/// <summary>
/// Initializes a new instance of the <see cref="TranscriptionApi"/> class.
/// </summary>
/// <param name="apiClient"> an instance of ApiClient (optional)
/// <returns></returns>
public TranscriptionApi(ApiClient apiClient = null) {
if (apiClient == null) { // use the default one in Configuration
this.apiClient = Configuration.apiClient;
} else {
this.apiClient = apiClient;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="TranscriptionApi"/> class.
/// </summary>
/// <returns></returns>
public TranscriptionApi(String basePath)
{
this.apiClient = new ApiClient(basePath);
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public void SetBasePath(String basePath) {
this.apiClient.basePath = basePath;
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath(String basePath) {
return this.apiClient.basePath;
}
/// <summary>
/// Gets or sets the API client.
/// </summary>
/// <value>The API client</value>
public ApiClient apiClient {get; set;}
/// <summary>
/// Supported Languages List of languages pairs in which Transcription is supported. This list can be limited to a specific source language or target language.
/// </summary>
/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>TranscriptionSupportedLanguagesResponse</returns>
public TranscriptionSupportedLanguagesResponse NlpTranscriptionSupportedLanguagesGet (string Source, string Target, string Callback) {
var path = "/nlp/transcription/supportedLanguages";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Source != null) queryParams.Add("source", apiClient.ParameterToString(Source)); // query parameter
if (Target != null) queryParams.Add("target", apiClient.ParameterToString(Target)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpTranscriptionSupportedLanguagesGet: " + response.Content, response.Content);
}
return (TranscriptionSupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(TranscriptionSupportedLanguagesResponse));
}
/// <summary>
/// Supported Languages List of languages pairs in which Transcription is supported. This list can be limited to a specific source language or target language.
/// </summary>
/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>TranscriptionSupportedLanguagesResponse</returns>
public async Task<TranscriptionSupportedLanguagesResponse> NlpTranscriptionSupportedLanguagesGetAsync (string Source, string Target, string Callback) {
var path = "/nlp/transcription/supportedLanguages";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Source != null) queryParams.Add("source", apiClient.ParameterToString(Source)); // query parameter
if (Target != null) queryParams.Add("target", apiClient.ParameterToString(Target)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpTranscriptionSupportedLanguagesGet: " + response.Content, response.Content);
}
return (TranscriptionSupportedLanguagesResponse) apiClient.Deserialize(response.Content, typeof(TranscriptionSupportedLanguagesResponse));
}
/// <summary>
/// Transcribe Transcribe text from a source language to a target language.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>string</returns>
public string NlpTranscriptionTranscribeGet (string InputFile, string Input, string Source, string Target, int? Profile, string Callback) {
// verify the required parameter 'Source' is set
if (Source == null) throw new ApiException(400, "Missing required parameter 'Source' when calling NlpTranscriptionTranscribeGet");
// verify the required parameter 'Target' is set
if (Target == null) throw new ApiException(400, "Missing required parameter 'Target' when calling NlpTranscriptionTranscribeGet");
var path = "/nlp/transcription/transcribe";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Source != null) queryParams.Add("source", apiClient.ParameterToString(Source)); // query parameter
if (Target != null) queryParams.Add("target", apiClient.ParameterToString(Target)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) apiClient.CallApi(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpTranscriptionTranscribeGet: " + response.Content, response.Content);
}
return (string) response.Content;
}
/// <summary>
/// Transcribe Transcribe text from a source language to a target language.\n
/// </summary>
/// <param name="InputFile">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Input">input text\n\n**Either `input` or `inputFile` is required**\n</param>/// <param name="Source">Source Language code ([details](#description_langage_code_values))</param>/// <param name="Target">Target Language code ([details](#description_langage_code_values))</param>/// <param name="Profile">Profile id\n</param>/// <param name="Callback">Javascript callback function name for JSONP Support\n</param>
/// <returns>string</returns>
public async Task<string> NlpTranscriptionTranscribeGetAsync (string InputFile, string Input, string Source, string Target, int? Profile, string Callback) {
// verify the required parameter 'Source' is set
if (Source == null) throw new ApiException(400, "Missing required parameter 'Source' when calling NlpTranscriptionTranscribeGet");
// verify the required parameter 'Target' is set
if (Target == null) throw new ApiException(400, "Missing required parameter 'Target' when calling NlpTranscriptionTranscribeGet");
var path = "/nlp/transcription/transcribe";
path = path.Replace("{format}", "json");
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
var formParams = new Dictionary<String, String>();
var fileParams = new Dictionary<String, String>();
String postBody = null;
if (Input != null) queryParams.Add("input", apiClient.ParameterToString(Input)); // query parameter
if (Source != null) queryParams.Add("source", apiClient.ParameterToString(Source)); // query parameter
if (Target != null) queryParams.Add("target", apiClient.ParameterToString(Target)); // query parameter
if (Profile != null) queryParams.Add("profile", apiClient.ParameterToString(Profile)); // query parameter
if (Callback != null) queryParams.Add("callback", apiClient.ParameterToString(Callback)); // query parameter
if (InputFile != null) fileParams.Add("inputFile", InputFile);
// authentication setting, if any
String[] authSettings = new String[] { "accessToken", "apiKey" };
// make the HTTP request
IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, authSettings);
if (((int)response.StatusCode) >= 400) {
throw new ApiException ((int)response.StatusCode, "Error calling NlpTranscriptionTranscribeGet: " + response.Content, response.Content);
}
return (string) response.Content;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ConvertScalarToVector128UInt64UInt64()
{
var test = new ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt64UInt64();
if (test.IsSupported)
{
// Validates basic functionality works
test.RunBasicScenario_UnsafeRead();
// Validates calling via reflection works
test.RunReflectionScenario_UnsafeRead();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works
test.RunLclVarScenario_UnsafeRead();
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt64UInt64
{
private struct TestStruct
{
public UInt64 _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
testStruct._fld = TestLibrary.Generator.GetUInt64();
return testStruct;
}
public void RunStructFldScenario(ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt64UInt64 testClass)
{
var result = Sse2.X64.ConvertScalarToVector128UInt64(_fld);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt64>>() / sizeof(UInt64);
private static UInt64 _data;
private static UInt64 _clsVar;
private UInt64 _fld;
private ScalarSimdUnaryOpTest__DataTable<UInt64> _dataTable;
static ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt64UInt64()
{
_clsVar = TestLibrary.Generator.GetUInt64();
}
public ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt64UInt64()
{
Succeeded = true;
_fld = TestLibrary.Generator.GetUInt64();
_data = TestLibrary.Generator.GetUInt64();
_dataTable = new ScalarSimdUnaryOpTest__DataTable<UInt64>(new UInt64[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.X64.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.X64.ConvertScalarToVector128UInt64(
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_data, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2.X64).GetMethod(nameof(Sse2.X64.ConvertScalarToVector128UInt64), new Type[] { typeof(UInt64) })
.Invoke(null, new object[] {
Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result));
ValidateResult(_data, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.X64.ConvertScalarToVector128UInt64(
_clsVar
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var data = Unsafe.ReadUnaligned<UInt64>(ref Unsafe.As<UInt64, byte>(ref _data));
var result = Sse2.X64.ConvertScalarToVector128UInt64(data);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(data, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ScalarSimdUnaryOpTest__ConvertScalarToVector128UInt64UInt64();
var result = Sse2.X64.ConvertScalarToVector128UInt64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.X64.ConvertScalarToVector128UInt64(_fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.X64.ConvertScalarToVector128UInt64(test._fld);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(UInt64 firstOp, void* result, [CallerMemberName] string method = "")
{
UInt64[] outArray = new UInt64[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt64>>());
ValidateResult(firstOp, outArray, method);
}
private void ValidateResult(UInt64 firstOp, UInt64[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (firstOp != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (false)
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2.X64)}.{nameof(Sse2.X64.ConvertScalarToVector128UInt64)}<UInt64>(UInt64): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using Xunit;
using Microsoft.DotNet.XUnitExtensions;
public class WindowAndCursorProps : RemoteExecutorTestBase
{
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferWidth_GetUnix_ReturnsWindowWidth()
{
Assert.Equal(Console.WindowWidth, Console.BufferWidth);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferWidth_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.BufferWidth = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferHeight_GetUnix_ReturnsWindowHeight()
{
Assert.Equal(Console.WindowHeight, Console.BufferHeight);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void BufferHeight_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.BufferHeight = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void SetBufferSize_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetBufferSize(0, 0));
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(0)]
[InlineData(-1)]
public static void WindowWidth_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowWidth = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.WindowWidth = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowWidth_GetUnix_Success()
{
// Validate that Console.WindowWidth returns some value in a non-redirected o/p.
Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth));
Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowWidth));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowWidth_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowWidth = 100);
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows
[InlineData(0)]
[InlineData(-1)]
public static void WindowHeight_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowHeight = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.WindowHeight = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowHeight_GetUnix_Success()
{
// Validate that Console.WindowHeight returns some value in a non-redirected o/p.
Helpers.RunInNonRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight));
Helpers.RunInRedirectedOutput((data) => Console.WriteLine(Console.WindowHeight));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowHeight_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowHeight = 100);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void LargestWindowWidth_UnixGet_ReturnsExpected()
{
Helpers.RunInNonRedirectedOutput((data) => Assert.Equal(Console.WindowWidth, Console.LargestWindowWidth));
Helpers.RunInRedirectedOutput((data) => Assert.Equal(Console.WindowWidth, Console.LargestWindowWidth));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void LargestWindowHeight_UnixGet_ReturnsExpected()
{
Helpers.RunInNonRedirectedOutput((data) => Assert.Equal(Console.WindowHeight, Console.LargestWindowHeight));
Helpers.RunInRedirectedOutput((data) => Assert.Equal(Console.WindowHeight, Console.LargestWindowHeight));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowLeft_GetUnix_ReturnsZero()
{
Assert.Equal(0, Console.WindowLeft);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowLeft_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowLeft = 0);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowTop_GetUnix_ReturnsZero()
{
Assert.Equal(0, Console.WindowTop);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void WindowTop_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.WindowTop = 0);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Expected behavior specific to Windows
public static void WindowLeftTop_Windows()
{
if (Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.WindowLeft);
Assert.Throws<IOException>(() => Console.WindowTop);
}
else
{
Console.WriteLine(Console.WindowLeft);
Console.WriteLine(Console.WindowTop);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] //CI system makes it difficult to run things in a non-redirected environments.
public static void NonRedirectedCursorVisible()
{
if (!Console.IsOutputRedirected)
{
// Validate that Console.CursorVisible adds something to the stream when in a non-redirected environment.
Helpers.RunInNonRedirectedOutput((data) => { Console.CursorVisible = false; Assert.True(data.ToArray().Length > 0); });
Helpers.RunInNonRedirectedOutput((data) => { Console.CursorVisible = true; Assert.True(data.ToArray().Length > 0); });
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void CursorVisible_GetUnix_ThrowsPlatformNotSupportedExeption()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorVisible);
}
[Theory]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
[InlineData(true)]
[InlineData(false)]
public static void CursorVisible_SetUnixRedirected_Nop(bool value)
{
Helpers.RunInRedirectedOutput((data) => {
Console.CursorVisible = value;
Assert.Equal(0, data.ToArray().Length);
});
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void Title_GetUnix_ThrowPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.Title);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)] // Expected behavior specific to Unix
public static void Title_SetUnix_Success()
{
RemoteInvoke(() =>
{
Console.Title = "Title set by unit test";
return SuccessExitCode;
}).Dispose();
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "// NETFX does not have the fix https://github.com/dotnet/corefx/pull/28905")]
public static void Title_GetWindows_ReturnsNonNull()
{
Assert.NotNull(Console.Title);
}
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
[PlatformSpecific(TestPlatforms.Windows)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "// NETFX does not have the fix https://github.com/dotnet/corefx/pull/28905")]
public static void Title_Get_Windows_NoNulls()
{
string title = Console.Title;
string trimmedTitle = title.TrimEnd('\0');
Assert.Equal(trimmedTitle, title);
}
[ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // Nano currently ignores set title
[InlineData(0)]
[InlineData(1)]
[InlineData(254)]
[InlineData(255)]
[InlineData(256)]
[InlineData(257)]
[InlineData(511)]
[InlineData(512)]
[InlineData(513)]
[InlineData(1024)]
[PlatformSpecific(TestPlatforms.Windows)]
public static void Title_Set_Windows(int lengthOfTitle)
{
// Try to set the title to some other value.
RemoteInvoke(lengthOfTitleString =>
{
string newTitle = new string('a', int.Parse(lengthOfTitleString));
Console.Title = newTitle;
if (newTitle.Length >= 511 && !PlatformDetection.IsNetCore && PlatformDetection.IsWindows10Version1703OrGreater && !PlatformDetection.IsWindows10Version1709OrGreater)
{
// RS2 has a bug when getting the window title when the title length is longer than 513 character
Assert.Throws<IOException>(() => Console.Title);
}
else
{
Assert.Equal(newTitle, Console.Title);
}
return SuccessExitCode;
}, lengthOfTitle.ToString()).Dispose();
}
public static void Title_GetWindowsUap_ThrowsIOException()
{
Assert.Throws<IOException>(() => Console.Title);
}
public static void Title_SetWindowsUap_ThrowsIOException(int lengthOfTitle)
{
Assert.Throws<IOException>(() => Console.Title = "x");
}
[Fact]
public static void Title_SetNull_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("value", () => Console.Title = null);
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.NetFramework)]
public static void Title_SetGreaterThan24500Chars_ThrowsArgumentOutOfRangeException()
{
// We don't explicitly throw on Core as this isn't technically correct
string newTitle = new string('a', 24501);
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Console.Title = newTitle);
}
[Fact]
[OuterLoop] // makes noise, not very inner-loop friendly
public static void Beep_Invoke_Success()
{
// Nothing to verify; just run the code.
Console.Beep();
}
[Fact]
[OuterLoop] // makes noise, not very inner-loop friendly
[PlatformSpecific(TestPlatforms.Windows)]
public static void BeepWithFrequency_Invoke_Success()
{
// Nothing to verify; just run the code.
Console.Beep(800, 200);
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(36)]
[InlineData(32768)]
public void BeepWithFrequency_InvalidFrequency_ThrowsArgumentOutOfRangeException(int frequency)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("frequency", () => Console.Beep(frequency, 200));
}
[Theory]
[PlatformSpecific(TestPlatforms.Windows)]
[InlineData(0)]
[InlineData(-1)]
public void BeepWithFrequency_InvalidDuration_ThrowsArgumentOutOfRangeException(int duration)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("duration", () => Console.Beep(800, duration));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void BeepWithFrequency_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.Beep(800, 200));
}
[Fact]
[OuterLoop] // clears the screen, not very inner-loop friendly
public static void Clear_Invoke_Success()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (!Console.IsInputRedirected && !Console.IsOutputRedirected))
{
// Nothing to verify; just run the code.
Console.Clear();
}
}
[Fact]
public static void SetCursorPosition_Invoke_Success()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || (!Console.IsInputRedirected && !Console.IsOutputRedirected))
{
int origLeft = Console.CursorLeft;
int origTop = Console.CursorTop;
// Nothing to verify; just run the code.
// On windows, we might end of throwing IOException, since the handles are redirected.
Console.SetCursorPosition(0, 0);
Console.SetCursorPosition(1, 2);
Console.SetCursorPosition(origLeft, origTop);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
public void SetCursorPosition_InvalidPosition_ThrowsArgumentOutOfRangeException(int value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetCursorPosition(value, 100));
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetCursorPosition(100, value));
}
[Fact]
public static void GetCursorPosition_Invoke_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origLeft = Console.CursorLeft, origTop = Console.CursorTop;
Console.SetCursorPosition(10, 12);
Assert.Equal(10, Console.CursorLeft);
Assert.Equal(12, Console.CursorTop);
Console.SetCursorPosition(origLeft, origTop);
Assert.Equal(origLeft, Console.CursorLeft);
Assert.Equal(origTop, Console.CursorTop);
}
else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(0, Console.CursorLeft);
Assert.Equal(0, Console.CursorTop);
}
}
[Fact]
public void CursorLeft_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origLeft = Console.CursorLeft;
Console.CursorLeft = 10;
Assert.Equal(10, Console.CursorLeft);
Console.CursorLeft = origLeft;
Assert.Equal(origLeft, Console.CursorLeft);
}
else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(0, Console.CursorLeft);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
public void CursorLeft_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (PlatformDetection.IsWindows && Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.CursorLeft = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.CursorLeft = value);
}
}
[Fact]
public void CursorTop_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int origTop = Console.CursorTop;
Console.CursorTop = 10;
Assert.Equal(10, Console.CursorTop);
Console.CursorTop = origTop;
Assert.Equal(origTop, Console.CursorTop);
}
else if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
Assert.Equal(0, Console.CursorTop);
}
}
[Theory]
[InlineData(-1)]
[InlineData(short.MaxValue + 1)]
public void CursorTop_SetInvalid_ThrowsArgumentOutOfRangeException(int value)
{
if (PlatformDetection.IsWindows & Console.IsOutputRedirected)
{
Assert.Throws<IOException>(() => Console.CursorTop = value);
}
else
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.CursorTop = value);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void CursorSize_Set_GetReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
int orig = Console.CursorSize;
try
{
Console.CursorSize = 50;
Assert.Equal(50, Console.CursorSize);
}
finally
{
Console.CursorSize = orig;
}
}
}
[Theory]
[InlineData(0)]
[InlineData(101)]
[PlatformSpecific(TestPlatforms.Windows)]
public void CursorSize_SetInvalidValue_ThrowsArgumentOutOfRangeException(int value)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => Console.CursorSize = value);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void CursorSize_GetUnix_ReturnsExpected()
{
Assert.Equal(100, Console.CursorSize);
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void CursorSize_SetUnix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.CursorSize = 1);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void SetWindowPosition_GetWindowPosition_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(-1, Console.WindowTop));
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetWindowPosition(Console.WindowLeft, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("left", () => Console.SetWindowPosition(Console.BufferWidth - Console.WindowWidth + 2, Console.WindowTop));
AssertExtensions.Throws<ArgumentOutOfRangeException>("top", () => Console.SetWindowPosition(Console.WindowHeight, Console.BufferHeight - Console.WindowHeight + 2));
int origTop = Console.WindowTop;
int origLeft = Console.WindowLeft;
try
{
Console.SetWindowPosition(0, 0);
Assert.Equal(0, Console.WindowTop);
Assert.Equal(0, Console.WindowLeft);
}
finally
{
Console.WindowTop = origTop;
Console.WindowLeft = origLeft;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SetWindowPosition_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowPosition(50, 50));
}
[PlatformSpecific(TestPlatforms.Windows)]
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))]
public void SetWindowSize_GetWindowSize_ReturnsExpected()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(-1, Console.WindowHeight));
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowHeight, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(short.MaxValue - Console.WindowLeft, Console.WindowHeight));
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowWidth, short.MaxValue - Console.WindowTop));
AssertExtensions.Throws<ArgumentOutOfRangeException>("width", () => Console.SetWindowSize(Console.LargestWindowWidth + 1, Console.WindowHeight));
AssertExtensions.Throws<ArgumentOutOfRangeException>("height", () => Console.SetWindowSize(Console.WindowWidth, Console.LargestWindowHeight + 1));
int origWidth = Console.WindowWidth;
int origHeight = Console.WindowHeight;
try
{
Console.SetWindowSize(10, 10);
Assert.Equal(10, Console.WindowWidth);
Assert.Equal(10, Console.WindowHeight);
}
finally
{
Console.WindowWidth = origWidth;
Console.WindowHeight = origHeight;
}
}
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void SetWindowSize_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.SetWindowSize(50, 50));
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea_DefaultChar()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, -1, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(0, 0, -1, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 0, 0, -1, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, -1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, -1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceLeft", () => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetLeft", () => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceTop", () => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("targetTop", () => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceHeight", () => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0));
AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceWidth", () => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0));
// Nothing to verify; just run the code.
Console.MoveBufferArea(0, 0, 1, 1, 2, 2);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea()
{
if (!Console.IsInputRedirected && !Console.IsOutputRedirected)
{
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(-1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, -1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, -1, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, -1, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, -1, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, -1, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(Console.BufferWidth + 1, 0, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, Console.BufferWidth + 1, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, Console.BufferHeight + 1, 0, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, Console.BufferHeight + 1, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(0, 1, 0, Console.BufferHeight, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
Assert.Throws<ArgumentOutOfRangeException>(() => Console.MoveBufferArea(1, 0, Console.BufferWidth, 0, 0, 0, '0', ConsoleColor.Black, ConsoleColor.White));
// Nothing to verify; just run the code.
Console.MoveBufferArea(0, 0, 1, 1, 2, 2, 'a', ConsoleColor.Black, ConsoleColor.White);
}
}
[Theory]
[InlineData(ConsoleColor.Black - 1)]
[InlineData(ConsoleColor.White + 1)]
[PlatformSpecific(TestPlatforms.Windows)]
public void MoveBufferArea_InvalidColor_ThrowsException(ConsoleColor color)
{
AssertExtensions.Throws<ArgumentException>("sourceForeColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', color, ConsoleColor.Black));
AssertExtensions.Throws<ArgumentException>("sourceBackColor", () => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'a', ConsoleColor.Black, color));
}
[Fact]
[PlatformSpecific(TestPlatforms.AnyUnix)]
public void MoveBufferArea_Unix_ThrowsPlatformNotSupportedException()
{
Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0));
Assert.Throws<PlatformNotSupportedException>(() => Console.MoveBufferArea(0, 0, 0, 0, 0, 0, 'c', ConsoleColor.White, ConsoleColor.Black));
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.Compiler.Common;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.ProjectModel;
using Microsoft.DotNet.Tools.Compiler;
namespace Microsoft.DotNet.Tools.Build
{
internal class DotNetProjectBuilder : ProjectBuilder
{
private readonly BuildCommandApp _args;
private readonly IncrementalPreconditionManager _preconditionManager;
private readonly CompilerIOManager _compilerIOManager;
private readonly ScriptRunner _scriptRunner;
private readonly DotNetCommandFactory _commandFactory;
private readonly IncrementalManager _incrementalManager;
public DotNetProjectBuilder(BuildCommandApp args) : base(args.ShouldSkipDependencies)
{
_args = args;
_preconditionManager = new IncrementalPreconditionManager(
args.ShouldPrintIncrementalPreconditions,
args.ShouldNotUseIncrementality,
args.ShouldSkipDependencies);
_compilerIOManager = new CompilerIOManager(
args.ConfigValue,
args.OutputValue,
args.BuildBasePathValue,
args.GetRuntimes(),
args.Workspace
);
_incrementalManager = new IncrementalManager(
this,
_compilerIOManager,
_preconditionManager,
_args.ShouldSkipDependencies,
_args.ConfigValue,
_args.BuildBasePathValue,
_args.OutputValue,
BuildIncrementalArgumentList(_args)
);
_scriptRunner = new ScriptRunner();
_commandFactory = new DotNetCommandFactory();
}
private static IDictionary<string, string> BuildIncrementalArgumentList(BuildCommandApp args) => new Dictionary<string, string>()
{
["version-suffix"] = args.VersionSuffixValue
};
private void StampProjectWithSDKVersion(ProjectContext project)
{
if (File.Exists(DotnetFiles.VersionFile))
{
var projectVersionFile = project.GetSDKVersionFile(_args.ConfigValue, _args.BuildBasePathValue, _args.OutputValue);
var parentDirectory = Path.GetDirectoryName(projectVersionFile);
if (!Directory.Exists(parentDirectory))
{
Directory.CreateDirectory(parentDirectory);
}
string content = DotnetFiles.ReadAndInterpretVersionFile();
File.WriteAllText(projectVersionFile, content);
}
else
{
Reporter.Verbose.WriteLine($"Project {project.GetDisplayName()} was not stamped with a CLI version because the version file does not exist: {DotnetFiles.VersionFile}");
}
}
private void PrintSummary(ProjectGraphNode projectNode, bool success)
{
// todo: Ideally it's the builder's responsibility for adding the time elapsed. That way we avoid cross cutting display concerns between compile and build for printing time elapsed
if (success)
{
var preconditions = _preconditionManager.GetIncrementalPreconditions(projectNode);
Reporter.Output.Write(" " + preconditions.LogMessage());
Reporter.Output.WriteLine();
}
Reporter.Output.WriteLine();
}
private void CopyCompilationOutput(OutputPaths outputPaths)
{
var dest = outputPaths.RuntimeOutputPath;
var source = outputPaths.CompilationOutputPath;
// No need to copy if dest and source are the same
if (string.Equals(dest, source, StringComparison.OrdinalIgnoreCase))
{
return;
}
foreach (var file in outputPaths.CompilationFiles.All())
{
var destFileName = file.Replace(source, dest);
var directoryName = Path.GetDirectoryName(destFileName);
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
File.Copy(file, destFileName, true);
}
}
private void MakeRunnable(ProjectGraphNode graphNode)
{
try
{
var runtimeContext = graphNode.ProjectContext.ProjectFile.HasRuntimeOutput(_args.ConfigValue) ?
_args.Workspace.GetRuntimeContext(graphNode.ProjectContext, _args.GetRuntimes()) :
graphNode.ProjectContext;
var outputPaths = runtimeContext.GetOutputPaths(_args.ConfigValue, _args.BuildBasePathValue, _args.OutputValue);
var libraryExporter = runtimeContext.CreateExporter(_args.ConfigValue, _args.BuildBasePathValue);
CopyCompilationOutput(outputPaths);
var executable = new Executable(runtimeContext, outputPaths, libraryExporter, _args.ConfigValue);
executable.MakeCompilationOutputRunnable();
}
catch (Exception e)
{
throw new Exception($"Failed to make the following project runnable: {graphNode.ProjectContext.GetDisplayName()} reason: {e.Message}", e);
}
}
protected override CompilationResult Build(ProjectGraphNode projectNode)
{
var result = base.Build(projectNode);
AfterRootBuild(projectNode, result);
return result;
}
protected void AfterRootBuild(ProjectGraphNode projectNode, CompilationResult result)
{
if (result != CompilationResult.IncrementalSkip && projectNode.IsRoot)
{
var success = result == CompilationResult.Success;
if (success)
{
MakeRunnable(projectNode);
}
PrintSummary(projectNode, success);
}
}
protected override CompilationResult RunCompile(ProjectGraphNode projectNode)
{
try
{
var managedCompiler = new ManagedCompiler(_scriptRunner, _commandFactory);
var success = managedCompiler.Compile(projectNode.ProjectContext, _args);
return success ? CompilationResult.Success : CompilationResult.Failure;
}
finally
{
StampProjectWithSDKVersion(projectNode.ProjectContext);
_incrementalManager.CacheIncrementalState(projectNode);
}
}
protected override void ProjectSkiped(ProjectGraphNode projectNode)
{
StampProjectWithSDKVersion(projectNode.ProjectContext);
_incrementalManager.CacheIncrementalState(projectNode);
}
protected override bool NeedsRebuilding(ProjectGraphNode graphNode)
{
var result = _incrementalManager.NeedsRebuilding(graphNode);
PrintIncrementalResult(graphNode.ProjectContext.GetDisplayName(), result);
return result.NeedsRebuilding;
}
private void PrintIncrementalResult(string projectName, IncrementalResult result)
{
if (result.NeedsRebuilding)
{
Reporter.Output.WriteLine($"Project {projectName} will be compiled because {result.Reason}");
PrintIncrementalItems(result);
}
else
{
Reporter.Output.WriteLine($"Project {projectName} was previously compiled. Skipping compilation.");
}
}
private static void PrintIncrementalItems(IncrementalResult result)
{
if (Reporter.IsVerbose)
{
foreach (var item in result.Items)
{
Reporter.Verbose.WriteLine($"\t{item}");
}
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="WebBrowserPermission.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// The WebBrowserPermission controls the ability to create the WebBrowsercontrol.
// In avalon - this control creates the ability for frames to navigate to html.
//
//
// History:
// 05/18/05: marka Created.
//---------------------------------------------------------------------------
using System;
using System.Security;
using System.Security.Permissions;
using System.IO;
using System.Runtime.Serialization;
using System.Collections;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Windows;
using MS.Internal.WindowsBase;
namespace System.Security.Permissions
{
///<summary>
/// Enum of permission levels.
///</summary>
public enum WebBrowserPermissionLevel
{
/// <summary>
/// WebBrowser not allowed
/// </summary>
None,
/// <summary>
/// Safe. Can create webbrowser with some restrictions.
/// </summary>
Safe,
/// <summary>
/// Unrestricted. Can create webbrowser with no restrictions.
/// </summary>
Unrestricted
}
///<summary>
/// The WebBrowserPermission controls the ability to create the WebBrowsercontrol.
/// In avalon - this permission grants the ability for frames to navigate to html.
/// The levels for this permission are :
/// None - not able to navigate frames to HTML.
/// Safe - able to navigate frames to HTML safely. This means that
/// there are several mitigations in effect. Namely.
/// Popup mitigation - unable to place an avalon popup over the weboc.
/// SiteLock - the WebOC can only be navigated to site of origin.
/// Url-Action-lockdown - the security settings of the weboc are reduced.
/// Unrestricted - able to navigate the weboc with no restrictions.
///</summary>
[Serializable()]
sealed public class WebBrowserPermission : CodeAccessPermission, IUnrestrictedPermission
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
///<summary>
/// WebBrowserPermission ctor.
///</summary>
public WebBrowserPermission()
{
_webBrowserPermissionLevel = WebBrowserPermissionLevel.Safe;
}
///<summary>
/// WebBrowserPermission ctor.
///</summary>
public WebBrowserPermission(PermissionState state)
{
if (state == PermissionState.Unrestricted)
{
_webBrowserPermissionLevel = WebBrowserPermissionLevel.Unrestricted;
}
else if (state == PermissionState.None)
{
_webBrowserPermissionLevel = WebBrowserPermissionLevel.None;
}
else
{
throw new ArgumentException( SR.Get(SRID.InvalidPermissionState) );
}
}
///<summary>
/// WebBrowserPermission ctor.
///</summary>
public WebBrowserPermission(WebBrowserPermissionLevel webBrowserPermissionLevel)
{
WebBrowserPermission.VerifyWebBrowserPermissionLevel(webBrowserPermissionLevel);
this._webBrowserPermissionLevel = webBrowserPermissionLevel;
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
//
// IUnrestrictedPermission implementation
//
///<summary>
/// Is this an unrestricted permisison ?
///</summary>
public bool IsUnrestricted()
{
return _webBrowserPermissionLevel == WebBrowserPermissionLevel.Unrestricted ;
}
//
// CodeAccessPermission implementation
//
///<summary>
/// Is this a subsetOf the target ?
///</summary>
public override bool IsSubsetOf(IPermission target)
{
if (target == null)
{
return _webBrowserPermissionLevel == WebBrowserPermissionLevel.None;
}
WebBrowserPermission operand = target as WebBrowserPermission ;
if ( operand != null )
{
return this._webBrowserPermissionLevel <= operand._webBrowserPermissionLevel;
}
else
{
throw new ArgumentException(SR.Get(SRID.TargetNotWebBrowserPermissionLevel));
}
}
///<summary>
/// Return the intersection with the target
///</summary>
public override IPermission Intersect(IPermission target)
{
if (target == null)
{
return null;
}
WebBrowserPermission operand = target as WebBrowserPermission ;
if ( operand != null )
{
WebBrowserPermissionLevel intersectLevel = _webBrowserPermissionLevel < operand._webBrowserPermissionLevel
? _webBrowserPermissionLevel : operand._webBrowserPermissionLevel;
if (intersectLevel == WebBrowserPermissionLevel.None)
{
return null;
}
else
{
return new WebBrowserPermission(intersectLevel);
}
}
else
{
throw new ArgumentException(SR.Get(SRID.TargetNotWebBrowserPermissionLevel));
}
}
///<summary>
/// Return the Union with the target
///</summary>
public override IPermission Union(IPermission target)
{
if (target == null)
{
return this.Copy();
}
WebBrowserPermission operand = target as WebBrowserPermission ;
if ( operand != null )
{
WebBrowserPermissionLevel unionLevel = _webBrowserPermissionLevel > operand._webBrowserPermissionLevel ?
_webBrowserPermissionLevel : operand._webBrowserPermissionLevel;
if (unionLevel == WebBrowserPermissionLevel.None)
{
return null;
}
else
{
return new WebBrowserPermission(unionLevel);
}
}
else
{
throw new ArgumentException(SR.Get(SRID.TargetNotWebBrowserPermissionLevel));
}
}
///<summary>
/// Copy this permission.
///</summary>
public override IPermission Copy()
{
return new WebBrowserPermission(this._webBrowserPermissionLevel);
}
///<summary>
/// Return an XML instantiation of this permisison.
///</summary>
public override SecurityElement ToXml()
{
SecurityElement securityElement = new SecurityElement("IPermission");
securityElement.AddAttribute("class", this.GetType().AssemblyQualifiedName);
securityElement.AddAttribute("version", "1");
if (IsUnrestricted())
{
securityElement.AddAttribute("Unrestricted", Boolean.TrueString);
}
else
{
securityElement.AddAttribute("Level", _webBrowserPermissionLevel.ToString());
}
return securityElement;
}
///<summary>
/// Create a permission from XML
///</summary>
public override void FromXml(SecurityElement securityElement)
{
if (securityElement == null)
{
throw new ArgumentNullException("securityElement");
}
String className = securityElement.Attribute("class");
if (className == null || className.IndexOf(this.GetType().FullName, StringComparison.Ordinal) == -1)
{
throw new ArgumentNullException("securityElement");
}
String unrestricted = securityElement.Attribute("Unrestricted");
if (unrestricted != null && Boolean.Parse(unrestricted))
{
_webBrowserPermissionLevel = WebBrowserPermissionLevel.Unrestricted;
return;
}
this._webBrowserPermissionLevel = WebBrowserPermissionLevel.None;
String level = securityElement.Attribute("Level");
if (level != null)
{
_webBrowserPermissionLevel = (WebBrowserPermissionLevel)Enum.Parse(typeof(WebBrowserPermissionLevel), level);
}
else
{
throw new ArgumentException(SR.Get(SRID.BadXml,"level")); // bad XML
}
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
///<summary>
/// Current permission level.
///</summary>
public WebBrowserPermissionLevel Level
{
get
{
return _webBrowserPermissionLevel;
}
set
{
WebBrowserPermission.VerifyWebBrowserPermissionLevel(value);
_webBrowserPermissionLevel = value;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
internal static void VerifyWebBrowserPermissionLevel(WebBrowserPermissionLevel level)
{
if (level < WebBrowserPermissionLevel.None || level > WebBrowserPermissionLevel.Unrestricted )
{
throw new ArgumentException(SR.Get(SRID.InvalidPermissionLevel));
}
}
#endregion Private Methods
//
// Private fields:
//
private WebBrowserPermissionLevel _webBrowserPermissionLevel;
}
///<summary>
/// Imperative attribute to create a WebBrowserPermission.
///</summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Assembly, AllowMultiple = true, Inherited = false )]
sealed public class WebBrowserPermissionAttribute : CodeAccessSecurityAttribute
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
///<summary>
/// Imperative attribute to create a WebBrowserPermission.
///</summary>
public WebBrowserPermissionAttribute(SecurityAction action) : base(action)
{
}
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
///<summary>
/// Create a WebBrowserPermisison.
///</summary>
public override IPermission CreatePermission()
{
if (Unrestricted)
{
return new WebBrowserPermission(PermissionState.Unrestricted);
}
else
{
return new WebBrowserPermission(_webBrowserPermissionLevel);
}
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
///<summary>
/// Current permission level.
///</summary>
public WebBrowserPermissionLevel Level
{
get
{
return _webBrowserPermissionLevel;
}
set
{
WebBrowserPermission.VerifyWebBrowserPermissionLevel(value);
_webBrowserPermissionLevel = value;
}
}
#endregion Public Properties
//
// Private fields:
//
private WebBrowserPermissionLevel _webBrowserPermissionLevel;
}
}
| |
// <copyright file="Actions.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.Generic;
using System.Drawing;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium.Interactions
{
/// <summary>
/// Provides values that indicate from where element offsets for MoveToElement
/// are calculated.
/// </summary>
public enum MoveToElementOffsetOrigin
{
/// <summary>
/// Offsets are calculated from the top-left corner of the element.
/// </summary>
TopLeft,
/// <summary>
/// Offsets are calcuated from the center of the element.
/// </summary>
Center
}
/// <summary>
/// Provides a mechanism for building advanced interactions with the browser.
/// </summary>
public class Actions : IAction
{
private readonly TimeSpan DefaultMouseMoveDuration = TimeSpan.FromMilliseconds(250);
private ActionBuilder actionBuilder = new ActionBuilder();
private PointerInputDevice defaultMouse = new PointerInputDevice(PointerKind.Mouse, "default mouse");
private KeyInputDevice defaultKeyboard = new KeyInputDevice("default keyboard");
private IKeyboard keyboard;
private IMouse mouse;
private IActionExecutor actionExecutor;
private CompositeAction action = new CompositeAction();
/// <summary>
/// Initializes a new instance of the <see cref="Actions"/> class.
/// </summary>
/// <param name="driver">The <see cref="IWebDriver"/> object on which the actions built will be performed.</param>
public Actions(IWebDriver driver)
{
//this.driver = driver;
IHasInputDevices inputDevicesDriver = GetDriverAs<IHasInputDevices>(driver);
if (inputDevicesDriver == null)
{
throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IHasInputDevices.", "driver");
}
IActionExecutor actionExecutor = GetDriverAs<IActionExecutor>(driver);
if (actionExecutor == null)
{
throw new ArgumentException("The IWebDriver object must implement or wrap a driver that implements IActionExecutor.", "driver");
}
this.keyboard = inputDevicesDriver.Keyboard;
this.mouse = inputDevicesDriver.Mouse;
this.actionExecutor = actionExecutor;
}
/// <summary>
/// Sends a modifier key down message to the browser.
/// </summary>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyDown(string theKey)
{
return this.KeyDown(null, theKey);
}
/// <summary>
/// Sends a modifier key down message to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the key command.</param>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyDown(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new KeyDownAction(this.keyboard, this.mouse, target, theKey));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(theKey[0]));
this.actionBuilder.AddAction(new PauseInteraction(this.defaultKeyboard, TimeSpan.FromMilliseconds(100)));
return this;
}
/// <summary>
/// Sends a modifier key up message to the browser.
/// </summary>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyUp(string theKey)
{
return this.KeyUp(null, theKey);
}
/// <summary>
/// Sends a modifier up down message to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the key command.</param>
/// <param name="theKey">The key to be sent.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
/// <exception cref="ArgumentException">If the key sent is not is not one
/// of <see cref="Keys.Shift"/>, <see cref="Keys.Control"/>, <see cref="Keys.Alt"/>,
/// <see cref="Keys.Meta"/>, <see cref="Keys.Command"/>,<see cref="Keys.LeftAlt"/>,
/// <see cref="Keys.LeftControl"/>,<see cref="Keys.LeftShift"/>.</exception>
public Actions KeyUp(IWebElement element, string theKey)
{
if (string.IsNullOrEmpty(theKey))
{
throw new ArgumentException("The key value must not be null or empty", "theKey");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new KeyUpAction(this.keyboard, this.mouse, target, theKey));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(theKey[0]));
return this;
}
/// <summary>
/// Sends a sequence of keystrokes to the browser.
/// </summary>
/// <param name="keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions SendKeys(string keysToSend)
{
return this.SendKeys(null, keysToSend);
}
/// <summary>
/// Sends a sequence of keystrokes to the specified element in the browser.
/// </summary>
/// <param name="element">The element to which to send the keystrokes.</param>
/// <param name="keysToSend">The keystrokes to send to the browser.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions SendKeys(IWebElement element, string keysToSend)
{
if (string.IsNullOrEmpty(keysToSend))
{
throw new ArgumentException("The key value must not be null or empty", "keysToSend");
}
ILocatable target = GetLocatableFromElement(element);
this.action.AddAction(new SendKeysAction(this.keyboard, this.mouse, target, keysToSend));
if (element != null)
{
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(element, 0, 0, DefaultMouseMoveDuration));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
}
foreach (char key in keysToSend)
{
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyDown(key));
this.actionBuilder.AddAction(this.defaultKeyboard.CreateKeyUp(key));
}
return this;
}
/// <summary>
/// Clicks and holds the mouse button down on the specified element.
/// </summary>
/// <param name="onElement">The element on which to click and hold.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ClickAndHold(IWebElement onElement)
{
this.MoveToElement(onElement).ClickAndHold();
return this;
}
/// <summary>
/// Clicks and holds the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ClickAndHold()
{
this.action.AddAction(new ClickAndHoldAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
return this;
}
/// <summary>
/// Releases the mouse button on the specified element.
/// </summary>
/// <param name="onElement">The element on which to release the button.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Release(IWebElement onElement)
{
this.MoveToElement(onElement).Release();
return this;
}
/// <summary>
/// Releases the mouse button at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Release()
{
this.action.AddAction(new ButtonReleaseAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Click(IWebElement onElement)
{
this.MoveToElement(onElement).Click();
return this;
}
/// <summary>
/// Clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions Click()
{
this.action.AddAction(new ClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Double-clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to double-click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DoubleClick(IWebElement onElement)
{
this.MoveToElement(onElement).DoubleClick();
return this;
}
/// <summary>
/// Double-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DoubleClick()
{
this.action.AddAction(new DoubleClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Left));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Left));
return this;
}
/// <summary>
/// Moves the mouse to the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement)
{
if (toElement == null)
{
throw new ArgumentException("MoveToElement cannot move to a null element with no offset.", "toElement");
}
ILocatable target = GetLocatableFromElement(toElement);
this.action.AddAction(new MoveMouseAction(this.mouse, target));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, 0, 0, DefaultMouseMoveDuration));
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the top-left corner of the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY)
{
return this.MoveToElement(toElement, offsetX, offsetY, MoveToElementOffsetOrigin.TopLeft);
}
/// <summary>
/// Moves the mouse to the specified offset of the top-left corner of the specified element.
/// </summary>
/// <param name="toElement">The element to which to move the mouse.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveToElement(IWebElement toElement, int offsetX, int offsetY, MoveToElementOffsetOrigin offsetOrigin)
{
ILocatable target = GetLocatableFromElement(toElement);
Size elementSize = toElement.Size;
Point elementLocation = toElement.Location;
if (offsetOrigin == MoveToElementOffsetOrigin.TopLeft)
{
int modifiedOffsetX = offsetX - (elementSize.Width / 2);
int modifiedOffsetY = offsetY - (elementSize.Height / 2);
this.action.AddAction(new MoveToOffsetAction(this.mouse, target, offsetX, offsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, modifiedOffsetX, modifiedOffsetY, DefaultMouseMoveDuration));
}
else
{
int modifiedOffsetX = offsetX + (elementSize.Width / 2);
int modifiedOffsetY = offsetY + (elementSize.Height / 2);
this.action.AddAction(new MoveToOffsetAction(this.mouse, target, modifiedOffsetX, modifiedOffsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(toElement, offsetX, offsetY, DefaultMouseMoveDuration));
}
return this;
}
/// <summary>
/// Moves the mouse to the specified offset of the last known mouse coordinates.
/// </summary>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions MoveByOffset(int offsetX, int offsetY)
{
this.action.AddAction(new MoveToOffsetAction(this.mouse, null, offsetX, offsetY));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerMove(CoordinateOrigin.Pointer, offsetX, offsetY, DefaultMouseMoveDuration));
return this;
}
/// <summary>
/// Right-clicks the mouse on the specified element.
/// </summary>
/// <param name="onElement">The element on which to right-click.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ContextClick(IWebElement onElement)
{
this.MoveToElement(onElement).ContextClick();
return this;
}
/// <summary>
/// Right-clicks the mouse at the last known mouse coordinates.
/// </summary>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions ContextClick()
{
this.action.AddAction(new ContextClickAction(this.mouse, null));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerDown(MouseButton.Right));
this.actionBuilder.AddAction(this.defaultMouse.CreatePointerUp(MouseButton.Right));
return this;
}
/// <summary>
/// Performs a drag-and-drop operation from one element to another.
/// </summary>
/// <param name="source">The element on which the drag operation is started.</param>
/// <param name="target">The element on which the drop is performed.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DragAndDrop(IWebElement source, IWebElement target)
{
this.ClickAndHold(source).MoveToElement(target).Release(target);
return this;
}
/// <summary>
/// Performs a drag-and-drop operation on one element to a specified offset.
/// </summary>
/// <param name="source">The element on which the drag operation is started.</param>
/// <param name="offsetX">The horizontal offset to which to move the mouse.</param>
/// <param name="offsetY">The vertical offset to which to move the mouse.</param>
/// <returns>A self-reference to this <see cref="Actions"/>.</returns>
public Actions DragAndDropToOffset(IWebElement source, int offsetX, int offsetY)
{
this.ClickAndHold(source).MoveByOffset(offsetX, offsetY).Release();
return this;
}
/// <summary>
/// Builds the sequence of actions.
/// </summary>
/// <returns>A composite <see cref="IAction"/> which can be used to perform the actions.</returns>
public IAction Build()
{
return this;
}
/// <summary>
/// Performs the currently built action.
/// </summary>
public void Perform()
{
if (this.actionExecutor.IsActionExecutor)
{
this.actionExecutor.PerformActions(this.actionBuilder.ToActionSequenceList());
}
else
{
this.action.Perform();
}
}
/// <summary>
/// Gets the <see cref="ILocatable"/> instance of the specified <see cref="IWebElement"/>.
/// </summary>
/// <param name="element">The <see cref="IWebElement"/> to get the location of.</param>
/// <returns>The <see cref="ILocatable"/> of the <see cref="IWebElement"/>.</returns>
protected static ILocatable GetLocatableFromElement(IWebElement element)
{
if (element == null)
{
return null;
}
ILocatable target = element as ILocatable;
if (target == null)
{
IWrapsElement wrapper = element as IWrapsElement;
while (wrapper != null)
{
target = wrapper.WrappedElement as ILocatable;
if (target != null)
{
break;
}
wrapper = wrapper.WrappedElement as IWrapsElement;
}
}
if (target == null)
{
throw new ArgumentException("The IWebElement object must implement or wrap an element that implements ILocatable.", "element");
}
return target;
}
/// <summary>
/// Adds an action to current list of actions to be performed.
/// </summary>
/// <param name="actionToAdd">The <see cref="IAction"/> to be added.</param>
protected void AddAction(IAction actionToAdd)
{
this.action.AddAction(actionToAdd);
}
private T GetDriverAs<T>(IWebDriver driver) where T : class
{
T driverAsType = driver as T;
if (driverAsType == null)
{
IWrapsDriver wrapper = driver as IWrapsDriver;
while (wrapper != null)
{
driverAsType = wrapper.WrappedDriver as T;
if (driverAsType != null)
{
driver = wrapper.WrappedDriver;
break;
}
wrapper = wrapper.WrappedDriver as IWrapsDriver;
}
}
return driverAsType;
}
}
}
| |
using System;
using System.Collections.Generic;
using UnityEngine;
using DarkMultiPlayerCommon;
using MessageStream2;
namespace DarkMultiPlayer
{
public class ChatWorker
{
private static ChatWorker singleton;
public bool display = false;
public bool workerEnabled = false;
private bool isWindowLocked = false;
private bool safeDisplay = false;
private bool initialized = false;
//State tracking
private Queue<string> disconnectingPlayers = new Queue<string>();
private Queue<JoinLeaveMessage> newJoinMessages = new Queue<JoinLeaveMessage>();
private Queue<JoinLeaveMessage> newLeaveMessages = new Queue<JoinLeaveMessage>();
private Queue<ChannelEntry> newChannelMessages = new Queue<ChannelEntry>();
private Queue<PrivateEntry> newPrivateMessages = new Queue<PrivateEntry>();
private Queue<ConsoleEntry> newConsoleMessages = new Queue<ConsoleEntry>();
private Dictionary<string, List<string>> channelMessages = new Dictionary<string, List<string>>();
private Dictionary<string, List<string>> privateMessages = new Dictionary<string, List<string>>();
private List<string> consoleMessages = new List<string>();
private Dictionary<string, List<string>> playerChannels = new Dictionary<string, List<string>>();
private List<string> joinedChannels = new List<string>();
private List<string> joinedPMChannels = new List<string>();
private List<string> highlightChannel = new List<string>();
private List<string> highlightPM = new List<string>();
public bool chatButtonHighlighted = false;
private string selectedChannel = null;
private string selectedPMChannel = null;
private bool chatLocked = false;
private bool ignoreChatInput = false;
private bool selectTextBox = false;
private string sendText = "";
public string consoleIdentifier = "";
//chat command register
private Dictionary<string, ChatCommand> registeredChatCommands = new Dictionary<string, ChatCommand>();
//event handling
private bool leaveEventHandled = true;
private bool sendEventHandled = true;
//GUILayout stuff
private Rect windowRect;
private Rect moveRect;
private GUILayoutOption[] windowLayoutOptions;
private GUILayoutOption[] smallSizeOption;
private GUIStyle windowStyle;
private GUIStyle labelStyle;
private GUIStyle buttonStyle;
private GUIStyle highlightStyle;
private GUIStyle textAreaStyle;
private GUIStyle scrollStyle;
private Vector2 chatScrollPos;
private Vector2 playerScrollPos;
//window size
private float WINDOW_HEIGHT = 300;
private float WINDOW_WIDTH = 400;
//const
private const string DMP_CHAT_LOCK = "DMP_ChatLock";
private const string DMP_CHAT_WINDOW_LOCK = "DMP_Chat_Window_Lock";
public const ControlTypes BLOCK_ALL_CONTROLS = ControlTypes.ALL_SHIP_CONTROLS | ControlTypes.ACTIONS_ALL | ControlTypes.EVA_INPUT | ControlTypes.TIMEWARP | ControlTypes.MISC | ControlTypes.GROUPS_ALL | ControlTypes.CUSTOM_ACTION_GROUPS;
public static ChatWorker fetch
{
get
{
return singleton;
}
}
public ChatWorker()
{
RegisterChatCommand("help", DisplayHelp, "Displays this help");
RegisterChatCommand("join", JoinChannel, "Joins a new chat channel");
RegisterChatCommand("query", StartQuery, "Starts a query");
RegisterChatCommand("leave", LeaveChannel, "Leaves the current channel");
RegisterChatCommand("part", LeaveChannel, "Leaves the current channel");
RegisterChatCommand("ping", ServerPing, "Pings the server");
RegisterChatCommand("motd", ServerMOTD, "Gets the current Message of the Day");
RegisterChatCommand("resize", ResizeChat, "Resized the chat window");
RegisterChatCommand("version", DisplayVersion, "Displays the current version of DMP");
}
private void PrintToSelectedChannel(string text)
{
if (selectedChannel == null && selectedPMChannel == null)
{
QueueChannelMessage(Settings.fetch.playerName, "", text);
}
if (selectedChannel != null && selectedChannel != consoleIdentifier)
{
QueueChannelMessage(Settings.fetch.playerName, selectedChannel, text);
}
if (selectedChannel == consoleIdentifier)
{
QueueSystemMessage(text);
}
if (selectedPMChannel != null)
{
QueuePrivateMessage(Settings.fetch.playerName, selectedPMChannel, text);
}
}
private void DisplayHelp(string commandArgs)
{
List<ChatCommand> commands = new List<ChatCommand>();
int longestName = 0;
foreach (ChatCommand cmd in registeredChatCommands.Values)
{
commands.Add(cmd);
if (cmd.name.Length > longestName)
{
longestName = cmd.name.Length;
}
}
commands.Sort();
foreach (ChatCommand cmd in commands)
{
string helpText = cmd.name.PadRight(longestName) + " - " + cmd.description;
PrintToSelectedChannel(helpText);
}
}
private void DisplayVersion(string commandArgs)
{
string versionMessage = (Common.PROGRAM_VERSION.Length == 40) ? "DarkMultiPlayer development build " + Common.PROGRAM_VERSION.Substring(0, 7) : "DarkMultiPlayer " + Common.PROGRAM_VERSION;
PrintToSelectedChannel(versionMessage);
}
private void JoinChannel(string commandArgs)
{
if (commandArgs != "" && commandArgs != "Global" && commandArgs != consoleIdentifier && commandArgs != "#Global" && commandArgs != "#" + consoleIdentifier)
{
if (commandArgs.StartsWith("#"))
{
commandArgs = commandArgs.Substring(1);
}
if (!joinedChannels.Contains(commandArgs))
{
DarkLog.Debug("Joining channel " + commandArgs);
joinedChannels.Add(commandArgs);
selectedChannel = commandArgs;
selectedPMChannel = null;
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.JOIN);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string>(commandArgs);
NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes());
}
}
}
else
{
ScreenMessages.PostScreenMessage("Couldn't join '" + commandArgs + "', channel name not valid!");
}
}
private void LeaveChannel(string commandArgs)
{
leaveEventHandled = false;
}
private void StartQuery(string commandArgs)
{
bool playerFound = false;
if (commandArgs != consoleIdentifier)
{
foreach (PlayerStatus ps in PlayerStatusWorker.fetch.playerStatusList)
{
if (ps.playerName == commandArgs)
{
playerFound = true;
}
}
}
else
{
//Make sure we can always query the server.
playerFound = true;
}
if (playerFound)
{
if (!joinedPMChannels.Contains(commandArgs))
{
DarkLog.Debug("Starting query with " + commandArgs);
joinedPMChannels.Add(commandArgs);
selectedChannel = null;
selectedPMChannel = commandArgs;
}
}
else
{
ScreenMessages.PostScreenMessage("Couldn't start query with '" + commandArgs + "', player not found!");
}
}
private void ServerPing(string commandArgs)
{
NetworkWorker.fetch.SendPingRequest();
}
private void ServerMOTD(string commandArgs)
{
NetworkWorker.fetch.SendMotdRequest();
}
private void ResizeChat(string commandArgs)
{
string func = "";
float size = 0;
func = commandArgs;
if (commandArgs.Contains(" "))
{
func = commandArgs.Substring(0, commandArgs.IndexOf(" "));
if (commandArgs.Substring(func.Length).Contains(" "))
{
try
{
size = Convert.ToSingle(commandArgs.Substring(func.Length + 1));
}
catch (FormatException)
{
PrintToSelectedChannel("Error: " + size + " is not a valid number");
size = 400f;
}
}
}
switch (func)
{
default:
PrintToSelectedChannel("Undefined function. Usage: /resize [default|medium|large], /resize [x|y] size, or /resize show");
PrintToSelectedChannel("Chat window size is currently: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "x":
if (size <= 800 && size >= 300)
{
WINDOW_WIDTH = size;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
}
else
{
PrintToSelectedChannel("Size is out of range.");
}
break;
case "y":
if (size <= 800 && size >= 300)
{
WINDOW_HEIGHT = size;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
}
else
{
PrintToSelectedChannel("Size is out of range.");
}
break;
case "default":
WINDOW_HEIGHT = 300;
WINDOW_WIDTH = 400;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "medium":
WINDOW_HEIGHT = 600;
WINDOW_WIDTH = 600;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "large":
WINDOW_HEIGHT = 800;
WINDOW_WIDTH = 800;
initialized = false;
PrintToSelectedChannel("New window size is: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
case "show":
PrintToSelectedChannel("Chat window size is currently: " + WINDOW_WIDTH + "x" + WINDOW_HEIGHT);
break;
}
}
private void InitGUI()
{
//Setup GUI stuff
windowRect = new Rect(Screen.width / 10, Screen.height / 2f - WINDOW_HEIGHT / 2f, WINDOW_WIDTH, WINDOW_HEIGHT);
moveRect = new Rect(0, 0, 10000, 20);
windowLayoutOptions = new GUILayoutOption[4];
windowLayoutOptions[0] = GUILayout.MinWidth(WINDOW_WIDTH);
windowLayoutOptions[1] = GUILayout.MaxWidth(WINDOW_WIDTH);
windowLayoutOptions[2] = GUILayout.MinHeight(WINDOW_HEIGHT);
windowLayoutOptions[3] = GUILayout.MaxHeight(WINDOW_HEIGHT);
smallSizeOption = new GUILayoutOption[1];
smallSizeOption[0] = GUILayout.Width(WINDOW_WIDTH * .25f);
windowStyle = new GUIStyle(GUI.skin.window);
scrollStyle = new GUIStyle(GUI.skin.scrollView);
chatScrollPos = new Vector2(0, 0);
labelStyle = new GUIStyle(GUI.skin.label);
buttonStyle = new GUIStyle(GUI.skin.button);
highlightStyle = new GUIStyle(GUI.skin.button);
highlightStyle.normal.textColor = Color.red;
highlightStyle.active.textColor = Color.red;
highlightStyle.hover.textColor = Color.red;
textAreaStyle = new GUIStyle(GUI.skin.textArea);
}
public void QueueChatJoin(string playerName, string channelName)
{
JoinLeaveMessage jlm = new JoinLeaveMessage();
jlm.fromPlayer = playerName;
jlm.channel = channelName;
newJoinMessages.Enqueue(jlm);
}
public void QueueChatLeave(string playerName, string channelName)
{
JoinLeaveMessage jlm = new JoinLeaveMessage();
jlm.fromPlayer = playerName;
jlm.channel = channelName;
newLeaveMessages.Enqueue(jlm);
}
public void QueueChannelMessage(string fromPlayer, string channelName, string channelMessage)
{
ChannelEntry ce = new ChannelEntry();
ce.fromPlayer = fromPlayer;
ce.channel = channelName;
ce.message = channelMessage;
newChannelMessages.Enqueue(ce);
if (!display)
{
chatButtonHighlighted = true;
if (ce.channel != "")
{
ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #" + ce.channel + ": " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT);
}
else
{
ScreenMessages.PostScreenMessage(ce.fromPlayer + " -> #Global : " + ce.message, 5f, ScreenMessageStyle.UPPER_LEFT);
}
}
}
public void QueuePrivateMessage(string fromPlayer, string toPlayer, string privateMessage)
{
PrivateEntry pe = new PrivateEntry();
pe.fromPlayer = fromPlayer;
pe.toPlayer = toPlayer;
pe.message = privateMessage;
newPrivateMessages.Enqueue(pe);
if (!display)
{
chatButtonHighlighted = true;
if (pe.fromPlayer != Settings.fetch.playerName)
{
ScreenMessages.PostScreenMessage(pe.fromPlayer + " -> @" + pe.toPlayer + ": " + pe.message, 5f, ScreenMessageStyle.UPPER_LEFT);
}
}
}
public void QueueRemovePlayer(string playerName)
{
disconnectingPlayers.Enqueue(playerName);
}
public void PMMessageServer(string message)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.PRIVATE_MESSAGE);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string>(consoleIdentifier);
mw.Write<string>(message);
NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes());
}
}
public void QueueSystemMessage(string message)
{
ConsoleEntry ce = new ConsoleEntry();
ce.message = message;
newConsoleMessages.Enqueue(ce);
}
public void RegisterChatCommand(string command, Action<string> func, string description)
{
ChatCommand cmd = new ChatCommand(command, func, description);
if (!registeredChatCommands.ContainsKey(command))
{
registeredChatCommands.Add(command, cmd);
}
}
public void HandleChatInput(string input)
{
if (!input.StartsWith("/") || input.StartsWith("//"))
{
//Handle chat messages
if (input.StartsWith("//"))
{
input = input.Substring(1);
}
if (selectedChannel == null && selectedPMChannel == null)
{
//Sending a global chat message
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.CHANNEL_MESSAGE);
mw.Write<string>(Settings.fetch.playerName);
//Global channel name is empty string.
mw.Write<string>("");
mw.Write<string>(input);
NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes());
}
}
if (selectedChannel != null && selectedChannel != consoleIdentifier)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.CHANNEL_MESSAGE);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string>(selectedChannel);
mw.Write<string>(input);
NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes());
}
}
if (selectedChannel == consoleIdentifier)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.CONSOLE_MESSAGE);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string>(input);
NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes());
DarkLog.Debug("Server Command: " + input);
}
}
if (selectedPMChannel != null)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.PRIVATE_MESSAGE);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string>(selectedPMChannel);
mw.Write<string>(input);
NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes());
}
}
}
else
{
string commandPart = input.Substring(1);
string argumentPart = "";
if (commandPart.Contains(" "))
{
if (commandPart.Length > commandPart.IndexOf(' ') + 1)
{
argumentPart = commandPart.Substring(commandPart.IndexOf(' ') + 1);
}
commandPart = commandPart.Substring(0, commandPart.IndexOf(' '));
}
if (commandPart.Length > 0)
{
if (registeredChatCommands.ContainsKey(commandPart))
{
try
{
DarkLog.Debug("Chat Command: " + input.Substring(1));
registeredChatCommands[commandPart].func(argumentPart);
}
catch (Exception e)
{
DarkLog.Debug("Error handling chat command " + commandPart + ", Exception " + e);
PrintToSelectedChannel("Error handling chat command: " + commandPart);
}
}
else
{
PrintToSelectedChannel("Unknown chat command: " + commandPart);
}
}
}
}
private void HandleChatEvents()
{
//Handle leave event
if (!leaveEventHandled)
{
if (selectedChannel != null && selectedChannel != consoleIdentifier)
{
using (MessageWriter mw = new MessageWriter())
{
mw.Write<int>((int)ChatMessageType.LEAVE);
mw.Write<string>(Settings.fetch.playerName);
mw.Write<string>(selectedChannel);
NetworkWorker.fetch.SendChatMessage(mw.GetMessageBytes());
}
if (joinedChannels.Contains(selectedChannel))
{
joinedChannels.Remove(selectedChannel);
}
selectedChannel = null;
selectedPMChannel = null;
}
if (selectedPMChannel != null)
{
if (joinedPMChannels.Contains(selectedPMChannel))
{
joinedPMChannels.Remove(selectedPMChannel);
}
selectedChannel = null;
selectedPMChannel = null;
}
leaveEventHandled = true;
}
//Handle send event
if (!sendEventHandled)
{
if (sendText != "")
{
HandleChatInput(sendText);
}
sendText = "";
sendEventHandled = true;
}
//Handle join messages
while (newJoinMessages.Count > 0)
{
JoinLeaveMessage jlm = newJoinMessages.Dequeue();
if (!playerChannels.ContainsKey(jlm.fromPlayer))
{
playerChannels.Add(jlm.fromPlayer, new List<string>());
}
if (!playerChannels[jlm.fromPlayer].Contains(jlm.channel))
{
playerChannels[jlm.fromPlayer].Add(jlm.channel);
}
}
//Handle leave messages
while (newLeaveMessages.Count > 0)
{
JoinLeaveMessage jlm = newLeaveMessages.Dequeue();
if (playerChannels.ContainsKey(jlm.fromPlayer))
{
if (playerChannels[jlm.fromPlayer].Contains(jlm.channel))
{
playerChannels[jlm.fromPlayer].Remove(jlm.channel);
}
if (playerChannels[jlm.fromPlayer].Count == 0)
{
playerChannels.Remove(jlm.fromPlayer);
}
}
}
//Handle channel messages
while (newChannelMessages.Count > 0)
{
ChannelEntry ce = newChannelMessages.Dequeue();
if (!channelMessages.ContainsKey(ce.channel))
{
channelMessages.Add(ce.channel, new List<string>());
}
//Highlight if the channel isn't selected.
if (selectedChannel != null && ce.channel == "")
{
if (!highlightChannel.Contains(ce.channel))
{
highlightChannel.Add(ce.channel);
}
}
if (ce.channel != selectedChannel && ce.channel != "")
{
if (!highlightChannel.Contains(ce.channel))
{
highlightChannel.Add(ce.channel);
}
}
//Move the bar to the bottom on a new message
if (selectedChannel == null && selectedPMChannel == null && ce.channel == "")
{
chatScrollPos.y = float.PositiveInfinity;
}
if (selectedChannel != null && selectedPMChannel == null && ce.channel == selectedChannel)
{
chatScrollPos.y = float.PositiveInfinity;
}
channelMessages[ce.channel].Add(ce.fromPlayer + ": " + ce.message);
}
//Handle private messages
while (newPrivateMessages.Count > 0)
{
PrivateEntry pe = newPrivateMessages.Dequeue();
if (pe.fromPlayer != Settings.fetch.playerName)
{
if (!privateMessages.ContainsKey(pe.fromPlayer))
{
privateMessages.Add(pe.fromPlayer, new List<string>());
}
//Highlight if the player isn't selected
if (!joinedPMChannels.Contains(pe.fromPlayer))
{
joinedPMChannels.Add(pe.fromPlayer);
}
if (selectedPMChannel != pe.fromPlayer)
{
if (!highlightPM.Contains(pe.fromPlayer))
{
highlightPM.Add(pe.fromPlayer);
}
}
}
if (!privateMessages.ContainsKey(pe.toPlayer))
{
privateMessages.Add(pe.toPlayer, new List<string>());
}
//Move the bar to the bottom on a new message
if (selectedPMChannel != null && selectedChannel == null && (pe.fromPlayer == selectedPMChannel || pe.fromPlayer == Settings.fetch.playerName))
{
chatScrollPos.y = float.PositiveInfinity;
}
if (pe.fromPlayer != Settings.fetch.playerName)
{
privateMessages[pe.fromPlayer].Add(pe.fromPlayer + ": " + pe.message);
}
else
{
privateMessages[pe.toPlayer].Add(pe.fromPlayer + ": " + pe.message);
}
}
//Handle console messages
while (newConsoleMessages.Count > 0)
{
ConsoleEntry ce = newConsoleMessages.Dequeue();
//Highlight if the channel isn't selected.
if (selectedChannel != consoleIdentifier)
{
if (!highlightChannel.Contains(consoleIdentifier))
{
highlightChannel.Add(consoleIdentifier);
}
}
//Move the bar to the bottom on a new message
if (selectedChannel == null && selectedPMChannel == null && consoleIdentifier == "")
{
chatScrollPos.y = float.PositiveInfinity;
}
if (selectedChannel != null && selectedPMChannel == null && consoleIdentifier == selectedChannel)
{
chatScrollPos.y = float.PositiveInfinity;
}
consoleMessages.Add(ce.message);
}
while (disconnectingPlayers.Count > 0)
{
string disconnectingPlayer = disconnectingPlayers.Dequeue();
if (playerChannels.ContainsKey(disconnectingPlayer))
{
playerChannels.Remove(disconnectingPlayer);
}
if (joinedPMChannels.Contains(disconnectingPlayer))
{
joinedPMChannels.Remove(disconnectingPlayer);
}
if (highlightPM.Contains(disconnectingPlayer))
{
highlightPM.Remove(disconnectingPlayer);
}
if (privateMessages.ContainsKey(disconnectingPlayer))
{
privateMessages.Remove(disconnectingPlayer);
}
}
}
private void Update()
{
safeDisplay = display;
ignoreChatInput = false;
if (chatButtonHighlighted && display)
{
chatButtonHighlighted = false;
}
if (chatLocked && !display)
{
chatLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_LOCK);
}
if (workerEnabled)
{
HandleChatEvents();
}
}
public void Draw()
{
if (!initialized)
{
InitGUI();
initialized = true;
}
if (safeDisplay)
{
bool pressedChatShortcutKey = (Event.current.type == EventType.KeyDown && Event.current.keyCode == Settings.fetch.chatKey);
if (pressedChatShortcutKey)
{
ignoreChatInput = true;
selectTextBox = true;
}
windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6704 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer Chat", windowStyle, windowLayoutOptions));
}
CheckWindowLock();
}
private void DrawContent(int windowID)
{
bool pressedEnter = (Event.current.type == EventType.KeyDown && !Event.current.shift && Event.current.character == '\n');
GUILayout.BeginVertical();
GUI.DragWindow(moveRect);
GUILayout.BeginHorizontal();
DrawRooms();
GUILayout.FlexibleSpace();
if (selectedChannel != null && selectedChannel != consoleIdentifier || selectedPMChannel != null)
{
if (GUILayout.Button("Leave", buttonStyle))
{
leaveEventHandled = false;
}
}
DrawConsole();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
chatScrollPos = GUILayout.BeginScrollView(chatScrollPos, scrollStyle);
if (selectedChannel == null && selectedPMChannel == null)
{
if (!channelMessages.ContainsKey(""))
{
channelMessages.Add("", new List<string>());
}
foreach (string channelMessage in channelMessages[""])
{
GUILayout.Label(channelMessage, labelStyle);
}
}
if (selectedChannel != null && selectedChannel != consoleIdentifier)
{
if (!channelMessages.ContainsKey(selectedChannel))
{
channelMessages.Add(selectedChannel, new List<string>());
}
foreach (string channelMessage in channelMessages[selectedChannel])
{
GUILayout.Label(channelMessage, labelStyle);
}
}
if (selectedChannel == consoleIdentifier)
{
foreach (string consoleMessage in consoleMessages)
{
GUILayout.Label(consoleMessage, labelStyle);
}
}
if (selectedPMChannel != null)
{
if (!privateMessages.ContainsKey(selectedPMChannel))
{
privateMessages.Add(selectedPMChannel, new List<string>());
}
foreach (string privateMessage in privateMessages[selectedPMChannel])
{
GUILayout.Label(privateMessage, labelStyle);
}
}
GUILayout.EndScrollView();
playerScrollPos = GUILayout.BeginScrollView(playerScrollPos, scrollStyle, smallSizeOption);
GUILayout.BeginVertical();
GUILayout.Label(Settings.fetch.playerName, labelStyle);
if (selectedPMChannel != null)
{
GUILayout.Label(selectedPMChannel, labelStyle);
}
else
{
if (selectedChannel == null)
{
//Global chat
foreach (PlayerStatus player in PlayerStatusWorker.fetch.playerStatusList)
{
if (joinedPMChannels.Contains(player.playerName))
{
GUI.enabled = false;
}
if (GUILayout.Button(player.playerName, labelStyle))
{
if (!joinedPMChannels.Contains(player.playerName))
{
joinedPMChannels.Add(player.playerName);
}
}
GUI.enabled = true;
}
}
else
{
foreach (KeyValuePair<string, List<string>> playerEntry in playerChannels)
{
if (playerEntry.Key != Settings.fetch.playerName)
{
if (playerEntry.Value.Contains(selectedChannel))
{
if (joinedPMChannels.Contains(playerEntry.Key))
{
GUI.enabled = false;
}
if (GUILayout.Button(playerEntry.Key, labelStyle))
{
if (!joinedPMChannels.Contains(playerEntry.Key))
{
joinedPMChannels.Add(playerEntry.Key);
}
}
GUI.enabled = true;
}
}
}
}
}
GUILayout.EndVertical();
GUILayout.EndScrollView();
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUI.SetNextControlName("SendTextArea");
string tempSendText = GUILayout.TextArea(sendText, textAreaStyle);
//Don't add the newline to the messages, queue a send
if (!ignoreChatInput)
{
if (pressedEnter)
{
sendEventHandled = false;
}
else
{
sendText = tempSendText;
}
}
if (sendText == "")
{
GUI.enabled = false;
}
if (GUILayout.Button("Send", buttonStyle, smallSizeOption))
{
sendEventHandled = false;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
GUILayout.EndVertical();
if ((GUI.GetNameOfFocusedControl() == "SendTextArea") && !chatLocked)
{
chatLocked = true;
InputLockManager.SetControlLock(BLOCK_ALL_CONTROLS, DMP_CHAT_LOCK);
}
if ((GUI.GetNameOfFocusedControl() != "SendTextArea") && chatLocked)
{
chatLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_LOCK);
}
if (selectTextBox)
{
selectTextBox = false;
GUI.FocusControl("SendTextArea");
}
}
private void DrawConsole()
{
GUIStyle possibleHighlightButtonStyle = buttonStyle;
if (selectedChannel == consoleIdentifier)
{
GUI.enabled = false;
}
if (highlightChannel.Contains(consoleIdentifier))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (AdminSystem.fetch.IsAdmin(Settings.fetch.playerName))
{
if (GUILayout.Button("#" + consoleIdentifier, possibleHighlightButtonStyle))
{
if (highlightChannel.Contains(consoleIdentifier))
{
highlightChannel.Remove(consoleIdentifier);
}
selectedChannel = consoleIdentifier;
selectedPMChannel = null;
chatScrollPos.y = float.PositiveInfinity;
}
}
GUI.enabled = true;
}
private void DrawRooms()
{
GUIStyle possibleHighlightButtonStyle = buttonStyle;
if (selectedChannel == null && selectedPMChannel == null)
{
GUI.enabled = false;
}
if (highlightChannel.Contains(""))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (GUILayout.Button("#Global", possibleHighlightButtonStyle))
{
if (highlightChannel.Contains(""))
{
highlightChannel.Remove("");
}
selectedChannel = null;
selectedPMChannel = null;
chatScrollPos.y = float.PositiveInfinity;
}
GUI.enabled = true;
foreach (string joinedChannel in joinedChannels)
{
if (highlightChannel.Contains(joinedChannel))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (selectedChannel == joinedChannel)
{
GUI.enabled = false;
}
if (GUILayout.Button("#" + joinedChannel, possibleHighlightButtonStyle))
{
if (highlightChannel.Contains(joinedChannel))
{
highlightChannel.Remove(joinedChannel);
}
selectedChannel = joinedChannel;
selectedPMChannel = null;
chatScrollPos.y = float.PositiveInfinity;
}
GUI.enabled = true;
}
foreach (string joinedPlayer in joinedPMChannels)
{
if (highlightPM.Contains(joinedPlayer))
{
possibleHighlightButtonStyle = highlightStyle;
}
else
{
possibleHighlightButtonStyle = buttonStyle;
}
if (selectedPMChannel == joinedPlayer)
{
GUI.enabled = false;
}
if (GUILayout.Button("@" + joinedPlayer, possibleHighlightButtonStyle))
{
if (highlightPM.Contains(joinedPlayer))
{
highlightPM.Remove(joinedPlayer);
}
selectedChannel = null;
selectedPMChannel = joinedPlayer;
chatScrollPos.y = float.PositiveInfinity;
}
GUI.enabled = true;
}
}
public static void Reset()
{
lock (Client.eventLock)
{
if (singleton != null)
{
singleton.workerEnabled = false;
singleton.RemoveWindowLock();
Client.updateEvent.Remove(singleton.Update);
Client.drawEvent.Remove(singleton.Draw);
if (singleton.chatLocked)
{
singleton.chatLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_LOCK);
}
}
singleton = new ChatWorker();
Client.updateEvent.Add(singleton.Update);
Client.drawEvent.Add(singleton.Draw);
}
}
private void CheckWindowLock()
{
if (!Client.fetch.gameRunning)
{
RemoveWindowLock();
return;
}
if (HighLogic.LoadedSceneIsFlight)
{
RemoveWindowLock();
return;
}
if (safeDisplay)
{
Vector2 mousePos = Input.mousePosition;
mousePos.y = Screen.height - mousePos.y;
bool shouldLock = windowRect.Contains(mousePos);
if (shouldLock && !isWindowLocked)
{
InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, DMP_CHAT_WINDOW_LOCK);
isWindowLocked = true;
}
if (!shouldLock && isWindowLocked)
{
RemoveWindowLock();
}
}
if (!safeDisplay && isWindowLocked)
{
RemoveWindowLock();
}
}
private void RemoveWindowLock()
{
if (isWindowLocked)
{
isWindowLocked = false;
InputLockManager.RemoveControlLock(DMP_CHAT_WINDOW_LOCK);
}
}
private class ChatCommand : IComparable
{
public string name;
public Action<string> func;
public string description;
public ChatCommand(string name, Action<string> func, string description)
{
this.name = name;
this.func = func;
this.description = description;
}
public int CompareTo(object obj)
{
var cmd = obj as ChatCommand;
return this.name.CompareTo(cmd.name);
}
}
}
public class ChannelEntry
{
public string fromPlayer;
public string channel;
public string message;
}
public class PrivateEntry
{
public string fromPlayer;
public string toPlayer;
public string message;
}
public class JoinLeaveMessage
{
public string fromPlayer;
public string channel;
}
public class ConsoleEntry
{
public string message;
}
}
| |
// 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.Text;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
public class DebugNameFormatter : TypeNameFormatter<DebugNameFormatter.Void, DebugNameFormatter.FormatOptions>
{
public static readonly DebugNameFormatter Instance = new DebugNameFormatter();
public override Void AppendName(StringBuilder sb, ArrayType type, FormatOptions options)
{
AppendName(sb, type.ElementType, options);
if (!type.IsSzArray && type.Rank == 1)
{
sb.Append("[*]");
}
else
{
sb.Append('[');
sb.Append(',', type.Rank - 1);
sb.Append(']');
}
return Void.Value;
}
public override Void AppendName(StringBuilder sb, ByRefType type, FormatOptions options)
{
AppendName(sb, type.ParameterType, options);
sb.Append('&');
return Void.Value;
}
public override Void AppendName(StringBuilder sb, PointerType type, FormatOptions options)
{
AppendName(sb, type.ParameterType, options);
sb.Append('*');
return Void.Value;
}
public override Void AppendName(StringBuilder sb, FunctionPointerType type, FormatOptions options)
{
MethodSignature signature = type.Signature;
sb.Append("(*");
AppendName(sb, signature.ReturnType, options);
sb.Append(")(");
for (int i = 0; i < signature.Length; i++)
{
if (i > 0)
sb.Append(',');
AppendName(sb, signature[i], options);
}
sb.Append(')');
return Void.Value;
}
public override Void AppendName(StringBuilder sb, GenericParameterDesc type, FormatOptions options)
{
sb.Append(type.Name);
return Void.Value;
}
public override Void AppendName(StringBuilder sb, SignatureMethodVariable type, FormatOptions options)
{
sb.Append("!!");
sb.Append(type.Index.ToStringInvariant());
return Void.Value;
}
public override Void AppendName(StringBuilder sb, SignatureTypeVariable type, FormatOptions options)
{
sb.Append("!");
sb.Append(type.Index.ToStringInvariant());
return Void.Value;
}
protected override Void AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType, FormatOptions options)
{
if ((options & FormatOptions.NamespaceQualify) != 0)
{
AppendName(sb, containingType, options);
sb.Append('+');
}
sb.Append(nestedType.Name);
return Void.Value;
}
protected override Void AppendNameForNamespaceType(StringBuilder sb, DefType type, FormatOptions options)
{
// Shortcut some of the well known types
switch (type.Category)
{
case TypeFlags.Void:
sb.Append("void");
return Void.Value;
case TypeFlags.Boolean:
sb.Append("bool");
return Void.Value;
case TypeFlags.Char:
sb.Append("char");
return Void.Value;
case TypeFlags.SByte:
sb.Append("int8");
return Void.Value;
case TypeFlags.Byte:
sb.Append("uint8");
return Void.Value;
case TypeFlags.Int16:
sb.Append("int16");
return Void.Value;
case TypeFlags.UInt16:
sb.Append("uint16");
return Void.Value;
case TypeFlags.Int32:
sb.Append("int32");
return Void.Value;
case TypeFlags.UInt32:
sb.Append("uint32");
return Void.Value;
case TypeFlags.Int64:
sb.Append("int64");
return Void.Value;
case TypeFlags.UInt64:
sb.Append("uint64");
return Void.Value;
case TypeFlags.IntPtr:
sb.Append("native int");
return Void.Value;
case TypeFlags.UIntPtr:
sb.Append("native uint");
return Void.Value;
case TypeFlags.Single:
sb.Append("float32");
return Void.Value;
case TypeFlags.Double:
sb.Append("float64");
return Void.Value;
}
if (type.IsString)
{
sb.Append("string");
return Void.Value;
}
if (type.IsObject)
{
sb.Append("object");
return Void.Value;
}
if (((options & FormatOptions.AssemblyQualify) != 0)
&& type is MetadataType mdType
&& mdType.Module is IAssemblyDesc)
{
sb.Append('[');
// Trim the "System.Private." prefix
string assemblyName = ((IAssemblyDesc)mdType.Module).GetName().Name;
if (assemblyName.StartsWith("System.Private", StringComparison.Ordinal))
assemblyName = "S.P" + assemblyName.Substring(14);
sb.Append(assemblyName);
sb.Append(']');
}
if ((options & FormatOptions.NamespaceQualify) != 0)
{
string ns = type.Namespace;
if (!string.IsNullOrEmpty(ns))
{
sb.Append(ns);
sb.Append('.');
}
}
sb.Append(type.Name);
return Void.Value;
}
protected override Void AppendNameForInstantiatedType(StringBuilder sb, DefType type, FormatOptions options)
{
AppendName(sb, type.GetTypeDefinition(), options);
FormatOptions parameterOptions = options & ~FormatOptions.AssemblyQualify;
sb.Append('<');
for (int i = 0; i < type.Instantiation.Length; i++)
{
if (i != 0)
sb.Append(',');
AppendName(sb, type.Instantiation[i], parameterOptions);
}
sb.Append('>');
return Void.Value;
}
public struct Void
{
public static Void Value => default(Void);
}
[Flags]
public enum FormatOptions
{
None = 0,
AssemblyQualify = 0x1,
NamespaceQualify = 0x2,
Default = AssemblyQualify | NamespaceQualify,
}
}
}
| |
// 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.DirectoryServices
{
using System.ComponentModel;
/// <include file='doc\DirectoryVirtualListView.uex' path='docs/doc[@for="DirectoryVirtualListView"]/*' />
/// <devdoc>
/// <para>Specifies how to do directory virtual list view search.</para>
/// </devdoc>
public class DirectoryVirtualListView
{
private int _beforeCount = 0;
private int _afterCount = 0;
private int _offset = 0;
private string _target = "";
private int _approximateTotal = 0;
private int _targetPercentage = 0;
private DirectoryVirtualListViewContext _context = null;
/// <include file='doc\DirectoryVirtualListView.uex' path='docs/doc[@for="DirectoryVirtualListView.DirectoryVirtualListView"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public DirectoryVirtualListView()
{
}
/// <include file='doc\DirectoryVirtualListView.uex' path='docs/doc[@for="DirectoryVirtualListView.DirectoryVirtualListView1"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public DirectoryVirtualListView(int afterCount)
{
AfterCount = afterCount;
}
/// <include file='doc\DirectoryVirtualListView.uex' path='docs/doc[@for="DirectoryVirtualListView.DirectoryVirtualListView2"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public DirectoryVirtualListView(int beforeCount, int afterCount, int offset)
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Offset = offset;
}
/// <include file='doc\DirectoryVirtualListView.uex' path='docs/doc[@for="DirectoryVirtualListView.DirectoryVirtualListView3"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public DirectoryVirtualListView(int beforeCount, int afterCount, string target)
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Target = target;
}
/// <include file='doc\DirectoryVirtualListView.uex' path='docs/doc[@for="DirectoryVirtualListView.DirectoryVirtualListView4"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public DirectoryVirtualListView(int beforeCount, int afterCount, int offset, DirectoryVirtualListViewContext context)
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Offset = offset;
_context = context;
}
/// <include file='doc\DirectoryVirtualListView.uex' path='docs/doc[@for="DirectoryVirtualListView.DirectoryVirtualListView5"]/*' />
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public DirectoryVirtualListView(int beforeCount, int afterCount, string target, DirectoryVirtualListViewContext context)
{
BeforeCount = beforeCount;
AfterCount = afterCount;
Target = target;
_context = context;
}
/// <include file='doc\DirectoryVirtualListView..uex' path='docs/doc[@for="DirectoryVirtualListView.BeforeCount"]/*' />
/// <devdoc>
/// <para>Gets or sets a value to indicate the number of entries before the target entry that the client is requesting from the server.</para>
/// </devdoc>
[
DefaultValue(0),
]
public int BeforeCount
{
get
{
return _beforeCount;
}
set
{
if (value < 0)
throw new ArgumentException(SR.DSBadBeforeCount);
_beforeCount = value;
}
}
/// <include file='doc\DirectoryVirtualListView..uex' path='docs/doc[@for="DirectoryVirtualListView.AfterCount"]/*' />
/// <devdoc>
/// <para>Gets or sets a value to indicate the number of entries after the target entry that the client is requesting from the server</para>
/// </devdoc>
[
DefaultValue(0),
]
public int AfterCount
{
get
{
return _afterCount;
}
set
{
if (value < 0)
throw new ArgumentException(SR.DSBadAfterCount);
_afterCount = value;
}
}
/// <include file='doc\DirectoryVirtualListView..uex' path='docs/doc[@for="DirectoryVirtualListView.Offset"]/*' />
/// <devdoc>
/// <para>Gets or sets a value to indicate the estimated target entry's requested offset within the list.</para>
/// </devdoc>
[
DefaultValue(0),
]
public int Offset
{
get
{
return _offset;
}
set
{
if (value < 0)
throw new ArgumentException(SR.DSBadOffset);
_offset = value;
if (_approximateTotal != 0)
_targetPercentage = (int)((double)_offset / _approximateTotal * 100);
else
_targetPercentage = 0;
}
}
/// <include file='doc\DirectoryVirtualListView..uex' path='docs/doc[@for="DirectoryVirtualListView.AfterCount"]/*' />
/// <devdoc>
/// <para>Gets or sets a value to indicate the offset percentage</para>
/// </devdoc>
[
DefaultValue(0),
]
public int TargetPercentage
{
get
{
return _targetPercentage;
}
set
{
if (value > 100 || value < 0)
throw new ArgumentException(SR.DSBadTargetPercentage);
_targetPercentage = value;
_offset = _approximateTotal * _targetPercentage / 100;
}
}
/// <include file='doc\DirectoryVirtualListView..uex' path='docs/doc[@for="DirectoryVirtualListView.AfterCount"]/*' />
/// <devdoc>
/// <para>Gets or sets a value to indicate the desired target entry requested by the client.</para>
/// </devdoc>
[
DefaultValue(""),
// CoreFXPort - Remove design support
// TypeConverter("System.Diagnostics.Design.StringValueConverter, " + AssemblyRef.SystemDesign)
]
public string Target
{
get
{
return _target;
}
set
{
if (value == null)
value = "";
_target = value;
}
}
/// <include file='doc\DirectoryVirtualListView..uex' path='docs/doc[@for="DirectoryVirtualListView.AfterCount"]/*' />
/// <devdoc>
/// <para>Gets or sets a value to indicate the estimated total count.</para>
/// </devdoc>
[
DefaultValue(0),
]
public int ApproximateTotal
{
get
{
return _approximateTotal;
}
set
{
if (value < 0)
throw new ArgumentException(SR.DSBadApproximateTotal);
_approximateTotal = value;
}
}
/// <include file='doc\DirectoryVirtualListView..uex' path='docs/doc[@for="DirectoryVirtualListView.AfterCount"]/*' />
/// <devdoc>
/// <para>Gets or sets a value to indicate the virtual list view search response.</para>
/// </devdoc>
[
DefaultValue(null),
]
public DirectoryVirtualListViewContext DirectoryVirtualListViewContext
{
get
{
return _context;
}
set
{
_context = value;
}
}
}
}
| |
namespace System.Workflow.ComponentModel.Design
{
using System;
using System.IO;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Reflection;
using Microsoft.CSharp;
using Microsoft.VisualBasic;
using System.Collections;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.ComponentModel.Design.Serialization;
using System.Workflow;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Serialization;
using System.Collections.Specialized;
internal sealed class IdentifierCreationService : IIdentifierCreationService
{
private IServiceProvider serviceProvider = null;
private WorkflowDesignerLoader loader = null;
private CodeDomProvider provider = null;
internal IdentifierCreationService(IServiceProvider serviceProvider, WorkflowDesignerLoader loader)
{
this.serviceProvider = serviceProvider;
this.loader = loader;
}
internal CodeDomProvider Provider
{
get
{
if (this.provider == null)
{
SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(this.serviceProvider);
if (language == SupportedLanguages.CSharp)
this.provider = CompilerHelpers.CreateCodeProviderInstance(typeof(CSharpCodeProvider));
else
this.provider = CompilerHelpers.CreateCodeProviderInstance(typeof(VBCodeProvider));
}
return this.provider;
}
}
#region IIdentifierCreationService
void IIdentifierCreationService.ValidateIdentifier(Activity activity, string identifier)
{
if (identifier == null)
throw new ArgumentNullException("identifier");
if (activity == null)
throw new ArgumentNullException("activity");
if (activity.Name.ToLowerInvariant().Equals(identifier.ToLowerInvariant()))
return;
if (this.Provider != null)
{
SupportedLanguages language = CompilerHelpers.GetSupportedLanguage(this.serviceProvider);
if (language == SupportedLanguages.CSharp && identifier.StartsWith("@", StringComparison.Ordinal) ||
language == SupportedLanguages.VB && identifier.StartsWith("[", StringComparison.Ordinal) && identifier.EndsWith("]", StringComparison.Ordinal) ||
!this.Provider.IsValidIdentifier(identifier))
{
throw new Exception(SR.GetString(SR.Error_InvalidLanguageIdentifier, identifier));
}
}
StringDictionary identifiers = new StringDictionary();
CompositeActivity rootActivity = Helpers.GetRootActivity(activity) as CompositeActivity;
if (rootActivity != null)
{
foreach (string existingIdentifier in Helpers.GetIdentifiersInCompositeActivity(rootActivity))
identifiers[existingIdentifier] = existingIdentifier;
}
Type customActivityType = GetRootActivityType(this.serviceProvider);
if (customActivityType != null)
{
foreach (MemberInfo member in customActivityType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
{
Type memberType = null;
if (member is FieldInfo)
memberType = ((FieldInfo)member).FieldType;
if (memberType == null || !typeof(Activity).IsAssignableFrom(memberType))
identifiers[member.Name] = member.Name;
}
}
if (identifiers.ContainsKey(identifier))
throw new ArgumentException(SR.GetString(SR.DuplicateActivityIdentifier, identifier));
}
/// <summary>
/// This method will ensure that the identifiers of the activities to be added to the parent activity
/// are unique within the scope of the parent activity.
/// </summary>
/// <param name="parentActivity">THis activity is the parent activity which the child activities are being added</param>
/// <param name="childActivities"></param>
void IIdentifierCreationService.EnsureUniqueIdentifiers(CompositeActivity parentActivity, ICollection childActivities)
{
if (parentActivity == null)
throw new ArgumentNullException("parentActivity");
if (childActivities == null)
throw new ArgumentNullException("childActivities");
ArrayList allActivities = new ArrayList();
Queue activities = new Queue(childActivities);
while (activities.Count > 0)
{
Activity activity = (Activity)activities.Dequeue();
if (activity is CompositeActivity)
{
foreach (Activity child in ((CompositeActivity)activity).Activities)
activities.Enqueue(child);
}
//If we are moving activities, we need not regenerate their identifiers
if (((IComponent)activity).Site != null)
continue;
//If the activity is built-in, we won't generate a new ID.
if (IsPreBuiltActivity(activity))
continue;
allActivities.Add(activity);
}
// get the root activity
CompositeActivity rootActivity = Helpers.GetRootActivity(parentActivity) as CompositeActivity;
StringDictionary identifiers = new StringDictionary(); // all the identifiers in the workflow
Type customActivityType = GetRootActivityType(this.serviceProvider);
if (rootActivity != null)
{
foreach (string identifier in Helpers.GetIdentifiersInCompositeActivity(rootActivity))
identifiers[identifier] = identifier;
}
if (customActivityType != null)
{
foreach (MemberInfo member in customActivityType.GetMembers(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance))
{
Type memberType = null;
if (member is FieldInfo)
memberType = ((FieldInfo)member).FieldType;
if (memberType == null || !typeof(Activity).IsAssignableFrom(memberType))
identifiers[member.Name] = member.Name;
}
}
// now loop until we find a identifier that hasn't been used
foreach (Activity activity in allActivities)
{
int index = 0;
string baseIdentifier = Helpers.GetBaseIdentifier(activity);
string finalIdentifier = null;
if (string.IsNullOrEmpty(activity.Name) || string.Equals(activity.Name, activity.GetType().Name, StringComparison.Ordinal))
finalIdentifier = string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { baseIdentifier, ++index });
else
finalIdentifier = activity.Name;
while (identifiers.ContainsKey(finalIdentifier))
{
finalIdentifier = string.Format(CultureInfo.InvariantCulture, "{0}{1}", new object[] { baseIdentifier, ++index });
if (this.Provider != null)
finalIdentifier = this.Provider.CreateValidIdentifier(finalIdentifier);
}
// add new identifier to collection
identifiers[finalIdentifier] = finalIdentifier;
activity.Name = finalIdentifier;
}
}
#endregion
private Type GetRootActivityType(IServiceProvider serviceProvider)
{
IDesignerHost host = serviceProvider.GetService(typeof(IDesignerHost)) as IDesignerHost;
if (host == null)
throw new Exception(SR.GetString(SR.General_MissingService, typeof(IDesignerHost).FullName));
string className = host.RootComponentClassName;
if (string.IsNullOrEmpty(className))
return null;
ITypeProvider typeProvider = serviceProvider.GetService(typeof(ITypeProvider)) as ITypeProvider;
if (typeProvider == null)
throw new Exception(SR.GetString(SR.General_MissingService, typeof(ITypeProvider).FullName));
return typeProvider.GetType(className, false);
}
private static bool IsPreBuiltActivity(Activity activity)
{
CompositeActivity parent = activity.Parent;
while (parent != null)
{
// Any custom activity found, then locked
if (Helpers.IsCustomActivity(parent))
return true;
parent = parent.Parent;
}
return false;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using Microsoft.Test.ModuleCore;
using System.Xml.Linq;
namespace CoreXml.Test.XLinq
{
public static class XMLReaderExtension
{
public static string[] GetSAData(this XmlReader r)
{
return new string[] { r.Prefix, r.LocalName, r.NamespaceURI, r.Value };
}
}
public static class ReaderDiffNSAware
{
public class NSStack
{
private Dictionary<int, Dictionary<string, string>> _nsStack = new Dictionary<int, Dictionary<string, string>>();
public NSStack()
{
// prepopulate ns stack with the xml namespace
Dictionary<string, string> xmlNs = new Dictionary<string, string>();
xmlNs.Add("xml", XNamespace.Xml.NamespaceName);
_nsStack.Add(0, xmlNs);
}
public void Add(int depth, string prefix, string ns)
{
// verify whether we do have duplicate
TestLog.Compare(!IsDuplicate(depth, prefix, ns), String.Format("Duplicate: {0}, {1}", prefix, ns));
// no duplicates, add new one
if (!_nsStack.ContainsKey(depth)) _nsStack.Add(depth, new Dictionary<string, string>());
_nsStack[depth].Add(prefix, ns);
}
public bool IsDuplicate(int depth, string prefix, string ns)
{
// verify whether we do have duplicate
for (int i = depth; i >= 0; i--)
{
if (_nsStack.ContainsKey(i) && _nsStack[i].ContainsKey(prefix))
{
return (_nsStack[i][prefix] == ns);
}
}
return false;
}
public void RemoveDepth(int depth)
{
if (_nsStack.ContainsKey(depth))
{
_nsStack.Remove(depth); // remove the lines and decrement current depth
}
}
}
public static void CompareNamespaceAware(SaveOptions so, XmlReader originalReader, XmlReader filteredReader)
{
if ((so & SaveOptions.OmitDuplicateNamespaces) > 0) CompareNamespaceAware(originalReader, filteredReader);
else ReaderDiff.Compare(originalReader, filteredReader);
return;
}
public static void CompareNamespaceAware(XmlReader originalReader, XmlReader filteredReader)
{
NSStack nsStack = new NSStack();
while (true)
{
bool r1Read = originalReader.Read();
TestLog.Compare(r1Read, filteredReader.Read(), "Read() out of sync");
if (!r1Read) break;
if (filteredReader.NodeType != XmlNodeType.Text)
{
TestLog.Compare(originalReader.NodeType, filteredReader.NodeType, "nodeType");
TestLog.Compare(originalReader.LocalName, filteredReader.LocalName, "localname");
TestLog.Compare(originalReader.NamespaceURI, filteredReader.NamespaceURI, "Namespaceuri");
}
else
{
TestLog.Compare(originalReader.Value, filteredReader.Value, "localname");
}
if (originalReader.NodeType == XmlNodeType.Element)
{
// read all r1 attributes
var origAttrs = MoveAtrributeEnumerator(originalReader).ToArray();
// read all r2 attributes
var filteredAttrs = MoveAtrributeEnumerator(filteredReader).ToArray();
// Verify HasAttributes consistency
TestLog.Compare(filteredAttrs.Any(), filteredReader.HasAttributes, "has attributes");
TestLog.Compare(filteredAttrs.Length, filteredReader.AttributeCount, "attribute count");
// Verify int indexers consistency
for (int i = 0; i < filteredAttrs.Length; i++)
{
// Verify int indexers consistency
TestLog.Compare(filteredReader[i], filteredAttrs[i][3], "value of attribute ... indexer[int]");
TestLog.Compare(filteredReader.GetAttribute(i), filteredAttrs[i][3], "value of attribute ... GetAttribute[int]");
filteredReader.MoveToAttribute(i);
TestLog.Compare(SAEqComparer.Instance.Equals(filteredReader.GetSAData(), filteredAttrs[i]), "Move to attribute int - wrong position");
VerifyNextFirstAttribute(filteredReader, filteredAttrs, i, " after MoveToAttribute (int)");
}
// does not overreach the index
{
try
{
filteredReader.MoveToAttribute(filteredAttrs.Length);
TestLog.Compare(false, "READER over reached the index");
}
catch (ArgumentOutOfRangeException)
{
}
}
// does not underreach the index
{
try
{
filteredReader.MoveToAttribute(-1);
TestLog.Compare(false, "READER under reached the index");
}
catch (ArgumentOutOfRangeException)
{
}
}
// Verify string / string,string indexers consistency
// note: using int approach to be able to verify MoveToFirst/NextAttribute consistency
for (int i = 0; i < filteredAttrs.Length; i++)
{
var n = filteredAttrs[i];
TestLog.Compare(filteredReader[n[1], n[2]], n[3], "value of attribute ... indexer[string, string]");
TestLog.Compare(filteredReader.GetAttribute(n[1], n[2]), n[3], "value of attribute ... GetAttribute[string, string]");
TestLog.Compare(filteredReader.MoveToAttribute(n[1], n[2]), "Move to attribute string/string");
TestLog.Compare(SAEqComparer.Instance.Equals(filteredReader.GetSAData(), n), "Move to attribute string/string - wrong position");
VerifyNextFirstAttribute(filteredReader, filteredAttrs, i, " after MoveToAttribute (string,string)");
filteredReader.MoveToElement(); // reset the reader position
string qName = n[0] == "" ? n[1] : string.Format("{0}:{1}", n[0], n[1]);
TestLog.Compare(filteredReader[qName], n[3], "value of attribute ... indexer[string]");
TestLog.Compare(filteredReader.GetAttribute(qName), n[3], "value of attribute ... GetAttribute[string]");
TestLog.Compare(filteredReader.MoveToAttribute(qName), "Move to attribute string/string");
TestLog.Compare(SAEqComparer.Instance.Equals(filteredReader.GetSAData(), n), "Move to attribute string/string - wrong position");
VerifyNextFirstAttribute(filteredReader, filteredAttrs, i, " after MoveToAttribute (string)");
filteredReader.MoveToElement(); // reset the reader position
// lookup namespaces for the declaration nodes
if (n[2] == XNamespace.Xmlns || n[1] == "xmlns")
{
TestLog.Compare(filteredReader.LookupNamespace(n[0] != "" ? n[1] : ""), n[3], "Lookup namespace failed for kept declaration");
}
}
// Verify that not reported NS are not accessible
var duplicateAttrs = origAttrs.Except(filteredAttrs, SAEqComparer.Instance).ToArray();
foreach (var n in duplicateAttrs)
{
TestLog.Compare(filteredReader[n[1], n[2]], null, "Should not found : value of attribute ... indexer[string, string]");
TestLog.Compare(filteredReader.GetAttribute(n[1], n[2]), null, "Should not found : value of attribute ... GetAttribute[string, string]");
var orig = filteredReader.GetSAData();
TestLog.Compare(!filteredReader.MoveToAttribute(n[1], n[2]), "Should not found : Move to attribute string/string");
TestLog.Compare(SAEqComparer.Instance.Equals(filteredReader.GetSAData(), orig), "Should not found : Move to attribute string/string - wrong position");
filteredReader.MoveToElement(); // reset the reader position
string qName = n[0] == "" ? n[1] : string.Format("{0}:{1}", n[0], n[1]);
TestLog.Compare(filteredReader[qName], null, "Should not found : value of attribute ... indexer[string]");
TestLog.Compare(filteredReader.GetAttribute(qName), null, "Should not found : value of attribute ... GetAttribute[string]");
orig = filteredReader.GetSAData();
TestLog.Compare(!filteredReader.MoveToAttribute(qName), "Should not found : Move to attribute string/string");
TestLog.Compare(SAEqComparer.Instance.Equals(filteredReader.GetSAData(), orig), "Should not found : Move to attribute string/string - wrong position");
filteredReader.MoveToElement(); // reset the reader position
// removed are only namespace declarations
TestLog.Compare(n[2] == XNamespace.Xmlns || n[1] == "xmlns", "Removed is not namespace declaration");
// Lookup namespace ... should pass
TestLog.Compare(filteredReader.LookupNamespace(n[0] != "" ? n[1] : ""), n[3], "Lookup namespace failed - for removed declaration");
}
// compare non-xmlns attributes
// compare xmlns attributes (those in r2 must be in r1)
// verify r2 namespace stack
Compare(origAttrs, filteredAttrs, nsStack, filteredReader.Depth);
}
// nsStack cleanup
if (originalReader.NodeType == XmlNodeType.EndElement || originalReader.IsEmptyElement) nsStack.RemoveDepth(filteredReader.Depth);
}
}
private static void VerifyNextFirstAttribute(XmlReader filteredReader, string[][] filteredAttrs, int attrPosition, string message)
{
// MoveToNextAttribute works OK
bool shouldNAWork = (attrPosition < filteredAttrs.Length - 1);
var orig = filteredReader.GetSAData();
TestLog.Compare(filteredReader.MoveToNextAttribute(), shouldNAWork, "Move to next attribute :: " + message);
TestLog.Compare(SAEqComparer.Instance.Equals(shouldNAWork ? filteredAttrs[attrPosition + 1] : orig, filteredReader.GetSAData()), "MoveToNextAttribute moved to bad position :: " + message);
// MoveToFirstAttribute works OK
TestLog.Compare(filteredReader.MoveToFirstAttribute(), "Move to first attribute should always work :: " + message);
TestLog.Compare(SAEqComparer.Instance.Equals(filteredAttrs[0], filteredReader.GetSAData()), "MoveToNextAttribute moved to bad position :: " + message);
}
private class SAEqComparer : IEqualityComparer<string[]>
{
private static SAEqComparer s_instance = new SAEqComparer();
public static SAEqComparer Instance
{
get { return s_instance; }
}
public bool Equals(string[] x, string[] y)
{
return x.SequenceEqual(y);
}
public int GetHashCode(string[] strings)
{
if (strings.Length == 0) return 0;
int hash = strings[0].GetHashCode();
for (int i = 1; i < strings.Length; i++) hash ^= strings[i].GetHashCode();
return hash;
}
}
private static IEnumerable<string[]> IndexedAtrributeEnumerator(XmlReader r, bool moveToElement)
{
TestLog.Compare(r.NodeType, XmlNodeType.Element, "Assert for enumerator"); // assert
int aCount = r.AttributeCount;
for (int i = 0; i < aCount; i++)
{
r.MoveToAttribute(i);
yield return r.GetSAData();
if (moveToElement) r.MoveToElement();
}
r.MoveToElement();
}
private static IEnumerable<string[]> MoveAtrributeEnumerator(XmlReader r)
{
TestLog.Compare(r.NodeType, XmlNodeType.Element, "Assert for enumerator"); // assert
if (r.MoveToFirstAttribute())
{
do
{
yield return r.GetSAData();
}
while (r.MoveToNextAttribute());
r.MoveToElement();
}
}
public static void Compare(IEnumerable<string[]> r1, IEnumerable<String[]> r2, NSStack nsTable, int depth)
{
IEnumerator<string[]> r1E = r1.GetEnumerator();
IEnumerator<string[]> r2E = r2.GetEnumerator();
while (r2E.MoveNext())
{
bool found = false;
while (!found)
{
r1E.MoveNext();
found = r1E.Current.SequenceEqual(r2E.Current, StringComparer.Ordinal);
if (!found)
{
// Verify the one thrown out is a) ns decl: b) the nsTable detect it as duplicate
TestLog.Compare(r1E.Current[2] == XNamespace.Xmlns.NamespaceName || r1E.Current[1] == "xmlns", String.Format("Reader removed the non NS declaration attribute: {0},{1},{2},{3}", r1E.Current[0], r1E.Current[1], r1E.Current[2], r1E.Current[3]));
TestLog.Compare(nsTable.IsDuplicate(depth, r1E.Current[1], r1E.Current[3]), "The namespace decl was not duplicate");
}
}
TestLog.Compare(found, true, "Attribute from r2 not found in r1!");
if (r2E.Current[2] == XNamespace.Xmlns.NamespaceName || r2E.Current[1] == "xmlns")
{
nsTable.Add(depth, r2E.Current[1], r2E.Current[3]);
}
}
}
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
using System.Globalization;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using Microsoft.Identity.Json.Serialization;
using Microsoft.Identity.Json.Utilities;
namespace Microsoft.Identity.Json
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized JSON data.
/// </summary>
internal abstract partial class JsonReader : IDisposable
{
/// <summary>
/// Specifies the state of the reader.
/// </summary>
protected internal enum State
{
/// <summary>
/// A <see cref="JsonReader"/> read method has not been called.
/// </summary>
Start,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Complete,
/// <summary>
/// Reader is at a property.
/// </summary>
Property,
/// <summary>
/// Reader is at the start of an object.
/// </summary>
ObjectStart,
/// <summary>
/// Reader is in an object.
/// </summary>
Object,
/// <summary>
/// Reader is at the start of an array.
/// </summary>
ArrayStart,
/// <summary>
/// Reader is in an array.
/// </summary>
Array,
/// <summary>
/// The <see cref="JsonReader.Close()"/> method has been called.
/// </summary>
Closed,
/// <summary>
/// Reader has just read a value.
/// </summary>
PostValue,
/// <summary>
/// Reader is at the start of a constructor.
/// </summary>
ConstructorStart,
/// <summary>
/// Reader is in a constructor.
/// </summary>
Constructor,
/// <summary>
/// An error occurred that prevents the read operation from continuing.
/// </summary>
Error,
/// <summary>
/// The end of the file has been reached successfully.
/// </summary>
Finished
}
// current Token data
private JsonToken _tokenType;
private object _value;
internal char _quoteChar;
internal State _currentState;
private JsonPosition _currentPosition;
private CultureInfo _culture;
private DateTimeZoneHandling _dateTimeZoneHandling;
private int? _maxDepth;
private bool _hasExceededMaxDepth;
internal DateParseHandling _dateParseHandling;
internal FloatParseHandling _floatParseHandling;
private string _dateFormatString;
private List<JsonPosition> _stack;
/// <summary>
/// Gets the current reader state.
/// </summary>
/// <value>The current reader state.</value>
protected State CurrentState => _currentState;
/// <summary>
/// Gets or sets a value indicating whether the source should be closed when this reader is closed.
/// </summary>
/// <value>
/// <c>true</c> to close the source when this reader is closed; otherwise <c>false</c>. The default is <c>true</c>.
/// </value>
public bool CloseInput { get; set; }
/// <summary>
/// Gets or sets a value indicating whether multiple pieces of JSON content can
/// be read from a continuous stream without erroring.
/// </summary>
/// <value>
/// <c>true</c> to support reading multiple pieces of JSON content; otherwise <c>false</c>.
/// The default is <c>false</c>.
/// </value>
public bool SupportMultipleContent { get; set; }
/// <summary>
/// Gets the quotation mark character used to enclose the value of a string.
/// </summary>
public virtual char QuoteChar
{
get => _quoteChar;
protected internal set => _quoteChar = value;
}
/// <summary>
/// Gets or sets how <see cref="DateTime"/> time zones are handled when reading JSON.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get => _dateTimeZoneHandling;
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Gets or sets how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON.
/// </summary>
public DateParseHandling DateParseHandling
{
get => _dateParseHandling;
set
{
if (value < DateParseHandling.None ||
#if HAVE_DATE_TIME_OFFSET
value > DateParseHandling.DateTimeOffset
#else
value > DateParseHandling.DateTime
#endif
)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateParseHandling = value;
}
}
/// <summary>
/// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public FloatParseHandling FloatParseHandling
{
get => _floatParseHandling;
set
{
if (value < FloatParseHandling.Double || value > FloatParseHandling.Decimal)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatParseHandling = value;
}
}
/// <summary>
/// Gets or sets how custom date formatted strings are parsed when reading JSON.
/// </summary>
public string DateFormatString
{
get => _dateFormatString;
set => _dateFormatString = value;
}
/// <summary>
/// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>.
/// </summary>
public int? MaxDepth
{
get => _maxDepth;
set
{
if (value <= 0)
{
throw new ArgumentException("Value must be positive.", nameof(value));
}
_maxDepth = value;
}
}
/// <summary>
/// Gets the type of the current JSON token.
/// </summary>
public virtual JsonToken TokenType => _tokenType;
/// <summary>
/// Gets the text value of the current JSON token.
/// </summary>
public virtual object Value => _value;
/// <summary>
/// Gets the .NET type for the current JSON token.
/// </summary>
public virtual Type ValueType => _value?.GetType();
/// <summary>
/// Gets the depth of the current token in the JSON document.
/// </summary>
/// <value>The depth of the current token in the JSON document.</value>
public virtual int Depth
{
get
{
int depth = _stack?.Count ?? 0;
if (JsonTokenUtils.IsStartToken(TokenType) || _currentPosition.Type == JsonContainerType.None)
{
return depth;
}
else
{
return depth + 1;
}
}
}
/// <summary>
/// Gets the path of the current JSON token.
/// </summary>
public virtual string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = _currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart;
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
}
}
/// <summary>
/// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get => _culture ?? CultureInfo.InvariantCulture;
set => _culture = value;
}
internal JsonPosition GetPosition(int depth)
{
if (_stack != null && depth < _stack.Count)
{
return _stack[depth];
}
return _currentPosition;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReader"/> class.
/// </summary>
protected JsonReader()
{
_currentState = State.Start;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
_dateParseHandling = DateParseHandling.DateTime;
_floatParseHandling = FloatParseHandling.Double;
CloseInput = true;
}
private void Push(JsonContainerType value)
{
UpdateScopeWithFinishedValue();
if (_currentPosition.Type == JsonContainerType.None)
{
_currentPosition = new JsonPosition(value);
}
else
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
_currentPosition = new JsonPosition(value);
// this is a little hacky because Depth increases when first property/value is written but only testing here is faster/simpler
if (_maxDepth != null && Depth + 1 > _maxDepth && !_hasExceededMaxDepth)
{
_hasExceededMaxDepth = true;
throw JsonReaderException.Create(this, "The reader's MaxDepth of {0} has been exceeded.".FormatWith(CultureInfo.InvariantCulture, _maxDepth));
}
}
}
private JsonContainerType Pop()
{
JsonPosition oldPosition;
if (_stack != null && _stack.Count > 0)
{
oldPosition = _currentPosition;
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
oldPosition = _currentPosition;
_currentPosition = new JsonPosition();
}
if (_maxDepth != null && Depth <= _maxDepth)
{
_hasExceededMaxDepth = false;
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Reads the next JSON token from the source.
/// </summary>
/// <returns><c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
public abstract bool Read();
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="int"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual int? ReadAsInt32()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
if (v is int i)
{
return i;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
i = (int)value;
}
else
#endif
{
try
{
i = Convert.ToInt32(v, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
// handle error for large integer overflow exceptions
throw JsonReaderException.Create(this, "Could not convert to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex);
}
}
SetToken(JsonToken.Integer, i, false);
return i;
case JsonToken.String:
string s = (string)Value;
return ReadInt32String(s);
}
throw JsonReaderException.Create(this, "Error reading integer. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal int? ReadInt32String(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (int.TryParse(s, NumberStyles.Integer, Culture, out int i))
{
SetToken(JsonToken.Integer, i, false);
return i;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to integer: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <returns>A <see cref="string"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual string ReadAsString()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.String:
return (string)Value;
}
if (JsonTokenUtils.IsPrimitiveToken(t))
{
object v = Value;
if (v != null)
{
string s;
if (v is IFormattable formattable)
{
s = formattable.ToString(null, Culture);
}
else
{
s = v is Uri uri ? uri.OriginalString : v.ToString();
}
SetToken(JsonToken.String, s, false);
return s;
}
}
throw JsonReaderException.Create(this, "Error reading string. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <returns>A <see cref="byte"/>[] or <c>null</c> if the next JSON token is null. This method will return <c>null</c> at the end of an array.</returns>
public virtual byte[] ReadAsBytes()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.StartObject:
{
ReadIntoWrappedTypeObject();
byte[] data = ReadAsBytes();
ReaderReadAndAssert();
if (TokenType != JsonToken.EndObject)
{
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
case JsonToken.String:
{
// attempt to convert possible base 64 or GUID string to bytes
// GUID has to have format 00000000-0000-0000-0000-000000000000
string s = (string)Value;
byte[] data;
if (s.Length == 0)
{
data = CollectionUtils.ArrayEmpty<byte>();
}
else if (ConvertUtils.TryConvertGuid(s, out Guid g1))
{
data = g1.ToByteArray();
}
else
{
data = Convert.FromBase64String(s);
}
SetToken(JsonToken.Bytes, data, false);
return data;
}
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Bytes:
if (Value is Guid g2)
{
byte[] data = g2.ToByteArray();
SetToken(JsonToken.Bytes, data, false);
return data;
}
return (byte[])Value;
case JsonToken.StartArray:
return ReadArrayIntoByteArray();
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal byte[] ReadArrayIntoByteArray()
{
List<byte> buffer = new List<byte>();
while (true)
{
if (!Read())
{
SetToken(JsonToken.None);
}
if (ReadArrayElementIntoByteArrayReportDone(buffer))
{
byte[] d = buffer.ToArray();
SetToken(JsonToken.Bytes, d, false);
return d;
}
}
}
private bool ReadArrayElementIntoByteArrayReportDone(List<byte> buffer)
{
switch (TokenType)
{
case JsonToken.None:
throw JsonReaderException.Create(this, "Unexpected end when reading bytes.");
case JsonToken.Integer:
buffer.Add(Convert.ToByte(Value, CultureInfo.InvariantCulture));
return false;
case JsonToken.EndArray:
return true;
case JsonToken.Comment:
return false;
default:
throw JsonReaderException.Create(this, "Unexpected token when reading bytes: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="double"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual double? ReadAsDouble()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
if (v is double d)
{
return d;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
d = (double)value;
}
else
#endif
{
d = Convert.ToDouble(v, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Float, d, false);
return (double)d;
case JsonToken.String:
return ReadDoubleString((string)Value);
}
throw JsonReaderException.Create(this, "Error reading double. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal double? ReadDoubleString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (double.TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, Culture, out double d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to double: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="bool"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual bool? ReadAsBoolean()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
bool b;
#if HAVE_BIG_INTEGER
if (Value is BigInteger integer)
{
b = integer != 0;
}
else
#endif
{
b = Convert.ToBoolean(Value, CultureInfo.InvariantCulture);
}
SetToken(JsonToken.Boolean, b, false);
return b;
case JsonToken.String:
return ReadBooleanString((string)Value);
case JsonToken.Boolean:
return (bool)Value;
}
throw JsonReaderException.Create(this, "Error reading boolean. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal bool? ReadBooleanString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (bool.TryParse(s, out bool b))
{
SetToken(JsonToken.Boolean, b, false);
return b;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to boolean: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="decimal"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual decimal? ReadAsDecimal()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Integer:
case JsonToken.Float:
object v = Value;
if (v is decimal d)
{
return d;
}
#if HAVE_BIG_INTEGER
if (v is BigInteger value)
{
d = (decimal)value;
}
else
#endif
{
try
{
d = Convert.ToDecimal(v, CultureInfo.InvariantCulture);
}
catch (Exception ex)
{
// handle error for large integer overflow exceptions
throw JsonReaderException.Create(this, "Could not convert to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, v), ex);
}
}
SetToken(JsonToken.Float, d, false);
return d;
case JsonToken.String:
return ReadDecimalString((string)Value);
}
throw JsonReaderException.Create(this, "Error reading decimal. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
internal decimal? ReadDecimalString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (decimal.TryParse(s, NumberStyles.Number, Culture, out decimal d))
{
SetToken(JsonToken.Float, d, false);
return d;
}
else if (ConvertUtils.DecimalTryParse(s.ToCharArray(), 0, s.Length, out d) == ParseResult.Success)
{
// This is to handle strings like "96.014e-05" that are not supported by traditional decimal.TryParse
SetToken(JsonToken.Float, d, false);
return d;
}
else
{
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to decimal: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
}
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual DateTime? ReadAsDateTime()
{
switch (GetContentToken())
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Date:
#if HAVE_DATE_TIME_OFFSET
if (Value is DateTimeOffset offset)
{
SetToken(JsonToken.Date, offset.DateTime, false);
}
#endif
return (DateTime)Value;
case JsonToken.String:
string s = (string)Value;
return ReadDateTimeString(s);
}
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, TokenType));
}
internal DateTime? ReadDateTimeString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (DateTimeUtils.TryParseDateTime(s, DateTimeZoneHandling, _dateFormatString, Culture, out DateTime dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTime.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
dt = DateTimeUtils.EnsureDateTime(dt, DateTimeZoneHandling);
SetToken(JsonToken.Date, dt, false);
return dt;
}
throw JsonReaderException.Create(this, "Could not convert string to DateTime: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <returns>A <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This method will return <c>null</c> at the end of an array.</returns>
public virtual DateTimeOffset? ReadAsDateTimeOffset()
{
JsonToken t = GetContentToken();
switch (t)
{
case JsonToken.None:
case JsonToken.Null:
case JsonToken.EndArray:
return null;
case JsonToken.Date:
if (Value is DateTime time)
{
SetToken(JsonToken.Date, new DateTimeOffset(time), false);
}
return (DateTimeOffset)Value;
case JsonToken.String:
string s = (string)Value;
return ReadDateTimeOffsetString(s);
default:
throw JsonReaderException.Create(this, "Error reading date. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, t));
}
}
internal DateTimeOffset? ReadDateTimeOffsetString(string s)
{
if (string.IsNullOrEmpty(s))
{
SetToken(JsonToken.Null, null, false);
return null;
}
if (DateTimeUtils.TryParseDateTimeOffset(s, _dateFormatString, Culture, out DateTimeOffset dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
if (DateTimeOffset.TryParse(s, Culture, DateTimeStyles.RoundtripKind, out dt))
{
SetToken(JsonToken.Date, dt, false);
return dt;
}
SetToken(JsonToken.String, s, false);
throw JsonReaderException.Create(this, "Could not convert string to DateTimeOffset: {0}.".FormatWith(CultureInfo.InvariantCulture, s));
}
#endif
internal void ReaderReadAndAssert()
{
if (!Read())
{
throw CreateUnexpectedEndException();
}
}
internal JsonReaderException CreateUnexpectedEndException()
{
return JsonReaderException.Create(this, "Unexpected end when reading JSON.");
}
internal void ReadIntoWrappedTypeObject()
{
ReaderReadAndAssert();
if (Value != null && Value.ToString() == JsonTypeReflector.TypePropertyName)
{
ReaderReadAndAssert();
if (Value != null && Value.ToString().StartsWith("System.Byte[]", StringComparison.Ordinal))
{
ReaderReadAndAssert();
if (Value.ToString() == JsonTypeReflector.ValuePropertyName)
{
return;
}
}
}
throw JsonReaderException.Create(this, "Error reading bytes. Unexpected token: {0}.".FormatWith(CultureInfo.InvariantCulture, JsonToken.StartObject));
}
/// <summary>
/// Skips the children of the current token.
/// </summary>
public void Skip()
{
if (TokenType == JsonToken.PropertyName)
{
Read();
}
if (JsonTokenUtils.IsStartToken(TokenType))
{
int depth = Depth;
while (Read() && (depth < Depth))
{
}
}
}
/// <summary>
/// Sets the current token.
/// </summary>
/// <param name="newToken">The new token.</param>
protected void SetToken(JsonToken newToken)
{
SetToken(newToken, null, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
protected void SetToken(JsonToken newToken, object value)
{
SetToken(newToken, value, true);
}
/// <summary>
/// Sets the current token and value.
/// </summary>
/// <param name="newToken">The new token.</param>
/// <param name="value">The value.</param>
/// <param name="updateIndex">A flag indicating whether the position index inside an array should be updated.</param>
protected void SetToken(JsonToken newToken, object value, bool updateIndex)
{
_tokenType = newToken;
_value = value;
switch (newToken)
{
case JsonToken.StartObject:
_currentState = State.ObjectStart;
Push(JsonContainerType.Object);
break;
case JsonToken.StartArray:
_currentState = State.ArrayStart;
Push(JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
_currentState = State.ConstructorStart;
Push(JsonContainerType.Constructor);
break;
case JsonToken.EndObject:
ValidateEnd(JsonToken.EndObject);
break;
case JsonToken.EndArray:
ValidateEnd(JsonToken.EndArray);
break;
case JsonToken.EndConstructor:
ValidateEnd(JsonToken.EndConstructor);
break;
case JsonToken.PropertyName:
_currentState = State.Property;
_currentPosition.PropertyName = (string)value;
break;
case JsonToken.Undefined:
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Date:
case JsonToken.String:
case JsonToken.Raw:
case JsonToken.Bytes:
SetPostValueState(updateIndex);
break;
}
}
internal void SetPostValueState(bool updateIndex)
{
if (Peek() != JsonContainerType.None || SupportMultipleContent)
{
_currentState = State.PostValue;
}
else
{
SetFinished();
}
if (updateIndex)
{
UpdateScopeWithFinishedValue();
}
}
private void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void ValidateEnd(JsonToken endToken)
{
JsonContainerType currentObject = Pop();
if (GetTypeForCloseToken(endToken) != currentObject)
{
throw JsonReaderException.Create(this, "JsonToken {0} is not valid for closing JsonType {1}.".FormatWith(CultureInfo.InvariantCulture, endToken, currentObject));
}
if (Peek() != JsonContainerType.None || SupportMultipleContent)
{
_currentState = State.PostValue;
}
else
{
SetFinished();
}
}
/// <summary>
/// Sets the state based on current token type.
/// </summary>
protected void SetStateBasedOnCurrent()
{
JsonContainerType currentObject = Peek();
switch (currentObject)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Constructor;
break;
case JsonContainerType.None:
SetFinished();
break;
default:
throw JsonReaderException.Create(this, "While setting the reader state back to current object an unexpected JsonType was encountered: {0}".FormatWith(CultureInfo.InvariantCulture, currentObject));
}
}
private void SetFinished()
{
_currentState = SupportMultipleContent ? State.Start : State.Finished;
}
private JsonContainerType GetTypeForCloseToken(JsonToken token)
{
switch (token)
{
case JsonToken.EndObject:
return JsonContainerType.Object;
case JsonToken.EndArray:
return JsonContainerType.Array;
case JsonToken.EndConstructor:
return JsonContainerType.Constructor;
default:
throw JsonReaderException.Create(this, "Not a valid close JsonToken: {0}".FormatWith(CultureInfo.InvariantCulture, token));
}
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
{
Close();
}
}
/// <summary>
/// Changes the reader's state to <see cref="JsonReader.State.Closed"/>.
/// If <see cref="JsonReader.CloseInput"/> is set to <c>true</c>, the source is also closed.
/// </summary>
public virtual void Close()
{
_currentState = State.Closed;
_tokenType = JsonToken.None;
_value = null;
}
internal void ReadAndAssert()
{
if (!Read())
{
throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
}
}
internal void ReadForTypeAndAssert(JsonContract contract, bool hasConverter)
{
if (!ReadForType(contract, hasConverter))
{
throw JsonSerializationException.Create(this, "Unexpected end when reading JSON.");
}
}
internal bool ReadForType(JsonContract contract, bool hasConverter)
{
// don't read properties with converters as a specific value
// the value might be a string which will then get converted which will error if read as date for example
if (hasConverter)
{
return Read();
}
ReadType t = contract?.InternalReadType ?? ReadType.Read;
switch (t)
{
case ReadType.Read:
return ReadAndMoveToContent();
case ReadType.ReadAsInt32:
ReadAsInt32();
break;
case ReadType.ReadAsInt64:
bool result = ReadAndMoveToContent();
if (TokenType == JsonToken.Undefined)
{
throw JsonReaderException.Create(this, "An undefined token is not a valid {0}.".FormatWith(CultureInfo.InvariantCulture, contract?.UnderlyingType ?? typeof(long)));
}
return result;
case ReadType.ReadAsDecimal:
ReadAsDecimal();
break;
case ReadType.ReadAsDouble:
ReadAsDouble();
break;
case ReadType.ReadAsBytes:
ReadAsBytes();
break;
case ReadType.ReadAsBoolean:
ReadAsBoolean();
break;
case ReadType.ReadAsString:
ReadAsString();
break;
case ReadType.ReadAsDateTime:
ReadAsDateTime();
break;
#if HAVE_DATE_TIME_OFFSET
case ReadType.ReadAsDateTimeOffset:
ReadAsDateTimeOffset();
break;
#endif
default:
throw new ArgumentOutOfRangeException();
}
return TokenType != JsonToken.None;
}
internal bool ReadAndMoveToContent()
{
return Read() && MoveToContent();
}
internal bool MoveToContent()
{
JsonToken t = TokenType;
while (t == JsonToken.None || t == JsonToken.Comment)
{
if (!Read())
{
return false;
}
t = TokenType;
}
return true;
}
private JsonToken GetContentToken()
{
JsonToken t;
do
{
if (!Read())
{
SetToken(JsonToken.None);
return JsonToken.None;
}
else
{
t = TokenType;
}
} while (t == JsonToken.Comment);
return t;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using ASC.Core;
using ASC.Web.Studio.Core;
namespace ASC.Mail
{
public static class Defines
{
static Defines()
{
DefaultServerLoginDelay = ConfigurationManagerExtension.AppSettings["mail.default-login-delay"] != null
? Convert.ToInt32(ConfigurationManagerExtension.AppSettings["mail.default-login-delay"])
: 30;
DefaultServerLoginDelayStr = DefaultServerLoginDelay.ToString();
SslCertificatesErrorPermit = ConfigurationManagerExtension.AppSettings["mail.certificate-permit"] != null &&
Convert.ToBoolean(ConfigurationManagerExtension.AppSettings["mail.certificate-permit"]);
IsSignalRAvailable = !string.IsNullOrEmpty(ConfigurationManagerExtension.AppSettings["web.hub"]);
AuthErrorWarningTimeout = ConfigurationManagerExtension.AppSettings["mail.auth-error-warning-in-minutes"] != null
? TimeSpan.FromMinutes(
Convert.ToInt32(ConfigurationManagerExtension.AppSettings["mail.auth-error-warning-in-minutes"]))
: TimeSpan.FromHours(1);
AuthErrorDisableTimeout = ConfigurationManagerExtension.AppSettings["mail.auth-error-disable-mailbox-in-minutes"] != null
? TimeSpan.FromMinutes(
Convert.ToInt32(
ConfigurationManagerExtension.AppSettings["mail.auth-error-disable-mailbox-in-minutes"]))
: TimeSpan.FromDays(3);
MailDaemonEmail = ConfigurationManagerExtension.AppSettings["mail.daemon-email"] ?? "mail-daemon@onlyoffice.com";
NeedProxyHttp = SetupInfo.IsVisibleSettings("ProxyHttpContent");
TcpTimeout = ConfigurationManagerExtension.AppSettings["mail.tcp-timeout"] != null
? Convert.ToInt32(ConfigurationManagerExtension.AppSettings["mail.tcp-timeout"])
: 10000;
var limit = ConfigurationManagerExtension.AppSettings["mail.recalculate-folders-timeout"];
RecalculateFoldersTimeout = limit != null ? Convert.ToInt32(limit) : 99999;
limit = ConfigurationManagerExtension.AppSettings["mail.remove-domain-timeout"];
RemoveDomainTimeout = limit != null ? Convert.ToInt32(limit) : 99999;
limit = ConfigurationManagerExtension.AppSettings["mail.remove-mailbox-timeout"];
RemoveMailboxTimeout = limit != null ? Convert.ToInt32(limit) : 99999;
var saveFlag = ConfigurationManagerExtension.AppSettings["mail.save-original-message"];
SaveOriginalMessage = saveFlag != null && Convert.ToBoolean(saveFlag);
ServerDomainMailboxPerUserLimit = Convert.ToInt32(ConfigurationManagerExtension.AppSettings["mail.server-mailbox-limit-per-user"] ?? "2");
ServerDnsSpfRecordValue = ConfigurationManagerExtension.AppSettings["mail.server.spf-record-value"] ?? "v=spf1 +mx ~all";
ServerDnsMxRecordPriority = Convert.ToInt32(ConfigurationManagerExtension.AppSettings["mail.server.mx-record-priority"] ?? "0");
ServerDnsDkimSelector = ConfigurationManagerExtension.AppSettings["mail.server-dkim-selector"] ?? "dkim";
ServerDnsDomainCheckPrefix = ConfigurationManagerExtension.AppSettings["mail.server-dns-check-prefix"] ?? "onlyoffice-domain";
var ttl = ConfigurationManagerExtension.AppSettings["mail.server-dns-default-ttl"];
ServerDnsDefaultTtl = ttl != null ? Convert.ToInt32(ttl) : 300;
MaximumMessageBodySize = Convert.ToInt32(ConfigurationManagerExtension.AppSettings["mail.maximum-message-body-size"] ?? "524288");
var operations = ConfigurationManagerExtension.AppSettings["mail.attachments-group-operations"];
IsAttachmentsGroupOperationsAvailable = operations != null ? Convert.ToBoolean(operations) : true;
var linkAvailable = ConfigurationManagerExtension.AppSettings["mail.ms-migration-link-available"];
IsMSExchangeMigrationLinkAvailable = linkAvailable != null
? Convert.ToBoolean(linkAvailable)
: CoreContext.Configuration.Standalone;
var timeout = ConfigurationManagerExtension.AppSettings["mail.server-connection-timeout"];
MailServerConnectionTimeout = timeout != null ? Convert.ToInt32(timeout) : 15000;
timeout = ConfigurationManagerExtension.AppSettings["mail.server-enable-utf8-timeout"];
MailServerEnableUtf8Timeout = timeout != null ? Convert.ToInt32(timeout) : 15000;
timeout = ConfigurationManagerExtension.AppSettings["mail.server-login-timeout"];
MailServerLoginTimeout = timeout != null ? Convert.ToInt32(timeout) : 30000;
ApiSchema = ConfigurationManagerExtension.AppSettings["mail.default-api-scheme"] != null ?
ConfigurationManagerExtension.AppSettings["mail.default-api-scheme"] == Uri.UriSchemeHttps
? Uri.UriSchemeHttps
: Uri.UriSchemeHttp
: null;
ApiPrefix = (ConfigurationManagerExtension.AppSettings["api.url"] ?? "").Trim('~', '/');
ApiVirtualDirPrefix = (ConfigurationManagerExtension.AppSettings["api.virtual-dir"] ?? "").Trim('/');
ApiHost = ConfigurationManagerExtension.AppSettings["api.host"];
ApiPort = ConfigurationManagerExtension.AppSettings["api.port"];
AutoreplyDaysInterval = Convert.ToInt32(ConfigurationManagerExtension.AppSettings["mail.autoreply-days-interval"] ?? "1");
var config = ConfigurationManagerExtension.AppSettings["mail.disable-imap-send-sync-servers"] ?? "imap.googlemail.com|imap.gmail.com|imap-mail.outlook.com";
DisableImapSendSyncServers = string.IsNullOrEmpty(config) ? new List<string>() : config.Split('|').ToList();
var list = new Dictionary<string, string>
{
{".outlook.", "office365.com"},
{".google.", "gmail.com"},
{".yandex.", "yandex.ru"},
{".mail.ru", "mail.ru"},
{".yahoodns.", "yahoo.com"}
};
try
{
if (!string.IsNullOrEmpty(ConfigurationManagerExtension.AppSettings["mail.busines-vendors-mx-domains"]))
// ".outlook.:office365.com|.google.:gmail.com|.yandex.:yandex.ru|.mail.ru:mail.ru|.yahoodns.:yahoo.com"
{
list = ConfigurationManagerExtension.AppSettings["mail.busines-vendors-mx-domains"]
.Split('|')
.Select(s => s.Split(':'))
.ToDictionary(s => s[0], s => s[1]);
}
}
catch (Exception ex)
{
// skip error
}
MxToDomainBusinessVendorsList = list;
limit = ConfigurationManagerExtension.AppSettings["mail.operations-limit"];
MailOperationsLimit = limit != null ? Convert.ToInt32(limit) : 100;
}
public const string MODULE_NAME = "mailaggregator";
public const string MD5_EMPTY = "d41d8cd98f00b204e9800998ecf8427e";
public const int SHARED_TENANT_ID = -1;
public const int UNUSED_DNS_SETTING_DOMAIN_ID = -1;
public const string ICAL_REQUEST = "REQUEST";
public const string ICAL_REPLY = "REPLY";
public const string ICAL_CANCEL = "CANCEL";
public const string GOOGLE_HOST = "gmail.com";
public const int HARDCODED_LOGIN_TIME_FOR_MS_MAIL = 900;
public const string IMAP = "imap";
public const string POP3 = "pop3";
public const string SMTP = "smtp";
public const string SSL = "ssl";
public const string START_TLS = "starttls";
public const string PLAIN = "plain";
public const string OAUTH2 = "oauth2";
public const string PASSWORD_CLEARTEXT = "password-cleartext";
public const string PASSWORD_ENCRYPTED = "password-encrypted";
public const string NONE = "none";
public const string GET_IMAP_POP_SETTINGS = "get_imap_pop_settings";
public const string GET_IMAP_SERVER = "get_imap_server";
public const string GET_IMAP_SERVER_FULL = "get_imap_server_full";
public const string GET_POP_SERVER = "get_pop_server";
public const string GET_POP_SERVER_FULL = "get_pop_server_full";
public const string MAIL_QUOTA_TAG = "666ceac1-4532-4f8c-9cba-8f510eca2fd1";
public const long ATTACHMENTS_TOTAL_SIZE_LIMIT = 25 * 1024 * 1024; // 25 megabytes
public const string ASCENDING = "ascending";
public const string DESCENDING = "descending";
public const string ORDER_BY_DATE_SENT = "datesent";
public const string ORDER_BY_DATE_CHAIN = "chaindate";
public const string ORDER_BY_SENDER = "sender";
public const string ORDER_BY_SUBJECT = "subject";
public const string CONNECTION_STRING_NAME = "mail";
public const string DNS_DEFAULT_ORIGIN = "@";
public const string ARCHIVE_NAME = "download.tar.gz";
public static readonly DateTime BaseJsDateTime = new DateTime(1970, 1, 1);
public enum TariffType
{
Active = 0,
Overdue,
LongDead
};
public static int DefaultServerLoginDelay
{
get; private set;
}
public static string DefaultServerLoginDelayStr
{
get; private set;
}
public static readonly DateTime MinBeginDate = new DateTime(1975, 1, 1, 0, 0, 0);
public static bool SslCertificatesErrorPermit
{
get; private set;
}
public static bool IsSignalRAvailable
{
get; private set;
}
public static TimeSpan AuthErrorWarningTimeout
{
get; private set;
}
public static TimeSpan AuthErrorDisableTimeout
{
get; private set;
}
public static string MailDaemonEmail
{
get; private set;
}
public static bool NeedProxyHttp
{
get; private set;
}
/// <summary>
/// Test mailbox connection tcp timeout (10 sec is default)
/// </summary>
public static int TcpTimeout
{
get; private set;
}
public static int RecalculateFoldersTimeout
{
get; private set;
}
public static int RemoveDomainTimeout
{
get; private set;
}
public static int RemoveMailboxTimeout
{
get; private set;
}
public static bool SaveOriginalMessage
{
get; private set;
}
public static int ServerDomainMailboxPerUserLimit
{
get; private set;
}
public static string ServerDnsSpfRecordValue
{
get; private set;
}
public static int ServerDnsMxRecordPriority
{
get; private set;
}
public static string ServerDnsDkimSelector
{
get; private set;
}
public static string ServerDnsDomainCheckPrefix
{
get; private set;
}
public static int ServerDnsDefaultTtl
{
get; private set;
}
public static int MaximumMessageBodySize
{
get; private set;
}
public static bool IsAttachmentsGroupOperationsAvailable
{
get; private set;
}
public static bool IsMSExchangeMigrationLinkAvailable
{
get; private set;
}
public static int MailServerConnectionTimeout
{
get; private set;
}
public static int MailServerEnableUtf8Timeout
{
get; private set;
}
public static int MailServerLoginTimeout
{
get; private set;
}
public static string ApiSchema { get; private set; }
public static string DefaultApiSchema
{
get
{
if (!string.IsNullOrEmpty(ApiSchema))
{
return ApiSchema;
}
return HttpContext.Current == null
? Uri.UriSchemeHttp
: HttpContext.Current.Request.GetUrlRewriter().Scheme;
}
}
public static string ApiPrefix
{
get; private set;
}
public static string ApiVirtualDirPrefix
{
get; private set;
}
public static string ApiHost
{
get; private set;
}
public static string ApiPort
{
get; private set;
}
public static int AutoreplyDaysInterval
{
get; private set;
}
public static List<string> DisableImapSendSyncServers
{
get; private set;
}
public static Dictionary<string, string> MxToDomainBusinessVendorsList
{
get; private set;
}
public static int MailOperationsLimit
{
get; private set;
}
}
}
| |
using System.Collections;
using System.Globalization;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Iana;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Macs;
using Org.BouncyCastle.Crypto.Paddings;
namespace Org.BouncyCastle.Security
{
/// <remarks>
/// Utility class for creating HMac object from their names/Oids
/// </remarks>
public sealed class MacUtilities
{
private MacUtilities()
{
}
private static readonly Hashtable algorithms = new Hashtable();
// private static readonly Hashtable oids = new Hashtable();
static MacUtilities()
{
algorithms[IanaObjectIdentifiers.HmacMD5.Id] = "HMAC-MD5";
algorithms[IanaObjectIdentifiers.HmacRipeMD160.Id] = "HMAC-RIPEMD160";
algorithms[IanaObjectIdentifiers.HmacSha1.Id] = "HMAC-SHA1";
algorithms[IanaObjectIdentifiers.HmacTiger.Id] = "HMAC-TIGER";
algorithms[PkcsObjectIdentifiers.IdHmacWithSha1.Id] = "HMAC-SHA1";
algorithms[PkcsObjectIdentifiers.IdHmacWithSha224.Id] = "HMAC-SHA224";
algorithms[PkcsObjectIdentifiers.IdHmacWithSha256.Id] = "HMAC-SHA256";
algorithms[PkcsObjectIdentifiers.IdHmacWithSha384.Id] = "HMAC-SHA384";
algorithms[PkcsObjectIdentifiers.IdHmacWithSha512.Id] = "HMAC-SHA512";
algorithms["DES"] = "DESMAC";
algorithms["DES/CFB8"] = "DESMAC/CFB8";
algorithms["DESEDE"] = "DESEDEMAC";
algorithms["DESEDE/CFB8"] = "DESEDEMAC/CFB8";
algorithms["DESISO9797MAC"] = "DESWITHISO9797";
algorithms["DESEDE64"] = "DESEDEMAC64";
algorithms["DESEDE64WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING";
algorithms["DESEDEISO9797ALG1MACWITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING";
algorithms["DESEDEISO9797ALG1WITHISO7816-4PADDING"] = "DESEDEMAC64WITHISO7816-4PADDING";
algorithms["ISO9797ALG3"] = "ISO9797ALG3MAC";
algorithms["ISO9797ALG3MACWITHISO7816-4PADDING"] = "ISO9797ALG3WITHISO7816-4PADDING";
algorithms["SKIPJACK"] = "SKIPJACKMAC";
algorithms["SKIPJACK/CFB8"] = "SKIPJACKMAC/CFB8";
algorithms["IDEA"] = "IDEAMAC";
algorithms["IDEA/CFB8"] = "IDEAMAC/CFB8";
algorithms["RC2"] = "RC2MAC";
algorithms["RC2/CFB8"] = "RC2MAC/CFB8";
algorithms["RC5"] = "RC5MAC";
algorithms["RC5/CFB8"] = "RC5MAC/CFB8";
algorithms["GOST28147"] = "GOST28147MAC";
algorithms["VMPC"] = "VMPCMAC";
algorithms["VMPC-MAC"] = "VMPCMAC";
algorithms["PBEWITHHMACSHA"] = "PBEWITHHMACSHA1";
algorithms["1.3.14.3.2.26"] = "PBEWITHHMACSHA1";
}
// /// <summary>
// /// Returns a ObjectIdentifier for a given digest mechanism.
// /// </summary>
// /// <param name="mechanism">A string representation of the digest meanism.</param>
// /// <returns>A DerObjectIdentifier, null if the Oid is not available.</returns>
// public static DerObjectIdentifier GetObjectIdentifier(
// string mechanism)
// {
// mechanism = (string) algorithms[mechanism.ToUpper(CultureInfo.InvariantCulture)];
//
// if (mechanism != null)
// {
// return (DerObjectIdentifier)oids[mechanism];
// }
//
// return null;
// }
// public static ICollection Algorithms
// {
// get { return oids.Keys; }
// }
public static IMac GetMac(
DerObjectIdentifier id)
{
return GetMac(id.Id);
}
public static IMac GetMac(
string algorithm)
{
string upper = algorithm.ToUpper(CultureInfo.InvariantCulture);
string mechanism = (string) algorithms[upper];
if (mechanism == null)
{
mechanism = upper;
}
if (mechanism.StartsWith("PBEWITH"))
{
mechanism = mechanism.Substring("PBEWITH".Length);
}
if (mechanism.StartsWith("HMAC"))
{
string digestName;
if (mechanism.StartsWith("HMAC-") || mechanism.StartsWith("HMAC/"))
{
digestName = mechanism.Substring(5);
}
else
{
digestName = mechanism.Substring(4);
}
return new HMac(DigestUtilities.GetDigest(digestName));
}
if (mechanism == "DESMAC")
{
return new CbcBlockCipherMac(new DesEngine());
}
if (mechanism == "DESMAC/CFB8")
{
return new CfbBlockCipherMac(new DesEngine());
}
if (mechanism == "DESEDEMAC")
{
return new CbcBlockCipherMac(new DesEdeEngine());
}
if (mechanism == "DESEDEMAC/CFB8")
{
return new CfbBlockCipherMac(new DesEdeEngine());
}
if (mechanism == "DESEDEMAC64")
{
return new CbcBlockCipherMac(new DesEdeEngine(), 64);
}
if (mechanism == "DESEDEMAC64WITHISO7816-4PADDING")
{
return new CbcBlockCipherMac(new DesEdeEngine(), 64, new ISO7816d4Padding());
}
if (mechanism == "DESWITHISO9797"
|| mechanism == "ISO9797ALG3MAC")
{
return new ISO9797Alg3Mac(new DesEngine());
}
if (mechanism == "ISO9797ALG3WITHISO7816-4PADDING")
{
return new ISO9797Alg3Mac(new DesEngine(), new ISO7816d4Padding());
}
if (mechanism == "SKIPJACKMAC")
{
return new CbcBlockCipherMac(new SkipjackEngine());
}
if (mechanism == "SKIPJACKMAC/CFB8")
{
return new CfbBlockCipherMac(new SkipjackEngine());
}
#if INCLUDE_IDEA
if (mechanism == "IDEAMAC")
{
return new CbcBlockCipherMac(new IdeaEngine());
}
if (mechanism == "IDEAMAC/CFB8")
{
return new CfbBlockCipherMac(new IdeaEngine());
}
#endif
if (mechanism == "RC2MAC")
{
return new CbcBlockCipherMac(new RC2Engine());
}
if (mechanism == "RC2MAC/CFB8")
{
return new CfbBlockCipherMac(new RC2Engine());
}
if (mechanism == "RC5MAC")
{
return new CbcBlockCipherMac(new RC532Engine());
}
if (mechanism == "RC5MAC/CFB8")
{
return new CfbBlockCipherMac(new RC532Engine());
}
if (mechanism == "GOST28147MAC")
{
return new Gost28147Mac();
}
if (mechanism == "VMPCMAC")
{
return new VmpcMac();
}
throw new SecurityUtilityException("Mac " + mechanism + " not recognised.");
}
public static string GetAlgorithmName(
DerObjectIdentifier oid)
{
return (string) algorithms[oid.Id];
}
public static byte[] DoFinal(
IMac mac)
{
byte[] b = new byte[mac.GetMacSize()];
mac.DoFinal(b, 0);
return b;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
namespace ExcelDataReader.Portable.Core.OpenXmlFormat
{
internal class XlsxWorkbook
{
private const string N_sheet = "sheet";
private const string N_t = "t";
private const string N_si = "si";
private const string N_cellXfs = "cellXfs";
private const string N_numFmts = "numFmts";
private const string A_sheetId = "sheetId";
private const string A_visibleState = "state";
private const string A_name = "name";
private const string A_rid = "r:id";
private const string N_rel = "Relationship";
private const string A_id = "Id";
private const string A_target = "Target";
private XlsxWorkbook() { }
public XlsxWorkbook(Stream workbookStream, Stream relsStream, Stream sharedStringsStream, Stream stylesStream)
{
if (null == workbookStream) throw new ArgumentNullException();
ReadWorkbook(workbookStream);
ReadWorkbookRels(relsStream);
ReadSharedStrings(sharedStringsStream);
ReadStyles(stylesStream);
}
private List<XlsxWorksheet> sheets;
public List<XlsxWorksheet> Sheets
{
get { return sheets; }
set { sheets = value; }
}
private XlsxSST _SST;
public XlsxSST SST
{
get { return _SST; }
}
private XlsxStyles _Styles;
public XlsxStyles Styles
{
get { return _Styles; }
}
private void ReadStyles(Stream xmlFileStream)
{
if (null == xmlFileStream) return;
_Styles = new XlsxStyles();
bool rXlsxNumFmt = false;
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
while (reader.Read())
{
if (!rXlsxNumFmt && reader.NodeType == XmlNodeType.Element && reader.LocalName == N_numFmts)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1) break;
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == XlsxNumFmt.N_numFmt)
{
_Styles.NumFmts.Add(
new XlsxNumFmt(
int.Parse(reader.GetAttribute(XlsxNumFmt.A_numFmtId)),
reader.GetAttribute(XlsxNumFmt.A_formatCode)
));
}
}
rXlsxNumFmt = true;
}
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == N_cellXfs)
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.Depth == 1) break;
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == XlsxXf.N_xf)
{
var xfId = reader.GetAttribute(XlsxXf.A_xfId);
var numFmtId = reader.GetAttribute(XlsxXf.A_numFmtId);
_Styles.CellXfs.Add(
new XlsxXf(
xfId == null ? -1 : int.Parse(xfId),
numFmtId == null ? -1 : int.Parse(numFmtId),
reader.GetAttribute(XlsxXf.A_applyNumberFormat)
));
}
}
break;
}
}
xmlFileStream.Dispose();
}
}
private void ReadSharedStrings(Stream xmlFileStream)
{
if (null == xmlFileStream) return;
_SST = new XlsxSST();
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
// There are multiple <t> in a <si>. Concatenate <t> within an <si>.
bool bAddStringItem = false;
string sStringItem = "";
while (reader.Read())
{
// There are multiple <t> in a <si>. Concatenate <t> within an <si>.
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == N_si)
{
// Do not add the string item until the next string item is read.
if (bAddStringItem)
{
// Add the string item to XlsxSST.
_SST.Add(sStringItem);
}
else
{
// Add the string items from here on.
bAddStringItem = true;
}
// Reset the string item.
sStringItem = "";
}
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == N_t)
{
// Skip phonetic string data.
if (sStringItem.Length == 0)
{
// Add to the string item.
sStringItem = reader.ReadElementContentAsString();
}
}
}
// Do not add the last string item unless we have read previous string items.
if (bAddStringItem)
{
// Add the string item to XlsxSST.
_SST.Add(sStringItem);
}
xmlFileStream.Dispose();
}
}
private void ReadWorkbook(Stream xmlFileStream)
{
sheets = new List<XlsxWorksheet>();
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == N_sheet)
{
sheets.Add(new XlsxWorksheet(
reader.GetAttribute(A_name),
int.Parse(reader.GetAttribute(A_sheetId)),
reader.GetAttribute(A_rid),
reader.GetAttribute(A_visibleState)));
}
}
xmlFileStream.Dispose();
}
}
private void ReadWorkbookRels(Stream xmlFileStream)
{
using (XmlReader reader = XmlReader.Create(xmlFileStream))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element && reader.LocalName == N_rel)
{
string rid = reader.GetAttribute(A_id);
for (int i = 0; i < sheets.Count; i++)
{
XlsxWorksheet tempSheet = sheets[i];
if (tempSheet.RID == rid)
{
tempSheet.Path = reader.GetAttribute(A_target);
sheets[i] = tempSheet;
break;
}
}
}
}
xmlFileStream.Dispose();
}
}
}
}
| |
/* ====================================================================
Copyright (C) 2004-2008 fyiReporting Software, LLC
Copyright (C) 2011 Peter Gill <peter@majorsilence.com>
This file is part of the fyiReporting RDL 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.
For additional information, email info@fyireporting.com or visit
the website www.fyiReporting.com.
*/
using System;
using System.Xml;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Text;
using System.Globalization;
using System.Reflection;
using RdlEngine.Resources;
namespace fyiReporting.RDL
{
///<summary>
/// Query representation against a data source. Holds the data at runtime.
///</summary>
[Serializable]
internal class Query : ReportLink
{
string _DataSourceName; // Name of the data source to execute the query against
DataSourceDefn _DataSourceDefn; // the data source object the DataSourceName references.
QueryCommandTypeEnum _QueryCommandType; // Indicates what type of query is contained in the CommandText
Expression _CommandText; // (string) The query to execute to obtain the data for the report
QueryParameters _QueryParameters; // A list of parameters that are passed to the data
// source as part of the query.
int _Timeout; // Number of seconds to allow the query to run before
// timing out. Must be >= 0; If omitted or zero; no timeout
int _RowLimit; // Number of rows to retrieve before stopping retrieval; 0 means no limit
IDictionary _Columns; // QueryColumn (when SQL)
internal Query(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_DataSourceName=null;
_QueryCommandType=QueryCommandTypeEnum.Text;
_CommandText=null;
_QueryParameters=null;
_Timeout=0;
_RowLimit=0;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "DataSourceName":
_DataSourceName = xNodeLoop.InnerText;
break;
case "CommandType":
_QueryCommandType = fyiReporting.RDL.QueryCommandType.GetStyle(xNodeLoop.InnerText, OwnerReport.rl);
break;
case "CommandText":
_CommandText = new Expression(r, this, xNodeLoop, ExpressionType.String);
break;
case "QueryParameters":
_QueryParameters = new QueryParameters(r, this, xNodeLoop);
break;
case "Timeout":
_Timeout = XmlUtil.Integer(xNodeLoop.InnerText);
break;
case "RowLimit": // Extension of RDL specification
_RowLimit = XmlUtil.Integer(xNodeLoop.InnerText);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown Query element '" + xNodeLoop.Name + "' ignored.");
break;
} // end of switch
} // end of foreach
// Resolve the data source name to the object
if (_DataSourceName == null)
{
r.rl.LogError(8, "DataSourceName element not specified for Query.");
return;
}
}
// Handle parsing of function in final pass
override internal void FinalPass()
{
if (_CommandText != null)
_CommandText.FinalPass();
if (_QueryParameters != null)
_QueryParameters.FinalPass();
// verify the data source
DataSourceDefn ds=null;
if (OwnerReport.DataSourcesDefn != null &&
OwnerReport.DataSourcesDefn.Items != null)
{
ds = OwnerReport.DataSourcesDefn[_DataSourceName];
}
if (ds == null)
{
OwnerReport.rl.LogError(8, "Query references unknown data source '" + _DataSourceName + "'");
return;
}
_DataSourceDefn = ds;
IDbConnection cnSQL = ds.SqlConnect(null);
if (cnSQL == null || _CommandText == null)
return;
// Treat this as a SQL statement
String sql = _CommandText.EvaluateString(null, null);
IDbCommand cmSQL=null;
IDataReader dr=null;
try
{
cmSQL = cnSQL.CreateCommand();
cmSQL.CommandText = AddParametersAsLiterals(null, cnSQL, sql, false);
if (this._QueryCommandType == QueryCommandTypeEnum.StoredProcedure)
cmSQL.CommandType = CommandType.StoredProcedure;
AddParameters(null, cnSQL, cmSQL, false);
dr = cmSQL.ExecuteReader(CommandBehavior.SchemaOnly);
if (dr.FieldCount < 10)
_Columns = new ListDictionary(); // Hashtable is overkill for small lists
else
_Columns = new Hashtable(dr.FieldCount);
for (int i=0; i < dr.FieldCount; i++)
{
QueryColumn qc = new QueryColumn(i, dr.GetName(i), Type.GetTypeCode(dr.GetFieldType(i)) );
try { _Columns.Add(qc.colName, qc); }
catch // name has already been added to list:
{ // According to the RDL spec SQL names are matched by Name not by relative
// position: this seems wrong to me and causes this problem; but
// user can fix by using "as" keyword to name columns in Select
// e.g. Select col as "col1", col as "col2" from tableA
OwnerReport.rl.LogError(8, String.Format("Column '{0}' is not uniquely defined within the SQL Select columns.", qc.colName));
}
}
}
catch (Exception e)
{
// Issue #35 - Kept the logging
OwnerReport.rl.LogError(4, "SQL Exception during report compilation: " + e.Message + "\r\nSQL: " + sql);
throw;
}
finally
{
if (cmSQL != null)
{
cmSQL.Dispose();
if (dr != null)
dr.Close();
}
}
return;
}
internal bool GetData(Report rpt, Fields flds, Filters f)
{
Rows uData = this.GetMyUserData(rpt);
if (uData != null)
{
this.SetMyData(rpt, uData);
return uData.Data == null || uData.Data.Count == 0 ? false : true;
}
// Treat this as a SQL statement
DataSourceDefn ds = _DataSourceDefn;
if (ds == null || _CommandText == null)
{
this.SetMyData(rpt, null);
return false;
}
IDbConnection cnSQL = ds.SqlConnect(rpt);
if (cnSQL == null)
{
this.SetMyData(rpt, null);
return false;
}
Rows _Data = new Rows(rpt, null,null,null); // no sorting and grouping at base data
String sql = _CommandText.EvaluateString(rpt, null);
IDbCommand cmSQL=null;
IDataReader dr=null;
try
{
cmSQL = cnSQL.CreateCommand();
cmSQL.CommandText = AddParametersAsLiterals(rpt, cnSQL, sql, true);
if (this._QueryCommandType == QueryCommandTypeEnum.StoredProcedure)
cmSQL.CommandType = CommandType.StoredProcedure;
if (this._Timeout > 0)
cmSQL.CommandTimeout = this._Timeout;
AddParameters(rpt, cnSQL, cmSQL, true);
dr = cmSQL.ExecuteReader(CommandBehavior.SingleResult);
List<Row> ar = new List<Row>();
_Data.Data = ar;
int rowCount=0;
int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue;
int fieldCount = flds.Items.Count;
// Determine the query column number for each field
int[] qcn = new int[flds.Items.Count];
foreach (Field fld in flds)
{
qcn[fld.ColumnNumber] = -1;
if (fld.Value != null)
continue;
try
{
qcn[fld.ColumnNumber] = dr.GetOrdinal(fld.DataField);
}
catch
{
qcn[fld.ColumnNumber] = -1;
}
}
while (dr.Read())
{
Row or = new Row(_Data, fieldCount);
foreach (Field fld in flds)
{
if (qcn[fld.ColumnNumber] != -1)
{
or.Data[fld.ColumnNumber] = dr.GetValue(qcn[fld.ColumnNumber]);
}
}
// Apply the filters
if (f == null || f.Apply(rpt, or))
{
or.RowNumber = rowCount; //
rowCount++;
ar.Add(or);
}
if (--maxRows <= 0) // don't retrieve more than max
break;
}
ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows
if (f != null)
f.ApplyFinalFilters(rpt, _Data, false);
//#if DEBUG
// rpt.rl.LogError(4, "Rows Read:" + ar.Count.ToString() + " SQL:" + sql );
//#endif
}
catch (Exception e)
{
// Issue #35 - Kept the logging
rpt.rl.LogError(8, "SQL Exception" + e.Message + "\r\n" + e.StackTrace);
throw;
}
finally
{
if (cmSQL != null)
{
cmSQL.Dispose();
if (dr != null)
dr.Close();
}
}
this.SetMyData(rpt, _Data);
return _Data == null || _Data.Data == null || _Data.Data.Count == 0 ? false : true;
}
// Obtain the data from the XML
internal bool GetData(Report rpt, string xmlData, Fields flds, Filters f)
{
Rows uData = this.GetMyUserData(rpt);
if (uData != null)
{
this.SetMyData(rpt, uData);
return uData.Data == null || uData.Data.Count == 0? false: true;
}
int fieldCount = flds.Items.Count;
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = false;
doc.LoadXml(xmlData);
XmlNode xNode;
xNode = doc.LastChild;
if (xNode == null || !(xNode.Name == "Rows" || xNode.Name == "fyi:Rows"))
{
throw new Exception(Strings.Query_Error_XMLMustContainTopLevelRows);
}
Rows _Data = new Rows(rpt, null,null,null);
List<Row> ar = new List<Row>();
_Data.Data = ar;
int rowCount=0;
foreach(XmlNode xNodeRow in xNode.ChildNodes)
{
if (xNodeRow.NodeType != XmlNodeType.Element)
{
continue;
}
if (xNodeRow.Name != "Row")
{
continue;
}
Row or = new Row(_Data, fieldCount);
foreach (XmlNode xNodeColumn in xNodeRow.ChildNodes)
{
Field fld = (Field) (flds.Items[xNodeColumn.Name]); // Find the column
if (fld == null)
{
continue; // Extraneous data is ignored
}
TypeCode tc = fld.qColumn != null? fld.qColumn.colType: fld.Type;
if (xNodeColumn.InnerText == null || xNodeColumn.InnerText.Length == 0)
{
or.Data[fld.ColumnNumber] = null;
}
else if (tc == TypeCode.String)
{
or.Data[fld.ColumnNumber] = xNodeColumn.InnerText;
}
else if (tc == TypeCode.DateTime)
{
try
{
or.Data[fld.ColumnNumber] =
Convert.ToDateTime(xNodeColumn.InnerText,
System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
catch // all conversion errors result in a null value
{
or.Data[fld.ColumnNumber] = null;
}
}
else
{
try
{
or.Data[fld.ColumnNumber] =
Convert.ChangeType(xNodeColumn.InnerText, tc, NumberFormatInfo.InvariantInfo);
}
catch // all conversion errors result in a null value
{
or.Data[fld.ColumnNumber] = null;
}
}
}
// Apply the filters
if (f == null || f.Apply(rpt, or))
{
or.RowNumber = rowCount; //
rowCount++;
ar.Add(or);
}
}
ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows
if (f != null)
{
f.ApplyFinalFilters(rpt, _Data, false);
}
SetMyData(rpt, _Data);
return _Data == null || _Data.Data == null || _Data.Data.Count == 0 ? false : true;
}
internal void SetData(Report rpt, IEnumerable ie, Fields flds, Filters f)
{
if (ie == null) // Does user want to remove user data?
{
SetMyUserData(rpt, null);
return;
}
Rows rows = new Rows(rpt, null,null,null); // no sorting and grouping at base data
List<Row> ar = new List<Row>();
rows.Data = ar;
int rowCount=0;
int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue;
int fieldCount = flds.Items.Count;
foreach (object dt in ie)
{
// Get the type.
Type myType = dt.GetType();
// Build the row
Row or = new Row(rows, fieldCount);
// Go thru each field and try to obtain a value
foreach (Field fld in flds)
{
// Get the type and fields of FieldInfoClass.
FieldInfo fi = myType.GetField(fld.Name.Nm, BindingFlags.Instance | BindingFlags.Public);
if (fi != null)
{
or.Data[fld.ColumnNumber] = fi.GetValue(dt);
}
else
{
// Try getting it as a property as well
PropertyInfo pi = myType.GetProperty(fld.Name.Nm, BindingFlags.Instance | BindingFlags.Public);
if (pi != null)
{
or.Data[fld.ColumnNumber] = pi.GetValue(dt, null);
}
}
}
// Apply the filters
if (f == null || f.Apply(rpt, or))
{
or.RowNumber = rowCount; //
rowCount++;
ar.Add(or);
}
if (--maxRows <= 0) // don't retrieve more than max
break;
}
ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows
if (f != null)
f.ApplyFinalFilters(rpt, rows, false);
SetMyUserData(rpt, rows);
}
internal void SetData(Report rpt, IDataReader dr, Fields flds, Filters f)
{
if (dr == null) // Does user want to remove user data?
{
SetMyUserData(rpt, null);
return;
}
Rows rows = new Rows(rpt,null,null,null); // no sorting and grouping at base data
List<Row> ar = new List<Row>();
rows.Data = ar;
int rowCount=0;
int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue;
while (dr.Read())
{
Row or = new Row(rows, dr.FieldCount);
dr.GetValues(or.Data);
// Apply the filters
if (f == null || f.Apply(rpt, or))
{
or.RowNumber = rowCount; //
rowCount++;
ar.Add(or);
}
if (--maxRows <= 0) // don't retrieve more than max
break;
}
ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows
if (f != null)
f.ApplyFinalFilters(rpt, rows, false);
SetMyUserData(rpt, rows);
}
internal void SetData(Report rpt, DataTable dt, Fields flds, Filters f)
{
if (dt == null) // Does user want to remove user data?
{
SetMyUserData(rpt, null);
return;
}
Rows rows = new Rows(rpt,null,null,null); // no sorting and grouping at base data
List<Row> ar = new List<Row>();
rows.Data = ar;
int rowCount=0;
int maxRows = _RowLimit > 0? _RowLimit: int.MaxValue;
int fieldCount = flds.Items.Count;
foreach (DataRow dr in dt.Rows)
{
Row or = new Row(rows, fieldCount);
// Loop thru the columns obtaining the data values by name
foreach (Field fld in flds.Items.Values)
{
or.Data[fld.ColumnNumber] = dr[fld.DataField];
}
// Apply the filters
if (f == null || f.Apply(rpt, or))
{
or.RowNumber = rowCount; //
rowCount++;
ar.Add(or);
}
if (--maxRows <= 0) // don't retrieve more than max
break;
}
ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows
if (f != null)
f.ApplyFinalFilters(rpt, rows, false);
SetMyUserData(rpt, rows);
}
internal void SetData(Report rpt, XmlDocument xmlDoc, Fields flds, Filters f)
{
if (xmlDoc == null) // Does user want to remove user data?
{
SetMyUserData(rpt, null);
return;
}
Rows rows = new Rows(rpt,null,null,null); // no sorting and grouping at base data
XmlNode xNode;
xNode = xmlDoc.LastChild;
if (xNode == null || !(xNode.Name == "Rows" || xNode.Name == "fyi:Rows"))
{
throw new Exception(Strings.Query_Error_XMLMustContainTopLevelRows);
}
List<Row> ar = new List<Row>();
rows.Data = ar;
int rowCount=0;
int fieldCount = flds.Items.Count;
foreach(XmlNode xNodeRow in xNode.ChildNodes)
{
if (xNodeRow.NodeType != XmlNodeType.Element)
continue;
if (xNodeRow.Name != "Row")
continue;
Row or = new Row(rows, fieldCount);
foreach (XmlNode xNodeColumn in xNodeRow.ChildNodes)
{
Field fld = (Field) (flds.Items[xNodeColumn.Name]); // Find the column
if (fld == null)
continue; // Extraneous data is ignored
if (xNodeColumn.InnerText == null || xNodeColumn.InnerText.Length == 0)
or.Data[fld.ColumnNumber] = null;
else if (fld.Type == TypeCode.String)
or.Data[fld.ColumnNumber] = xNodeColumn.InnerText;
else
{
try
{
or.Data[fld.ColumnNumber] =
Convert.ChangeType(xNodeColumn.InnerText, fld.Type, NumberFormatInfo.InvariantInfo);
}
catch // all conversion errors result in a null value
{
or.Data[fld.ColumnNumber] = null;
}
}
}
// Apply the filters
if (f == null || f.Apply(rpt, or))
{
or.RowNumber = rowCount; //
rowCount++;
ar.Add(or);
}
}
ar.TrimExcess(); // free up any extraneous space; can be sizeable for large # rows
if (f != null)
f.ApplyFinalFilters(rpt, rows, false);
SetMyUserData(rpt, rows);
}
private void AddParameters(Report rpt, IDbConnection cn, IDbCommand cmSQL, bool bValue)
{
// any parameters to substitute
if (this._QueryParameters == null ||
this._QueryParameters.Items == null ||
this._QueryParameters.Items.Count == 0 ||
this._QueryParameters.ContainsArray) // arrays get handled by AddParametersAsLiterals
return;
// AddParametersAsLiterals handles it when there is replacement
if (RdlEngineConfig.DoParameterReplacement(Provider, cn))
return;
foreach(QueryParameter qp in this._QueryParameters.Items)
{
string paramName;
// force the name to start with @
if (qp.Name.Nm[0] == '@')
paramName = qp.Name.Nm;
else
paramName = "@" + qp.Name.Nm;
object pvalue= bValue? qp.Value.Evaluate(rpt, null): null;
IDbDataParameter dp = cmSQL.CreateParameter();
dp.ParameterName = paramName;
if (pvalue is ArrayList) // Probably a MultiValue Report parameter result
{
ArrayList ar = (ArrayList) pvalue;
dp.Value = ar.ToArray(ar[0].GetType());
}
else
dp.Value = pvalue;
cmSQL.Parameters.Add(dp);
}
}
private string AddParametersAsLiterals(Report rpt, IDbConnection cn, string sql, bool bValue)
{
// No parameters means nothing to do
if (this._QueryParameters == null ||
this._QueryParameters.Items == null ||
this._QueryParameters.Items.Count == 0)
return sql;
// Only do this for ODBC datasources - AddParameters handles it in other cases
if (!RdlEngineConfig.DoParameterReplacement(Provider, cn))
{
if (!_QueryParameters.ContainsArray) // when array we do substitution
return sql;
}
StringBuilder sb = new StringBuilder(sql);
List<QueryParameter> qlist;
if (_QueryParameters.Items.Count <= 1)
qlist = _QueryParameters.Items;
else
{ // need to sort the list so that longer items are first in the list
// otherwise substitution could be done incorrectly
qlist = new List<QueryParameter>(_QueryParameters.Items);
qlist.Sort();
}
foreach(QueryParameter qp in qlist)
{
string paramName;
// force the name to start with @
if (qp.Name.Nm[0] == '@')
paramName = qp.Name.Nm;
else
paramName = "@" + qp.Name.Nm;
// build the replacement value
string svalue;
if (bValue)
{ // use the value provided
svalue = this.ParameterValue(rpt, qp);
}
else
{ // just need a place holder value that will pass parsing
switch (qp.Value.Expr.GetTypeCode())
{
case TypeCode.Char:
svalue = "' '";
break;
case TypeCode.DateTime:
svalue = "'1900-01-01 00:00:00'";
break;
case TypeCode.Decimal:
case TypeCode.Double:
case TypeCode.Int32:
case TypeCode.Int64:
svalue = "0";
break;
case TypeCode.Boolean:
svalue = "'false'";
break;
case TypeCode.String:
default:
svalue = "' '";
break;
}
}
sb.Replace(paramName, svalue);
}
return sb.ToString();
}
private string ParameterValue(Report rpt, QueryParameter qp)
{
if (!qp.IsArray)
{
// handle non-array
string svalue = qp.Value.EvaluateString(rpt, null);
if (svalue == null)
svalue = "null";
else switch (qp.Value.Expr.GetTypeCode())
{
case TypeCode.Char:
case TypeCode.DateTime:
case TypeCode.String:
// need to double up on "'" and then surround by '
svalue = svalue.Replace("'", "''");
svalue = "'" + svalue + "'";
break;
}
return svalue;
}
StringBuilder sb = new StringBuilder();
ArrayList ar = qp.Value.Evaluate(rpt, null) as ArrayList;
if (ar == null)
return null;
bool bFirst = true;
foreach (object v in ar)
{
if (!bFirst)
sb.Append(", ");
if (v == null)
{
sb.Append("null");
}
else
{
string sv = v.ToString();
if (v is string || v is char || v is DateTime)
{
// need to double up on "'" and then surround by '
sv = sv.Replace("'", "''");
sb.Append("'");
sb.Append(sv);
sb.Append("'");
}
else
sb.Append(sv);
}
bFirst = false;
}
return sb.ToString();
}
private string Provider
{
get
{
if (this.DataSourceDefn == null ||
this.DataSourceDefn.ConnectionProperties == null)
return "";
return this.DataSourceDefn.ConnectionProperties.DataProvider;
}
}
internal string DataSourceName
{
get { return _DataSourceName; }
}
internal DataSourceDefn DataSourceDefn
{
get { return _DataSourceDefn; }
}
internal QueryCommandTypeEnum QueryCommandType
{
get { return _QueryCommandType; }
set { _QueryCommandType = value; }
}
internal Expression CommandText
{
get { return _CommandText; }
set { _CommandText = value; }
}
internal QueryParameters QueryParameters
{
get { return _QueryParameters; }
set { _QueryParameters = value; }
}
internal int Timeout
{
get { return _Timeout; }
set { _Timeout = value; }
}
internal IDictionary Columns
{
get { return _Columns; }
}
// Runtime data
internal Rows GetMyData(Report rpt)
{
return rpt.Cache.Get(this, "data") as Rows;
}
private void SetMyData(Report rpt, Rows data)
{
if (data == null)
{
rpt.Cache.Remove(this, "data");
}
else
{
rpt.Cache.AddReplace(this, "data", data);
}
}
private Rows GetMyUserData(Report rpt)
{
return rpt.Cache.Get(this, "userdata") as Rows;
}
private void SetMyUserData(Report rpt, Rows data)
{
if (data == null)
{
rpt.Cache.Remove(this, "userdata");
}
else
{
rpt.Cache.AddReplace(this, "userdata", data);
}
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.SignatureHelp;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
public GenericNamePartiallyWrittenSignatureHelpProviderTests(CSharpTestWorkspaceFixture workspaceFixture) : base(workspaceFixture)
{
}
internal override ISignatureHelpProvider CreateSignatureHelpProvider()
{
return new GenericNamePartiallyWrittenSignatureHelpProvider();
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedGenericUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Foo()
{
G<G<int>$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task DeclaringGenericTypeWith1ParameterUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Foo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task CallingGenericAsyncMethod()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void Main(string[] args)
{
Foo<$$
}
Task<int> Foo<T>()
{
return Foo<T>();
}
}
";
var documentation = $@"
{WorkspacesResources.Usage_colon}
int x = await Foo();";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task<int> Program.Foo<T>()", documentation, string.Empty, currentParameterIndex: 0));
// TODO: Enable the script case when we have support for extension methods in scripts
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Foo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C().Foo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Foo<T>(T x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Foo<T, U>(T x, U y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Foo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task GenericExtensionMethod()
{
var markup = @"
interface IFoo
{
void Bar<T>();
}
static class FooExtensions
{
public static void Bar<T1, T2>(this IFoo foo) { }
}
class Program
{
static void Main()
{
IFoo f = null;
f.[|Bar<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IFoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IFoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokingGenericMethodWith1ParameterUnterminated()
{
var markup = @"
class C
{
/// <summary>
/// Method Foo
/// </summary>
/// <typeparam name=""T"">Method type parameter</typeparam>
void Foo<T>() { }
void Bar()
{
[|Foo<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Foo<T>()",
"Method Foo", "Method type parameter", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerBracket()
{
var markup = @"
class G<S, T> { };
class C
{
void Foo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class G<S, T> { };
class C
{
void Foo()
{
[|G<int,$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// foo<$$";
await TestAsync(markup);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Numerics.Tests
{
public class logTest
{
private static int s_samples = 10;
private static Random s_random = new Random(100);
[Fact]
public static void RunLogTests()
{
byte[] tempByteArray1 = new byte[0];
byte[] tempByteArray2 = new byte[0];
BigInteger bi;
// Log Method - Log(1,+Infinity)
Assert.Equal(0, BigInteger.Log(1, Double.PositiveInfinity));
// Log Method - Log(1,0)
VerifyLogString("0 1 bLog");
// Log Method - Log(0, >1)
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 10);
VerifyLogString(Print(tempByteArray1) + "0 bLog");
}
// Log Method - Log(0, 0>x>1)
for (int i = 0; i < s_samples; i++)
{
Assert.Equal(Double.PositiveInfinity, BigInteger.Log(0, s_random.NextDouble()));
}
// Log Method - base = 0
for (int i = 0; i < s_samples; i++)
{
bi = 1;
while (bi == 1)
{
bi = new BigInteger(GetRandomPosByteArray(s_random, 8));
}
Assert.True((Double.IsNaN(BigInteger.Log(bi, 0))));
}
// Log Method - base = 1
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random);
VerifyLogString("1 " + Print(tempByteArray1) + "bLog");
}
// Log Method - base = NaN
for (int i = 0; i < s_samples; i++)
{
Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.NaN)));
}
// Log Method - base = +Infinity
for (int i = 0; i < s_samples; i++)
{
Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), Double.PositiveInfinity)));
}
// Log Method - Log(0,1)
VerifyLogString("1 0 bLog");
// Log Method - base < 0
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomByteArray(s_random, 10);
tempByteArray2 = GetRandomNegByteArray(s_random, 1);
VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog");
Assert.True(Double.IsNaN(BigInteger.Log(new BigInteger(GetRandomByteArray(s_random, 10)), -s_random.NextDouble())));
}
// Log Method - value < 0
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomNegByteArray(s_random, 10);
tempByteArray2 = GetRandomPosByteArray(s_random, 1);
VerifyLogString(Print(tempByteArray2) + Print(tempByteArray1) + "bLog");
}
// Log Method - Small BigInteger and 0<base<0.5
for (int i = 0; i < s_samples; i++)
{
BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, 10));
Double newbase = Math.Min(s_random.NextDouble(), 0.5);
Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase)));
}
// Log Method - Large BigInteger and 0<base<0.5
for (int i = 0; i < s_samples; i++)
{
BigInteger temp = new BigInteger(GetRandomPosByteArray(s_random, s_random.Next(1, 100)));
Double newbase = Math.Min(s_random.NextDouble(), 0.5);
Assert.True(ApproxEqual(BigInteger.Log(temp, newbase), Math.Log((double)temp, newbase)));
}
// Log Method - two small BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 2);
tempByteArray2 = GetRandomPosByteArray(s_random, 3);
VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog");
}
// Log Method - one small and one large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, 1);
tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100));
VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog");
}
// Log Method - two large BigIntegers
for (int i = 0; i < s_samples; i++)
{
tempByteArray1 = GetRandomPosByteArray(s_random, s_random.Next(1, 100));
tempByteArray2 = GetRandomPosByteArray(s_random, s_random.Next(1, 100));
VerifyLogString(Print(tempByteArray1) + Print(tempByteArray2) + "bLog");
}
}
private static void VerifyLogString(string opstring)
{
StackCalc sc = new StackCalc(opstring);
while (sc.DoNextOperation())
{
Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString());
}
}
private static void VerifyIdentityString(string opstring1, string opstring2)
{
StackCalc sc1 = new StackCalc(opstring1);
while (sc1.DoNextOperation())
{
//Run the full calculation
sc1.DoNextOperation();
}
StackCalc sc2 = new StackCalc(opstring2);
while (sc2.DoNextOperation())
{
//Run the full calculation
sc2.DoNextOperation();
}
Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString());
}
private static byte[] GetRandomByteArray(Random random)
{
return GetRandomByteArray(random, random.Next(0, 100));
}
private static byte[] GetRandomByteArray(Random random, int size)
{
return MyBigIntImp.GetRandomByteArray(random, size);
}
private static Byte[] GetRandomPosByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; i++)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] &= 0x7F;
return value;
}
private static Byte[] GetRandomNegByteArray(Random random, int size)
{
byte[] value = new byte[size];
for (int i = 0; i < value.Length; ++i)
{
value[i] = (byte)random.Next(0, 256);
}
value[value.Length - 1] |= 0x80;
return value;
}
private static String Print(byte[] bytes)
{
return MyBigIntImp.Print(bytes);
}
private static bool ApproxEqual(double value1, double value2)
{
//Special case values;
if (Double.IsNaN(value1))
{
return Double.IsNaN(value2);
}
if (Double.IsNegativeInfinity(value1))
{
return Double.IsNegativeInfinity(value2);
}
if (Double.IsPositiveInfinity(value1))
{
return Double.IsPositiveInfinity(value2);
}
if (value2 == 0)
{
return (value1 == 0);
}
double result = Math.Abs((value1 / value2) - 1);
return (result <= Double.Parse("1e-15"));
}
}
}
| |
using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using System.Configuration;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using Csla.Validation;
namespace Northwind.CSLA.Library
{
/// <summary>
/// Region Generated by MyGeneration using the CSLA Object Mapping template
/// </summary>
[Serializable()]
[TypeConverter(typeof(RegionConverter))]
public partial class Region : BusinessBase<Region>, IDisposable, IVEHasBrokenRules
{
#region Refresh
private List<Region> _RefreshRegions = new List<Region>();
private List<RegionTerritory> _RefreshRegionTerritories = new List<RegionTerritory>();
private void AddToRefreshList(List<Region> refreshRegions, List<RegionTerritory> refreshRegionTerritories)
{
if (IsDirty)
refreshRegions.Add(this);
if (_RegionTerritories != null && _RegionTerritories.IsDirty)
{
foreach (RegionTerritory tmp in _RegionTerritories)
{
if(tmp.IsDirty)refreshRegionTerritories.Add(tmp);
}
}
}
private void BuildRefreshList()
{
_RefreshRegions = new List<Region>();
_RefreshRegionTerritories = new List<RegionTerritory>();
AddToRefreshList(_RefreshRegions, _RefreshRegionTerritories);
}
private void ProcessRefreshList()
{
foreach (Region tmp in _RefreshRegions)
{
RegionInfo.Refresh(tmp);
}
foreach (RegionTerritory tmp in _RefreshRegionTerritories)
{
TerritoryInfo.Refresh(tmp);
}
}
#endregion
#region Collection
protected static List<Region> _AllList = new List<Region>();
private static Dictionary<string, Region> _AllByPrimaryKey = new Dictionary<string, Region>();
private static void ConvertListToDictionary()
{
List<Region> remove = new List<Region>();
foreach (Region tmp in _AllList)
{
_AllByPrimaryKey[tmp.RegionID.ToString()]=tmp; // Primary Key
remove.Add(tmp);
}
foreach (Region tmp in remove)
_AllList.Remove(tmp);
}
public static Region GetExistingByPrimaryKey(int regionID)
{
ConvertListToDictionary();
string key = regionID.ToString();
if (_AllByPrimaryKey.ContainsKey(key)) return _AllByPrimaryKey[key];
return null;
}
#endregion
#region Business Methods
private string _ErrorMessage = string.Empty;
public string ErrorMessage
{
get { return _ErrorMessage; }
}
private int _RegionID;
[System.ComponentModel.DataObjectField(true, true)]
public int RegionID
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _RegionID;
}
}
private string _RegionDescription = string.Empty;
public string RegionDescription
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _RegionDescription;
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
set
{
CanWriteProperty(true);
if (value == null) value = string.Empty;
if (_RegionDescription != value)
{
_RegionDescription = value;
PropertyHasChanged();
}
}
}
private int _RegionTerritoryCount = 0;
/// <summary>
/// Count of RegionTerritories for this Region
/// </summary>
public int RegionTerritoryCount
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
return _RegionTerritoryCount;
}
}
private RegionTerritories _RegionTerritories = null;
/// <summary>
/// Related Field
/// </summary>
[TypeConverter(typeof(RegionTerritoriesConverter))]
public RegionTerritories RegionTerritories
{
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
get
{
CanReadProperty(true);
if(_RegionTerritoryCount > 0 && _RegionTerritories == null)
_RegionTerritories = RegionTerritories.GetByRegionID(RegionID);
else if(_RegionTerritories == null)
_RegionTerritories = RegionTerritories.New();
return _RegionTerritories;
}
}
public override bool IsDirty
{
get { return base.IsDirty || (_RegionTerritories == null? false : _RegionTerritories.IsDirty); }
}
public override bool IsValid
{
get { return (IsNew && !IsDirty ? true : base.IsValid) && (_RegionTerritories == null? true : _RegionTerritories.IsValid); }
}
// TODO: Replace base Region.ToString function as necessary
/// <summary>
/// Overrides Base ToString
/// </summary>
/// <returns>A string representation of current Region</returns>
//public override string ToString()
//{
// return base.ToString();
//}
// TODO: Check Region.GetIdValue to assure that the ID returned is unique
/// <summary>
/// Overrides Base GetIdValue - Used internally by CSLA to determine equality
/// </summary>
/// <returns>A Unique ID for the current Region</returns>
protected override object GetIdValue()
{
return _RegionID;
}
#endregion
#region ValidationRules
[NonSerialized]
private bool _CheckingBrokenRules=false;
public IVEHasBrokenRules HasBrokenRules
{
get {
if(_CheckingBrokenRules)return null;
if ((IsDirty || !IsNew) && BrokenRulesCollection.Count > 0) return this;
try
{
_CheckingBrokenRules=true;
IVEHasBrokenRules hasBrokenRules = null;
if (_RegionTerritories != null && (hasBrokenRules = _RegionTerritories.HasBrokenRules) != null) return hasBrokenRules;
return hasBrokenRules;
}
finally
{
_CheckingBrokenRules=false;
}
}
}
public BrokenRulesCollection BrokenRules
{
get
{
IVEHasBrokenRules hasBrokenRules = HasBrokenRules;
if (this.Equals(hasBrokenRules)) return BrokenRulesCollection;
return (hasBrokenRules != null ? hasBrokenRules.BrokenRules : null);
}
}
protected override void AddBusinessRules()
{
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringRequired, "RegionDescription");
ValidationRules.AddRule(
Csla.Validation.CommonRules.StringMaxLength,
new Csla.Validation.CommonRules.MaxLengthRuleArgs("RegionDescription", 50));
//ValidationRules.AddDependantProperty("x", "y");
_RegionExtension.AddValidationRules(ValidationRules);
// TODO: Add other validation rules
}
protected override void AddInstanceBusinessRules()
{
_RegionExtension.AddInstanceValidationRules(ValidationRules);
// TODO: Add other validation rules
}
// Sample data comparison validation rule
//private bool StartDateGTEndDate(object target, Csla.Validation.RuleArgs e)
//{
// if (_started > _ended)
// {
// e.Description = "Start date can't be after end date";
// return false;
// }
// else
// return true;
//}
#endregion
#region Authorization Rules
protected override void AddAuthorizationRules()
{
//TODO: Who can read/write which fields
//AuthorizationRules.AllowRead(RegionID, "<Role(s)>");
//AuthorizationRules.AllowRead(RegionDescription, "<Role(s)>");
//AuthorizationRules.AllowWrite(RegionDescription, "<Role(s)>");
_RegionExtension.AddAuthorizationRules(AuthorizationRules);
}
protected override void AddInstanceAuthorizationRules()
{
//TODO: Who can read/write which fields
_RegionExtension.AddInstanceAuthorizationRules(AuthorizationRules);
}
public static bool CanAddObject()
{
// TODO: Can Add Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
public static bool CanGetObject()
{
// TODO: CanGet Authorization
return true;
}
public static bool CanDeleteObject()
{
// TODO: CanDelete Authorization
//bool result = false;
//if (Csla.ApplicationContext.User.IsInRole("ProjectManager"))result = true;
//if (Csla.ApplicationContext.User.IsInRole("Administrator"))result = true;
//return result;
return true;
}
public static bool CanEditObject()
{
// TODO: CanEdit Authorization
//return Csla.ApplicationContext.User.IsInRole("ProjectManager");
return true;
}
#endregion
#region Factory Methods
public int CurrentEditLevel
{ get { return EditLevel; } }
protected Region()
{/* require use of factory methods */
_AllList.Add(this);
}
public void Dispose()
{
_AllList.Remove(this);
_AllByPrimaryKey.Remove(RegionID.ToString());
}
public static Region New()
{
if (!CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Region");
try
{
return DataPortal.Create<Region>();
}
catch (Exception ex)
{
throw new DbCslaException("Error on Region.New", ex);
}
}
public static Region New(int regionID, string regionDescription)
{
Region tmp = Region.New();
tmp._RegionID = regionID;
tmp.RegionDescription = regionDescription;
return tmp;
}
public static Region MakeRegion(int regionID, string regionDescription)
{
Region tmp = Region.New(regionID, regionDescription);
if (tmp.IsSavable)
tmp = tmp.Save();
else
{
Csla.Validation.BrokenRulesCollection brc = tmp.ValidationRules.GetBrokenRules();
tmp._ErrorMessage = "Failed Validation:";
foreach (Csla.Validation.BrokenRule br in brc)
{
tmp._ErrorMessage += "\r\n\tFailure: " + br.RuleName;
}
}
return tmp;
}
public static Region Get(int regionID)
{
if (!CanGetObject())
throw new System.Security.SecurityException("User not authorized to view a Region");
try
{
Region tmp = GetExistingByPrimaryKey(regionID);
if (tmp == null)
{
tmp = DataPortal.Fetch<Region>(new PKCriteria(regionID));
_AllList.Add(tmp);
}
if (tmp.ErrorMessage == "No Record Found") tmp = null;
return tmp;
}
catch (Exception ex)
{
throw new DbCslaException("Error on Region.Get", ex);
}
}
public static Region Get(SafeDataReader dr)
{
if (dr.Read()) return new Region(dr);
return null;
}
internal Region(SafeDataReader dr)
{
ReadData(dr);
}
public static void Delete(int regionID)
{
if (!CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Region");
try
{
DataPortal.Delete(new PKCriteria(regionID));
}
catch (Exception ex)
{
throw new DbCslaException("Error on Region.Delete", ex);
}
}
public override Region Save()
{
if (IsDeleted && !CanDeleteObject())
throw new System.Security.SecurityException("User not authorized to remove a Region");
else if (IsNew && !CanAddObject())
throw new System.Security.SecurityException("User not authorized to add a Region");
else if (!CanEditObject())
throw new System.Security.SecurityException("User not authorized to update a Region");
try
{
BuildRefreshList();
Region region = base.Save();
_AllList.Add(region);//Refresh the item in AllList
ProcessRefreshList();
return region;
}
catch (Exception ex)
{
throw new DbCslaException("Error on CSLA Save", ex);
}
}
#endregion
#region Data Access Portal
[Serializable()]
protected class PKCriteria
{
private int _RegionID;
public int RegionID
{ get { return _RegionID; } }
public PKCriteria(int regionID)
{
_RegionID = regionID;
}
}
// TODO: If Create needs to access DB - It should not be marked RunLocal
[RunLocal()]
private new void DataPortal_Create()
{
// Database Defaults
// TODO: Add any defaults that are necessary
ValidationRules.CheckRules();
}
private void ReadData(SafeDataReader dr)
{
Database.LogInfo("Region.ReadData", GetHashCode());
try
{
_RegionID = dr.GetInt32("RegionID");
_RegionDescription = dr.GetString("RegionDescription");
_RegionTerritoryCount = dr.GetInt32("TerritoryCount");
MarkOld();
}
catch (Exception ex)
{
Database.LogException("Region.ReadData", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Region.ReadData", ex);
}
}
private void DataPortal_Fetch(PKCriteria criteria)
{
Database.LogInfo("Region.DataPortal_Fetch", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
ApplicationContext.LocalContext["cn"] = cn;
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "getRegion";
cm.Parameters.AddWithValue("@RegionID", criteria.RegionID);
using (SafeDataReader dr = new SafeDataReader(cm.ExecuteReader()))
{
if (!dr.Read())
{
_ErrorMessage = "No Record Found";
return;
}
ReadData(dr);
// load child objects
dr.NextResult();
_RegionTerritories = RegionTerritories.Get(dr);
}
}
// removing of item only needed for local data portal
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
ApplicationContext.LocalContext.Remove("cn");
}
}
catch (Exception ex)
{
Database.LogException("Region.DataPortal_Fetch", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Region.DataPortal_Fetch", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Insert()
{
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
ApplicationContext.LocalContext["cn"] = cn;
SQLInsert();
// removing of item only needed for local data portal
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
ApplicationContext.LocalContext.Remove("cn");
}
}
catch (Exception ex)
{
Database.LogException("Region.DataPortal_Insert", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Region.DataPortal_Insert", ex);
}
finally
{
Database.LogInfo("Region.DataPortal_Insert", GetHashCode());
}
}
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLInsert()
{
if (!this.IsDirty) return;
try
{
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "addRegion";
// Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@RegionID", _RegionID);
cm.Parameters.AddWithValue("@RegionDescription", _RegionDescription);
// Output Calculated Columns
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
}
MarkOld();
// update child objects
if (_RegionTerritories != null) _RegionTerritories.Update(this);
Database.LogInfo("Region.SQLInsert", GetHashCode());
}
catch (Exception ex)
{
Database.LogException("Region.SQLInsert", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Region.SQLInsert", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
public static void Add(SqlConnection cn, int regionID, string regionDescription)
{
Database.LogInfo("Region.Add", 0);
try
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "addRegion";
// Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@RegionID", regionID);
cm.Parameters.AddWithValue("@RegionDescription", regionDescription);
// Output Calculated Columns
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
// No Timestamp value to return
}
}
catch (Exception ex)
{
Database.LogException("Region.Add", ex);
throw new DbCslaException("Region.Add", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_Update()
{
if (!IsDirty) return; // If not dirty - nothing to do
Database.LogInfo("Region.DataPortal_Update", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
ApplicationContext.LocalContext["cn"] = cn;
SQLUpdate();
// removing of item only needed for local data portal
if (ApplicationContext.ExecutionLocation == ApplicationContext.ExecutionLocations.Client)
ApplicationContext.LocalContext.Remove("cn");
}
}
catch (Exception ex)
{
Database.LogException("Region.DataPortal_Update", ex);
_ErrorMessage = ex.Message;
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
}
}
[Transactional(TransactionalTypes.TransactionScope)]
internal void SQLUpdate()
{
if (!IsDirty) return; // If not dirty - nothing to do
Database.LogInfo("Region.SQLUpdate", GetHashCode());
try
{
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
if (base.IsDirty)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "updateRegion";
// All Fields including Calculated Fields
cm.Parameters.AddWithValue("@RegionID", _RegionID);
cm.Parameters.AddWithValue("@RegionDescription", _RegionDescription);
// Output Calculated Columns
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
}
}
MarkOld();
// use the open connection to update child objects
if (_RegionTerritories != null) _RegionTerritories.Update(this);
}
catch (Exception ex)
{
Database.LogException("Region.SQLUpdate", ex);
_ErrorMessage = ex.Message;
if (!ex.Message.EndsWith("has been edited by another user.")) throw ex;
}
}
internal void Update()
{
if (!this.IsDirty) return;
if (base.IsDirty)
{
SqlConnection cn = (SqlConnection)ApplicationContext.LocalContext["cn"];
if (IsNew)
Region.Add(cn, _RegionID, _RegionDescription);
else
Region.Update(cn, _RegionID, _RegionDescription);
MarkOld();
}
if (_RegionTerritories != null) _RegionTerritories.Update(this);
}
[Transactional(TransactionalTypes.TransactionScope)]
public static void Update(SqlConnection cn, int regionID, string regionDescription)
{
Database.LogInfo("Region.Update", 0);
try
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "updateRegion";
// Input All Fields - Except Calculated Columns
cm.Parameters.AddWithValue("@RegionID", regionID);
cm.Parameters.AddWithValue("@RegionDescription", regionDescription);
// Output Calculated Columns
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
// Save all values being returned from the Procedure
// No Timestamp value to return
}
}
catch (Exception ex)
{
Database.LogException("Region.Update", ex);
throw new DbCslaException("Region.Update", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
protected override void DataPortal_DeleteSelf()
{
DataPortal_Delete(new PKCriteria(_RegionID));
}
[Transactional(TransactionalTypes.TransactionScope)]
private void DataPortal_Delete(PKCriteria criteria)
{
Database.LogInfo("Region.DataPortal_Delete", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "deleteRegion";
cm.Parameters.AddWithValue("@RegionID", criteria.RegionID);
cm.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Database.LogException("Region.DataPortal_Delete", ex);
_ErrorMessage = ex.Message;
throw new DbCslaException("Region.DataPortal_Delete", ex);
}
}
[Transactional(TransactionalTypes.TransactionScope)]
public static void Remove(SqlConnection cn, int regionID)
{
Database.LogInfo("Region.Remove", 0);
try
{
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "deleteRegion";
// Input PK Fields
cm.Parameters.AddWithValue("@RegionID", regionID);
// TODO: Define any additional output parameters
cm.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Database.LogException("Region.Remove", ex);
throw new DbCslaException("Region.Remove", ex);
}
}
#endregion
#region Exists
public static bool Exists(int regionID)
{
ExistsCommand result;
try
{
result = DataPortal.Execute<ExistsCommand>(new ExistsCommand(regionID));
return result.Exists;
}
catch (Exception ex)
{
throw new DbCslaException("Error on Region.Exists", ex);
}
}
[Serializable()]
private class ExistsCommand : CommandBase
{
private int _RegionID;
private bool _exists;
public bool Exists
{
get { return _exists; }
}
public ExistsCommand(int regionID)
{
_RegionID = regionID;
}
protected override void DataPortal_Execute()
{
Database.LogInfo("Region.DataPortal_Execute", GetHashCode());
try
{
using (SqlConnection cn = Database.Northwind_SqlConnection)
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.StoredProcedure;
cm.CommandText = "existsRegion";
cm.Parameters.AddWithValue("@RegionID", _RegionID);
int count = (int)cm.ExecuteScalar();
_exists = (count > 0);
}
}
}
catch (Exception ex)
{
Database.LogException("Region.DataPortal_Execute", ex);
throw new DbCslaException("Region.DataPortal_Execute", ex);
}
}
}
#endregion
// Standard Default Code
#region extension
RegionExtension _RegionExtension = new RegionExtension();
[Serializable()]
partial class RegionExtension : extensionBase
{
}
[Serializable()]
class extensionBase
{
// Default Values
// Authorization Rules
public virtual void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Instance Authorization Rules
public virtual void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
{
// Needs to be overriden to add new authorization rules
}
// Validation Rules
public virtual void AddValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
// InstanceValidation Rules
public virtual void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
{
// Needs to be overriden to add new validation rules
}
}
#endregion
} // Class
#region Converter
internal class RegionConverter : ExpandableObjectConverter
{
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destType)
{
if (destType == typeof(string) && value is Region)
{
// Return the ToString value
return ((Region)value).ToString();
}
return base.ConvertTo(context, culture, value, destType);
}
}
#endregion
} // Namespace
//// The following is a sample Extension File. You can use it to create RegionExt.cs
//using System;
//using System.Collections.Generic;
//using System.Text;
//using Csla;
//namespace Northwind.CSLA.Library
//{
// public partial class Region
// {
// partial class RegionExtension : extensionBase
// {
// // TODO: Override automatic defaults
// public new void AddAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowRead(Dbid, "<Role(s)>");
// }
// public new void AddInstanceAuthorizationRules(Csla.Security.AuthorizationRules rules)
// {
// //rules.AllowInstanceRead(Dbid, "<Role(s)>");
// }
// public new void AddValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddRule(
// Csla.Validation.CommonRules.StringMaxLength,
// new Csla.Validation.CommonRules.MaxLengthRuleArgs("Name", 100));
// }
// public new void AddInstanceValidationRules(Csla.Validation.ValidationRules rules)
// {
// rules.AddInstanceRule(/* Instance Validation Rule */);
// }
// }
// }
//}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Generator.Constants;
using Generator.Enums;
using Generator.Enums.InstructionInfo;
namespace Generator.Tables {
sealed class ImpliedAccessParser {
readonly Dictionary<string, EnumValue> toMemorySize;
readonly Dictionary<uint, EnumValue> uintToRegister;
readonly Dictionary<string, EnumValue> toRegisterImplAcc;
readonly Dictionary<EnumValue, RegisterDef> toRegisterDef;
public ImpliedAccessParser(GenTypes genTypes) {
toMemorySize = CreateEnumDict(genTypes[TypeIds.MemorySize]);
uintToRegister = genTypes[TypeIds.Register].Values.ToDictionary(a => a.Value, a => a);
toRegisterImplAcc = CreateEnumDict(genTypes[TypeIds.Register], ignoreCase: true);
toRegisterDef = genTypes.GetObject<RegisterDefs>(TypeIds.RegisterDefs).Defs.ToDictionary(a => a.Register, a => a);
uint vmmFirst = IcedConstantsType.Get_VMM_first(genTypes).Value;
uint vmmLast = IcedConstantsType.Get_VMM_last(genTypes).Value;
uint vmmCount = vmmLast - vmmFirst + 1;
var tmmLast = IcedConstantsType.Get_TMM_last(genTypes);
toRegisterImplAcc.Add("tmm_last", tmmLast);
for (uint ri = 0; ri < vmmCount; ri++) {
var reg = uintToRegister[vmmFirst + ri];
toRegisterImplAcc.Add("vmm" + ri, reg);
}
}
static Dictionary<string, EnumValue> CreateEnumDict(EnumType enumType, bool ignoreCase = false) =>
enumType.Values.ToDictionary(a => a.RawName, a => a, ignoreCase ? StringComparer.OrdinalIgnoreCase : StringComparer.Ordinal);
static bool TryParse_2_4_or_8(string value, out uint result, [NotNullWhen(false)] out string? error) {
if (!ParserUtils.TryParseUInt32(value, out result, out error))
return false;
switch (result) {
case 2:
case 4:
case 8:
error = null;
return true;
default:
error = $"Invalid integer, expected 2, 4 or 8: `{value}`";
return false;
}
}
static bool TryParse_2_or_4(string value, out uint result, [NotNullWhen(false)] out string? error) {
if (!ParserUtils.TryParseUInt32(value, out result, out error))
return false;
switch (result) {
case 2:
case 4:
error = null;
return true;
default:
error = $"Invalid integer, expected 2, 4 or 8: `{value}`";
return false;
}
}
static bool TryParsePushPopArgs(string value, out uint count, out uint size, [NotNullWhen(false)] out string? error) {
count = 0;
size = 0;
var parts = value.Split('x');
if (parts.Length != 2) {
error = $"Expected <count> x <size>, eg. 1x8: `{value}`";
return false;
}
if (!ParserUtils.TryParseUInt32(parts[0], out count, out error))
return false;
if (!TryParse_2_4_or_8(parts[1], out size, out error))
return false;
error = null;
return true;
}
static readonly HashSet<string> impliedAccessKeyHasValue = new HashSet<string>(StringComparer.Ordinal) {
"cr", "cw", "crcw", "r", "w", "rw", "rcw",
"shift-mask", "shift-mask-1F-mod",
"enter", "leave",
"push", "pop", "pop-rm",
"pusha", "popa",
"emmi-reg",
"xstore",
};
public bool ReadImpliedAccesses(string line, [NotNullWhen(true)] out ImpliedAccesses? accesses, [NotNullWhen(false)] out string? error) {
accesses = null;
if (!TryReadImpliedAccesses(line, out var conds, out error))
return false;
if (HasSpecialAccWithOtherAcc(conds)) {
// They change rflags bits and the runtime code needs to check if it's one of these, see GetRflagsInfo()
error = "These can only be used with no other commands: shift-mask=0x1F, shift-mask=0x3F, shift-mask-1F-mod, zero-reg-rflags";
return false;
}
var mergedConds = MergeConds(conds);
AddReadMemRegs(mergedConds);
RemoveDupeStatements(mergedConds);
RemoveUselessRegs(mergedConds);
mergedConds.Sort((a, b) => a.Kind.CompareTo(b.Kind));
foreach (var cond in mergedConds) {
Sort(cond.TrueStatements);
Sort(cond.FalseStatements);
}
accesses = new ImpliedAccesses(mergedConds);
return true;
}
void Sort(List<ImplAccStatement> stmts) => stmts.Sort(CompareStmts);
int CompareStmts(ImplAccStatement x, ImplAccStatement y) {
if (x.Kind != y.Kind)
return x.Kind.CompareTo(y.Kind);
switch (x) {
case NoArgImplAccStatement:
return 0;
case EmmiImplAccStatement emmi_a:
var emmi_b = (EmmiImplAccStatement)y;
return emmi_a.CompareTo(emmi_b);
case IntArgImplAccStatement ia_a:
var ia_b = (IntArgImplAccStatement)y;
return ia_a.CompareTo(ia_b);
case IntX2ArgImplAccStatement ia2_a:
var ia2_b = (IntX2ArgImplAccStatement)y;
return ia2_a.CompareTo(ia2_b);
case RegisterRangeImplAccStatement range_a:
var range_b = (RegisterRangeImplAccStatement)y;
return range_a.CompareTo(range_b);
case RegisterImplAccStatement reg_a:
var reg_b = (RegisterImplAccStatement)y;
return reg_a.CompareTo(reg_b);
case MemoryImplAccStatement mem_a:
var mem_b = (MemoryImplAccStatement)y;
return mem_a.CompareTo(mem_b);
default:
throw new InvalidOperationException();
}
}
static void RemoveUselessRegs(List<ImplAccCondition> conds) {
foreach (var cond in conds) {
switch (cond.Kind) {
case ImplAccConditionKind.Bit64:
RemoveUselessSegmentReads(cond.TrueStatements);
break;
case ImplAccConditionKind.NotBit64:
RemoveUselessSegmentReads(cond.FalseStatements);
break;
}
}
}
static void RemoveUselessSegmentReads(List<ImplAccStatement> stmts) {
for (int i = stmts.Count - 1; i >= 0; i--) {
var stmt = stmts[i];
if (stmt is RegisterImplAccStatement reg) {
if (!IsSeg_ES_CS_SS_DS(reg.Register))
continue;
if (reg.Access == OpAccess.Read || reg.Access == OpAccess.CondRead)
stmts.RemoveAt(i);
}
}
}
static bool IsSeg_ES_CS_SS_DS(ImplAccRegister register) {
if (register.Kind == ImplAccRegisterKind.Register) {
Debug.Assert(register.Register is not null);
switch ((Register)register.Register.Value) {
case Register.ES:
case Register.CS:
case Register.SS:
case Register.DS:
return true;
}
}
return false;
}
static void RemoveDupeStatements(List<ImplAccCondition> conds) {
foreach (var cond in conds) {
RemoveDupeStatements(cond.TrueStatements);
RemoveDupeStatements(cond.FalseStatements);
}
}
static void RemoveDupeStatements(List<ImplAccStatement> stmts) {
var unique = stmts.Distinct().ToArray();
stmts.Clear();
stmts.AddRange(unique);
}
static void AddReadMemRegs(List<ImplAccCondition> conds) {
var extra = new List<ImplAccStatement>();
foreach (var cond in conds) {
AddReadRegs(extra, cond.TrueStatements);
AddReadRegs(extra, cond.FalseStatements);
}
}
static void AddReadRegs(List<ImplAccStatement> extra, List<ImplAccStatement> stmts) {
extra.Clear();
foreach (var stmt in stmts) {
if (stmt is MemoryImplAccStatement mem) {
var opAccess = mem.Access switch {
OpAccess.Read or OpAccess.Write or OpAccess.ReadWrite or OpAccess.ReadCondWrite or OpAccess.NoMemAccess => OpAccess.Read,
OpAccess.CondRead or OpAccess.CondWrite => OpAccess.CondRead,
_ => throw new InvalidOperationException(),
};
AddReadReg(extra, mem.Segment, opAccess, true);
AddReadReg(extra, mem.Base, opAccess, false);
AddReadReg(extra, mem.Index, opAccess, false);
}
}
stmts.AddRange(extra);
}
static void AddReadReg(List<ImplAccStatement> extra, ImplAccRegister? reg, OpAccess opAccess, bool isMemOpSegRead) {
if (reg is ImplAccRegister reg2) {
switch (reg2.Kind) {
case ImplAccRegisterKind.Register:
case ImplAccRegisterKind.SegmentDefaultDS:
case ImplAccRegisterKind.a_rDI:
extra.Add(new RegisterImplAccStatement(opAccess, reg2, isMemOpSegRead));
break;
case ImplAccRegisterKind.Op0:
case ImplAccRegisterKind.Op1:
case ImplAccRegisterKind.Op2:
case ImplAccRegisterKind.Op3:
case ImplAccRegisterKind.Op4:
// Added automatically by the runtime code
break;
default:
throw new InvalidOperationException();
}
}
}
static readonly Dictionary<ImplAccConditionKind, ImplAccConditionKind> toPosCond = new Dictionary<ImplAccConditionKind, ImplAccConditionKind> {
{ ImplAccConditionKind.None, ImplAccConditionKind.None },
{ ImplAccConditionKind.Bit64, ImplAccConditionKind.Bit64 },
{ ImplAccConditionKind.NotBit64, ImplAccConditionKind.Bit64 },
};
static readonly Dictionary<ImplAccConditionKind, ImplAccConditionKind> toNegCond = new Dictionary<ImplAccConditionKind, ImplAccConditionKind> {
{ ImplAccConditionKind.None, ImplAccConditionKind.None },
{ ImplAccConditionKind.Bit64, ImplAccConditionKind.NotBit64 },
{ ImplAccConditionKind.NotBit64, ImplAccConditionKind.NotBit64 },
};
static List<ImplAccCondition> MergeConds(Dictionary<ImplAccConditionKind, ImplAccCondition> conds) {
if (toPosCond.Count != toNegCond.Count)
throw new InvalidOperationException();
var mergedConds = new Dictionary<ImplAccConditionKind, ImplAccCondition>();
foreach (var kv in conds) {
var currCond = kv.Value;
var newKind = toPosCond[currCond.Kind];
if (!mergedConds.TryGetValue(newKind, out var cond))
mergedConds.Add(newKind, cond = new ImplAccCondition(newKind));
if (currCond.Kind == newKind) {
cond.TrueStatements.AddRange(currCond.TrueStatements);
cond.FalseStatements.AddRange(currCond.FalseStatements);
}
else {
cond.TrueStatements.AddRange(currCond.FalseStatements);
cond.FalseStatements.AddRange(currCond.TrueStatements);
}
}
var result = new List<ImplAccCondition>();
foreach (var kv in mergedConds) {
var currCond = kv.Value;
if (currCond.TrueStatements.Count == 0 && currCond.FalseStatements.Count == 0)
continue;
if (currCond.TrueStatements.Count == 0) {
var newKind = toNegCond[currCond.Kind];
var newCond = new ImplAccCondition(newKind);
newCond.TrueStatements.AddRange(currCond.FalseStatements);
result.Add(newCond);
}
else
result.Add(currCond);
}
return result;
}
static bool HasSpecialAccWithOtherAcc(Dictionary<ImplAccConditionKind, ImplAccCondition> conds) {
int count = 0;
bool found = false;
foreach (var kv in conds) {
var acc = kv.Value;
Check(ref count, ref found, acc.TrueStatements);
Check(ref count, ref found, acc.FalseStatements);
}
return found && count > 1;
static void Check(ref int count, ref bool found, List<ImplAccStatement> stmts) {
foreach (var stmt in stmts) {
count++;
switch (stmt.Kind) {
case ImplAccStatementKind.ShiftMask:
case ImplAccStatementKind.ShiftMask1FMod:
case ImplAccStatementKind.ZeroRegRflags:
found = true;
break;
}
}
}
}
bool TryReadImpliedAccesses(string line, out Dictionary<ImplAccConditionKind, ImplAccCondition> conds, [NotNullWhen(false)] out string? error) {
conds = new Dictionary<ImplAccConditionKind, ImplAccCondition>();
foreach (var keyValue in line.Split(' ', StringSplitOptions.RemoveEmptyEntries)) {
var (keyCond, value) = ParserUtils.GetKeyValue(keyValue);
var (key, condStr) = GetKeyCond(keyCond);
ImplAccConditionKind cond;
switch (condStr) {
case "": cond = ImplAccConditionKind.None; break;
case "64": cond = ImplAccConditionKind.Bit64; break;
case "!64": cond = ImplAccConditionKind.NotBit64; break;
default:
error = $"Unknown condition `{condStr}`";
return false;
}
if (impliedAccessKeyHasValue.Contains(key)) {
if (value == string.Empty) {
error = $"Missing key=value: `{keyValue}`";
return false;
}
}
else {
if (value != string.Empty) {
error = $"`{key}` doesn't support values: `{keyValue}`";
return false;
}
}
if (!conds.TryGetValue(cond, out var implAccCond))
conds.Add(cond, implAccCond = new ImplAccCondition(cond));
ImplAccStatement? stmt = null;
uint arg1, arg2;
switch (key) {
case "cr":
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.CondRead, out error))
return false;
break;
case "cw":
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.CondWrite, out error))
return false;
break;
case "crcw":
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.CondRead, out error))
return false;
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.CondWrite, out error))
return false;
break;
case "r":
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.Read, out error))
return false;
break;
case "w":
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.Write, out error))
return false;
break;
case "rw":
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.ReadWrite, out error))
return false;
break;
case "rcw":
if (!TryParseImplAccRegOrMem(implAccCond.TrueStatements, value, OpAccess.ReadCondWrite, out error))
return false;
break;
case "shift-mask":
if (!ParserUtils.TryParseUInt32(value, out arg1, out error))
return false;
// The reason this can't be changed is the hard coded enum values in ImpliedAccessEnumFactory which are used by the runtime code
if (arg1 != 0x1F && arg1 != 0x3F) {
error = $"Invalid mask: `{value}`";
return false;
}
stmt = new IntArgImplAccStatement(ImplAccStatementKind.ShiftMask, arg1);
break;
case "zero-reg-rflags":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.ZeroRegRflags);
break;
case "zero-reg-regmem":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.ZeroRegRegmem);
break;
case "zero-reg-reg-regmem":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.ZeroRegRegRegmem);
break;
case "arpl":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Arpl);
break;
case "last-gpr-8":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.LastGpr8);
break;
case "last-gpr-16":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.LastGpr16);
break;
case "last-gpr-32":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.LastGpr32);
break;
case "lea":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.lea);
break;
case "cmps":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Cmps);
break;
case "ins":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Ins);
break;
case "lods":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Lods);
break;
case "movs":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Movs);
break;
case "outs":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Outs);
break;
case "scas":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Scas);
break;
case "stos":
stmt = new NoArgImplAccStatement(ImplAccStatementKind.Stos);
break;
case "xstore":
if (!TryParse_2_4_or_8(value, out arg1, out error))
return false;
stmt = new IntArgImplAccStatement(ImplAccStatementKind.Xstore, arg1);
break;
case "emmi-reg":
EmmiAccess emmiAccess;
switch (value) {
case "r": emmiAccess = EmmiAccess.Read; break;
case "w": emmiAccess = EmmiAccess.Write; break;
case "rw": emmiAccess = EmmiAccess.ReadWrite; break;
default:
error = $"Unknown access: `{value}`";
return false;
}
stmt = new EmmiImplAccStatement(emmiAccess);
break;
case "shift-mask-1F-mod":
if (!ParserUtils.TryParseUInt32(value, out arg1, out error))
return false;
// The reason this can't be changed is the hard coded enum values in ImpliedAccessEnumFactory which are used by the runtime code
if (arg1 != 9 && arg1 != 17) {
error = $"Invalid modulus: `{value}`";
return false;
}
stmt = new IntArgImplAccStatement(ImplAccStatementKind.ShiftMask1FMod, arg1);
break;
case "enter":
if (!TryParse_2_4_or_8(value, out arg1, out error))
return false;
stmt = new IntArgImplAccStatement(ImplAccStatementKind.Enter, arg1);
break;
case "leave":
if (!TryParse_2_4_or_8(value, out arg1, out error))
return false;
stmt = new IntArgImplAccStatement(ImplAccStatementKind.Leave, arg1);
break;
case "push":
if (!TryParsePushPopArgs(value, out arg1, out arg2, out error))
return false;
stmt = new IntX2ArgImplAccStatement(ImplAccStatementKind.Push, arg1, arg2);
break;
case "pop":
if (!TryParsePushPopArgs(value, out arg1, out arg2, out error))
return false;
stmt = new IntX2ArgImplAccStatement(ImplAccStatementKind.Pop, arg1, arg2);
break;
case "pop-rm":
if (!TryParse_2_4_or_8(value, out arg1, out error))
return false;
stmt = new IntArgImplAccStatement(ImplAccStatementKind.PopRm, arg1);
break;
case "pusha":
if (!TryParse_2_or_4(value, out arg1, out error))
return false;
stmt = new IntArgImplAccStatement(ImplAccStatementKind.Pusha, arg1);
break;
case "popa":
if (!TryParse_2_or_4(value, out arg1, out error))
return false;
stmt = new IntArgImplAccStatement(ImplAccStatementKind.Popa, arg1);
break;
default:
error = $"Unknown key=value: `{keyValue}`";
return false;
}
if (stmt is not null)
implAccCond.TrueStatements.Add(stmt);
}
error = null;
return true;
}
bool TryParseImplAccRegOrMem(List<ImplAccStatement> statements, string value, OpAccess access, [NotNullWhen(false)] out string? error) {
var parts = value.Split(';', StringSplitOptions.RemoveEmptyEntries);
if (parts.Length == 0) {
error = "Missing value";
return false;
}
foreach (var part in parts) {
ImplAccStatement? stmt;
if (part[0] == '[') {
if (!TryParseImplAccMem(part, access, out stmt, out error))
return false;
statements.Add(stmt);
}
else {
if (TrySplit(part, '-', out var left, out var right)) {
if (!TryParseRegister(left, out var regLeft, out error))
return false;
if (!TryParseRegister(right, out var regRight, out error))
return false;
if (regLeft.Register is null || regLeft.Kind != ImplAccRegisterKind.Register) {
error = $"Must be a normal register: `{left}`";
return false;
}
if (regRight.Register is null || regRight.Kind != ImplAccRegisterKind.Register) {
error = $"Must be a normal register: `{right}`";
return false;
}
if (regLeft.Register.Value > regRight.Register.Value) {
error = $"Left reg ({left}) must be <= right reg ({right})";
return false;
}
statements.Add(new RegisterRangeImplAccStatement(access, regLeft.Register, regRight.Register));
}
else {
if (!TryParseImplAccReg(part, access, out stmt, out error))
return false;
statements.Add(stmt);
}
}
}
error = null;
return true;
}
bool TryParseMemorySize(string value, out ImplAccMemorySize memorySize, [NotNullWhen(false)] out string? error) {
memorySize = default;
if (toMemorySize.TryGetValue(value, out var memSize)) {
memorySize = new ImplAccMemorySize(memSize);
error = null;
return true;
}
switch (value) {
case "default":
memorySize = new ImplAccMemorySize(ImplAccMemorySizeKind.Default);
break;
default:
error = $"Unknown memory size: `{value}`";
return false;
}
error = null;
return true;
}
bool TryParseRegister(string regStr, [NotNullWhen(true)] out ImplAccRegister register, [NotNullWhen(false)] out string? error) {
register = default;
if (toRegisterImplAcc.TryGetValue(regStr, out var regEnumValue)) {
register = new ImplAccRegister(regEnumValue);
error = null;
return true;
}
switch (regStr) {
case "seg": register = new ImplAccRegister(ImplAccRegisterKind.SegmentDefaultDS); break;
case "a_rDI": register = new ImplAccRegister(ImplAccRegisterKind.a_rDI); break;
case "op0-reg": register = new ImplAccRegister(ImplAccRegisterKind.Op0); break;
case "op1-reg": register = new ImplAccRegister(ImplAccRegisterKind.Op1); break;
case "op2-reg": register = new ImplAccRegister(ImplAccRegisterKind.Op2); break;
case "op3-reg": register = new ImplAccRegister(ImplAccRegisterKind.Op3); break;
case "op4-reg": register = new ImplAccRegister(ImplAccRegisterKind.Op4); break;
default:
error = $"Unknown register `{regStr}";
return false;
}
error = null;
return true;
}
static bool TrySplit(string value, char c, [NotNullWhen(true)] out string? left, [NotNullWhen(true)] out string? right) {
int index = value.IndexOf(c, StringComparison.Ordinal);
if (index < 0) {
left = null;
right = null;
return false;
}
else {
left = value[0..index].Trim();
right = value[(index + 1)..].Trim();
return true;
}
}
bool TryParseImplAccMem(string value, OpAccess access, [NotNullWhen(true)] out ImplAccStatement? stmt, [NotNullWhen(false)] out string? error) {
stmt = null;
if (value.Length == 0 || value[0] != '[' || value[^1] != ']') {
error = "Memory must be inside `[` and `]`";
return false;
}
value = value[1..^1].Trim();
if (!TrySplit(value, '=', out var left, out var right)) {
error = "Missing memory size";
return false;
}
value = left;
var memSizeAndOptions = right.Split('|');
var memSize = memSizeAndOptions[0];
if (!TryParseMemorySize(memSize, out var memorySize, out error))
return false;
var addressSize = CodeSize.Unknown;
uint vsibSize = 0;
for (int i = 1; i < memSizeAndOptions.Length; i++) {
var opt = memSizeAndOptions[i];
switch (opt) {
case "16":
case "32":
case "64":
if (addressSize != CodeSize.Unknown) {
error = "Duplicate address size value";
return false;
}
addressSize = opt switch {
"16" => CodeSize.Code16,
"32" => CodeSize.Code32,
"64" => CodeSize.Code64,
_ => throw new InvalidOperationException(),
};
break;
case "vsib32":
case "vsib64":
if (vsibSize != 0) {
error = "Duplicate vsib size value";
return false;
}
vsibSize = opt switch {
"vsib32" => 4,
"vsib64" => 8,
_ => throw new InvalidOperationException(),
};
break;
default:
error = $"Unknown memory operand option: `{opt}`";
return false;
}
}
ImplAccRegister? segment;
if (TrySplit(value, ':', out var segStr, out right)) {
value = right;
if (!TryParseRegister(segStr, out var seg, out error))
return false;
segment = seg;
}
else
segment = null;
if (!TryParseRegister(value, out var @base, out error))
return false;
ImplAccRegister? index = null;
if (addressSize == CodeSize.Unknown)
addressSize = GetAddressSize(@base);
if (addressSize == CodeSize.Unknown)
addressSize = GetAddressSize(index);
bool isVecIndexReg = index is ImplAccRegister register &&
register.Kind == ImplAccRegisterKind.Register &&
(RegisterClass)toRegisterDef[register.Register!].RegisterClass.Value == RegisterClass.Vector;
if (vsibSize != 0) {
if (!isVecIndexReg) {
error = "Missing vector index register";
return false;
}
}
else {
if (isVecIndexReg) {
error = "Missing vsib size";
return false;
}
}
stmt = new MemoryImplAccStatement(access, segment, @base, index, 1, memorySize, addressSize, vsibSize);
error = null;
return true;
}
CodeSize GetAddressSize(ImplAccRegister? register) {
if (register is ImplAccRegister reg) {
switch (reg.Kind) {
case ImplAccRegisterKind.Register:
var regEnum = reg.Register ?? throw new InvalidOperationException();
var regDef = toRegisterDef[regEnum];
switch ((RegisterKind)regDef.RegisterKind.Value) {
case RegisterKind.GPR16:
return CodeSize.Code16;
case RegisterKind.GPR32:
return CodeSize.Code32;
case RegisterKind.GPR64:
return CodeSize.Code64;
default:
break;
}
break;
case ImplAccRegisterKind.SegmentDefaultDS:
case ImplAccRegisterKind.a_rDI:
case ImplAccRegisterKind.Op0:
case ImplAccRegisterKind.Op1:
case ImplAccRegisterKind.Op2:
case ImplAccRegisterKind.Op3:
case ImplAccRegisterKind.Op4:
break;
default:
throw new InvalidOperationException();
}
}
return CodeSize.Unknown;
}
bool TryParseImplAccReg(string value, OpAccess access, [NotNullWhen(true)] out ImplAccStatement? stmt, [NotNullWhen(false)] out string? error) {
stmt = null;
if (!TryParseRegister(value, out var register, out error))
return false;
stmt = new RegisterImplAccStatement(access, register, false);
error = null;
return true;
}
static (string key, string cond) GetKeyCond(string keyCond) {
int index = keyCond.IndexOf(';', StringComparison.Ordinal);
if (index < 0)
return (keyCond, string.Empty);
var key = keyCond[0..index].Trim();
var cond = keyCond[(index + 1)..].Trim();
return (key, cond);
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.CodeDom;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
namespace Avro
{
public class CodeGen
{
/// <summary>
/// Object that contains all the generated types
/// </summary>
public CodeCompileUnit CompileUnit { get; private set; }
/// <summary>
/// List of schemas to generate code for
/// </summary>
public IList<Schema> Schemas { get; private set; }
/// <summary>
/// List of protocols to generate code for
/// </summary>
public IList<Protocol> Protocols { get; private set; }
/// <summary>
/// List of generated namespaces
/// </summary>
protected Dictionary<string, CodeNamespace> namespaceLookup = new Dictionary<string, CodeNamespace>(StringComparer.Ordinal);
/// <summary>
/// Default constructor
/// </summary>
public CodeGen()
{
this.Schemas = new List<Schema>();
this.Protocols = new List<Protocol>();
}
/// <summary>
/// Adds a protocol object to generate code for
/// </summary>
/// <param name="protocol">protocol object</param>
public virtual void AddProtocol(Protocol protocol)
{
Protocols.Add(protocol);
}
/// <summary>
/// Adds a schema object to generate code for
/// </summary>
/// <param name="schema">schema object</param>
public virtual void AddSchema(Schema schema)
{
Schemas.Add(schema);
}
/// <summary>
/// Adds a namespace object for the given name into the dictionary if it doesn't exist yet
/// </summary>
/// <param name="name">name of namespace</param>
/// <returns></returns>
protected virtual CodeNamespace addNamespace(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name", "name cannot be null.");
CodeNamespace ns = null;
if (!namespaceLookup.TryGetValue(name, out ns))
{
ns = new CodeNamespace(CodeGenUtil.Instance.Mangle(name));
foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports)
ns.Imports.Add(nci);
CompileUnit.Namespaces.Add(ns);
namespaceLookup.Add(name, ns);
}
return ns;
}
/// <summary>
/// Generates code for the given protocol and schema objects
/// </summary>
/// <returns>CodeCompileUnit object</returns>
public virtual CodeCompileUnit GenerateCode()
{
CompileUnit = new CodeCompileUnit();
processSchemas();
processProtocols();
return CompileUnit;
}
/// <summary>
/// Generates code for the schema objects
/// </summary>
protected virtual void processSchemas()
{
foreach (Schema schema in this.Schemas)
{
SchemaNames names = generateNames(schema);
foreach (KeyValuePair<SchemaName, NamedSchema> sn in names)
{
switch (sn.Value.Tag)
{
case Schema.Type.Enumeration: processEnum(sn.Value); break;
case Schema.Type.Fixed: processFixed(sn.Value); break;
case Schema.Type.Record: processRecord(sn.Value); break;
case Schema.Type.Error: processRecord(sn.Value); break;
default:
throw new CodeGenException("Names in schema should only be of type NamedSchema, type found " + sn.Value.Tag);
}
}
}
}
/// <summary>
/// Generates code for the protocol objects
/// </summary>
protected virtual void processProtocols()
{
foreach (Protocol protocol in Protocols)
{
SchemaNames names = generateNames(protocol);
foreach (KeyValuePair<SchemaName, NamedSchema> sn in names)
{
switch (sn.Value.Tag)
{
case Schema.Type.Enumeration: processEnum(sn.Value); break;
case Schema.Type.Fixed: processFixed(sn.Value); break;
case Schema.Type.Record: processRecord(sn.Value); break;
case Schema.Type.Error: processRecord(sn.Value); break;
default:
throw new CodeGenException("Names in protocol should only be of type NamedSchema, type found " + sn.Value.Tag);
}
}
processInterface(protocol);
}
}
/// <summary>
/// Generate list of named schemas from given protocol
/// </summary>
/// <param name="protocol">protocol to process</param>
/// <returns></returns>
protected virtual SchemaNames generateNames(Protocol protocol)
{
var names = new SchemaNames();
foreach (Schema schema in protocol.Types)
addName(schema, names);
return names;
}
/// <summary>
/// Generate list of named schemas from given schema
/// </summary>
/// <param name="schema">schema to process</param>
/// <returns></returns>
protected virtual SchemaNames generateNames(Schema schema)
{
var names = new SchemaNames();
addName(schema, names);
return names;
}
/// <summary>
/// Recursively search the given schema for named schemas and adds them to the given container
/// </summary>
/// <param name="schema">schema object to search</param>
/// <param name="names">list of named schemas</param>
protected virtual void addName(Schema schema, SchemaNames names)
{
NamedSchema ns = schema as NamedSchema;
if (null != ns) if (names.Contains(ns.SchemaName)) return;
switch (schema.Tag)
{
case Schema.Type.Null:
case Schema.Type.Boolean:
case Schema.Type.Int:
case Schema.Type.Long:
case Schema.Type.Float:
case Schema.Type.Double:
case Schema.Type.Bytes:
case Schema.Type.String:
break;
case Schema.Type.Enumeration:
case Schema.Type.Fixed:
names.Add(ns);
break;
case Schema.Type.Record:
case Schema.Type.Error:
var rs = schema as RecordSchema;
names.Add(rs);
foreach (Field field in rs.Fields)
addName(field.Schema, names);
break;
case Schema.Type.Array:
var asc = schema as ArraySchema;
addName(asc.ItemSchema, names);
break;
case Schema.Type.Map:
var ms = schema as MapSchema;
addName(ms.ValueSchema, names);
break;
case Schema.Type.Union:
var us = schema as UnionSchema;
foreach (Schema usc in us.Schemas)
addName(usc, names);
break;
default:
throw new CodeGenException("Unable to add name for " + schema.Name + " type " + schema.Tag);
}
}
/// <summary>
/// Creates a class declaration for fixed schema
/// </summary>
/// <param name="schema">fixed schema</param>
/// <param name="ns">namespace object</param>
protected virtual void processFixed(Schema schema)
{
FixedSchema fixedSchema = schema as FixedSchema;
if (null == fixedSchema) throw new CodeGenException("Unable to cast schema into a fixed");
CodeTypeDeclaration ctd = new CodeTypeDeclaration();
ctd.Name = CodeGenUtil.Instance.Mangle(fixedSchema.Name);
ctd.IsClass = true;
//ctd.IsPartial = true;
ctd.Attributes = MemberAttributes.Public;
//ctd.BaseTypes.Add("SpecificFixed");
// create static schema field
//createSchemaField(schema, ctd, true);
// Add Size field
string sizefname = "fixedSize";
var ctrfield = new CodeTypeReference(typeof(uint));
var codeField = new CodeMemberField(ctrfield, sizefname);
codeField.Attributes = MemberAttributes.Private | MemberAttributes.Static;
codeField.InitExpression = new CodePrimitiveExpression(fixedSchema.Size);
ctd.Members.Add(codeField);
// Add Size property
var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), sizefname);
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Static;
property.Name = "FixedSize";
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(schema.Name + "." + sizefname)));
ctd.Members.Add(property);
// create constructor to initiate base class SpecificFixed
CodeConstructor cc = new CodeConstructor();
cc.Attributes = MemberAttributes.Public;
cc.BaseConstructorArgs.Add(new CodeVariableReferenceExpression(sizefname));
ctd.Members.Add(cc);
string nspace = fixedSchema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + fixedSchema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
}
/// <summary>
/// Creates an enum declaration
/// </summary>
/// <param name="schema">enum schema</param>
/// <param name="ns">namespace</param>
protected virtual void processEnum(Schema schema)
{
EnumSchema enumschema = schema as EnumSchema;
if (null == enumschema) throw new CodeGenException("Unable to cast schema into an enum");
CodeTypeDeclaration ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(enumschema.Name));
ctd.IsEnum = true;
ctd.Attributes = MemberAttributes.Public;
foreach (string symbol in enumschema.Symbols)
{
if (CodeGenUtil.Instance.ReservedKeywords.Contains(symbol))
throw new CodeGenException("Enum symbol " + symbol + " is a C# reserved keyword");
CodeMemberField field = new CodeMemberField(typeof(int), symbol);
ctd.Members.Add(field);
}
string nspace = enumschema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + enumschema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
}
protected virtual void processInterface(Protocol protocol)
{
// Create abstract class
string protocolNameMangled = CodeGenUtil.Instance.Mangle(protocol.Name);
var ctd = new CodeTypeDeclaration(protocolNameMangled);
ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
ctd.IsClass = true;
ctd.BaseTypes.Add("Avro.Specific.ISpecificProtocol");
AddProtocolDocumentation(protocol, ctd);
// Add static protocol field.
var protocolField = new CodeMemberField();
protocolField.Attributes = MemberAttributes.Private | MemberAttributes.Static | MemberAttributes.Final;
protocolField.Name = "protocol";
protocolField.Type = new CodeTypeReference("readonly Avro.Protocol");
var cpe = new CodePrimitiveExpression(protocol.ToString());
var cmie = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Protocol)), "Parse"),
new CodeExpression[] { cpe });
protocolField.InitExpression = cmie;
ctd.Members.Add(protocolField);
// Add overridden Protocol method.
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
property.Name = "Protocol";
property.Type = new CodeTypeReference("Avro.Protocol");
property.HasGet = true;
property.GetStatements.Add(new CodeTypeReferenceExpression("return protocol"));
ctd.Members.Add(property);
//var requestMethod = CreateRequestMethod();
//ctd.Members.Add(requestMethod);
var requestMethod = CreateRequestMethod();
//requestMethod.Attributes |= MemberAttributes.Override;
var builder = new StringBuilder();
if (protocol.Messages.Count > 0)
{
builder.Append("switch(messageName)\n\t\t\t{");
foreach (var a in protocol.Messages)
{
builder.Append("\n\t\t\t\tcase \"").Append(a.Key).Append("\":\n");
bool unused = false;
string type = getType(a.Value.Response, false, ref unused);
builder.Append("\t\t\t\trequestor.Request<")
.Append(type)
.Append(">(messageName, args, callback);\n");
builder.Append("\t\t\t\tbreak;\n");
}
builder.Append("\t\t\t}");
}
var cseGet = new CodeSnippetExpression(builder.ToString());
requestMethod.Statements.Add(cseGet);
ctd.Members.Add(requestMethod);
AddMethods(protocol, false, ctd);
string nspace = protocol.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for enum schema " + nspace);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
// Create callback abstract class
ctd = new CodeTypeDeclaration(protocolNameMangled + "Callback");
ctd.TypeAttributes = TypeAttributes.Abstract | TypeAttributes.Public;
ctd.IsClass = true;
ctd.BaseTypes.Add(protocolNameMangled);
// Need to override
AddProtocolDocumentation(protocol, ctd);
AddMethods(protocol, true, ctd);
codens.Types.Add(ctd);
}
private static CodeMemberMethod CreateRequestMethod()
{
var requestMethod = new CodeMemberMethod();
requestMethod.Attributes = MemberAttributes.Public | MemberAttributes.Final;
requestMethod.Name = "Request";
requestMethod.ReturnType = new CodeTypeReference(typeof (void));
{
var requestor = new CodeParameterDeclarationExpression(typeof (Avro.Specific.ICallbackRequestor),
"requestor");
requestMethod.Parameters.Add(requestor);
var messageName = new CodeParameterDeclarationExpression(typeof (string), "messageName");
requestMethod.Parameters.Add(messageName);
var args = new CodeParameterDeclarationExpression(typeof (object[]), "args");
requestMethod.Parameters.Add(args);
var callback = new CodeParameterDeclarationExpression(typeof (object), "callback");
requestMethod.Parameters.Add(callback);
}
return requestMethod;
}
private static void AddMethods(Protocol protocol, bool generateCallback, CodeTypeDeclaration ctd)
{
foreach (var e in protocol.Messages)
{
var name = e.Key;
var message = e.Value;
var response = message.Response;
if (generateCallback && message.Oneway.GetValueOrDefault())
continue;
var messageMember = new CodeMemberMethod();
messageMember.Name = CodeGenUtil.Instance.Mangle(name);
messageMember.Attributes = MemberAttributes.Public | MemberAttributes.Abstract;
if (message.Doc!= null && message.Doc.Trim() != string.Empty)
messageMember.Comments.Add(new CodeCommentStatement(message.Doc));
if (message.Oneway.GetValueOrDefault() || generateCallback)
{
messageMember.ReturnType = new CodeTypeReference(typeof (void));
}
else
{
bool ignored = false;
string type = getType(response, false, ref ignored);
messageMember.ReturnType = new CodeTypeReference(type);
}
foreach (Field field in message.Request.Fields)
{
bool ignored = false;
string type = getType(field.Schema, false, ref ignored);
string fieldName = CodeGenUtil.Instance.Mangle(field.Name);
var parameter = new CodeParameterDeclarationExpression(type, fieldName);
messageMember.Parameters.Add(parameter);
}
if (generateCallback)
{
bool unused = false;
var type = getType(response, false, ref unused);
var parameter = new CodeParameterDeclarationExpression("Avro.IO.ICallback<" + type + ">",
"callback");
messageMember.Parameters.Add(parameter);
}
ctd.Members.Add(messageMember);
}
}
private void AddProtocolDocumentation(Protocol protocol, CodeTypeDeclaration ctd)
{
// Add interface documentation
if (protocol.Doc != null && protocol.Doc.Trim() != string.Empty)
{
var interfaceDoc = createDocComment(protocol.Doc);
if (interfaceDoc != null)
ctd.Comments.Add(interfaceDoc);
}
}
/// <summary>
/// Creates a class declaration
/// </summary>
/// <param name="schema">record schema</param>
/// <param name="ns">namespace</param>
/// <returns></returns>
protected virtual CodeTypeDeclaration processRecord(Schema schema)
{
RecordSchema recordSchema = schema as RecordSchema;
if (null == recordSchema) throw new CodeGenException("Unable to cast schema into a record");
bool isError = recordSchema.Tag == Schema.Type.Error;
// declare the class
var ctd = new CodeTypeDeclaration(CodeGenUtil.Instance.Mangle(recordSchema.Name));
// ctd.BaseTypes.Add(isError ? "SpecificException" : "ISpecificRecord");
ctd.Attributes = MemberAttributes.Public;
ctd.IsClass = true;
//ctd.IsPartial = true;
//createSchemaField(schema, ctd, isError);
//// declare Get() to be used by the Writer classes
//var cmmGet = new CodeMemberMethod();
//cmmGet.Name = "Get";
//cmmGet.Attributes = MemberAttributes.Public;
//cmmGet.ReturnType = new CodeTypeReference("System.Object");
//cmmGet.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
//StringBuilder getFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");
//// declare Put() to be used by the Reader classes
//var cmmPut = new CodeMemberMethod();
//cmmPut.Name = "Put";
//cmmPut.Attributes = MemberAttributes.Public;
//cmmPut.ReturnType = new CodeTypeReference(typeof(void));
//cmmPut.Parameters.Add(new CodeParameterDeclarationExpression(typeof(int), "fieldPos"));
//cmmPut.Parameters.Add(new CodeParameterDeclarationExpression("System.Object", "fieldValue"));
//var putFieldStmt = new StringBuilder("switch (fieldPos)\n\t\t\t{\n");
//if (isError)
//{
// cmmGet.Attributes |= MemberAttributes.Override;
// cmmPut.Attributes |= MemberAttributes.Override;
//}
foreach (Field field in recordSchema.Fields)
{
// Determine type of field
bool nullibleEnum = false;
string baseType = getType(field.Schema, false, ref nullibleEnum);
var ctrfield = new CodeTypeReference(baseType);
// Create field
string privFieldName = string.Concat("_", field.Name);
var codeField = new CodeMemberField(ctrfield, privFieldName);
codeField.Attributes = MemberAttributes.Private;
// Process field documentation if it exist and add to the field
CodeCommentStatement propertyComment = null;
if (!string.IsNullOrEmpty(field.Documentation))
{
propertyComment = createDocComment(field.Documentation);
if (null != propertyComment)
codeField.Comments.Add(propertyComment);
}
// Add field to class
ctd.Members.Add(codeField);
// Create reference to the field - this.fieldname
var fieldRef = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), privFieldName);
var mangledName = CodeGenUtil.Instance.Mangle(field.Name);
// Create field property with get and set methods
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public | MemberAttributes.Final;
property.Name = mangledName.FirstCharToUpper();
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(fieldRef));
property.SetStatements.Add(new CodeAssignStatement(fieldRef, new CodePropertySetValueReferenceExpression()));
if (null != propertyComment)
property.Comments.Add(propertyComment);
// Add field property to class
ctd.Members.Add(property);
if (field.Schema.Tag == Schema.Type.Union) // union
{
var unionSchema = (UnionSchema) field.Schema;
var attr = new CodeAttributeDeclaration("Microsoft.Hadoop.Avro.AvroUnion");
foreach (var item in unionSchema.Schemas)
{
var name = item.Name;
if (name == "null")
{
name = "Microsoft.Hadoop.Avro.AvroNull";
}
else if (name == "bytes")
{
name = "byte[]";
}
else if (name == "boolean")
{
name = "bool";
}
attr.Arguments.Add(new CodeAttributeArgument(new CodeSnippetExpression(string.Format("typeof({0})", name))));
}
property.CustomAttributes.Add(attr);
}
// add to Get()
//getFieldStmt.Append("\t\t\tcase ");
//getFieldStmt.Append(field.Pos);
//getFieldStmt.Append(": return this.");
//getFieldStmt.Append(privFieldName);
//getFieldStmt.Append(";\n");
//// add to Put()
//putFieldStmt.Append("\t\t\tcase ");
//putFieldStmt.Append(field.Pos);
//putFieldStmt.Append(": this.");
//putFieldStmt.Append(privFieldName);
//if (nullibleEnum)
//{
// putFieldStmt.Append(" = fieldValue == null ? (");
// putFieldStmt.Append(baseType);
// putFieldStmt.Append(")null : (");
// string type = baseType.Remove(0, 16); // remove System.Nullable<
// type = type.Remove(type.Length - 1); // remove >
// putFieldStmt.Append(type);
// putFieldStmt.Append(")fieldValue; break;\n");
//}
//else
//{
// putFieldStmt.Append(" = (");
// putFieldStmt.Append(baseType);
// putFieldStmt.Append(")fieldValue; break;\n");
//}
}
//// end switch block for Get()
//getFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Get()\");\n\t\t\t}");
//var cseGet = new CodeSnippetExpression(getFieldStmt.ToString());
//cmmGet.Statements.Add(cseGet);
//ctd.Members.Add(cmmGet);
//// end switch block for Put()
//putFieldStmt.Append("\t\t\tdefault: throw new AvroRuntimeException(\"Bad index \" + fieldPos + \" in Put()\");\n\t\t\t}");
//var csePut = new CodeSnippetExpression(putFieldStmt.ToString());
//cmmPut.Statements.Add(csePut);
//ctd.Members.Add(cmmPut);
string nspace = recordSchema.Namespace;
if (string.IsNullOrEmpty(nspace))
throw new CodeGenException("Namespace required for record schema " + recordSchema.Name);
CodeNamespace codens = addNamespace(nspace);
codens.Types.Add(ctd);
return ctd;
}
/// <summary>
/// Gets the string representation of the schema's data type
/// </summary>
/// <param name="schema">schema</param>
/// <param name="nullible">flag to indicate union with null</param>
/// <returns></returns>
internal static string getType(Schema schema, bool nullible, ref bool nullibleEnum)
{
switch (schema.Tag)
{
case Schema.Type.Null:
return "System.Object";
case Schema.Type.Boolean:
if (nullible) return "System.Nullable<bool>";
else return typeof(bool).ToString();
case Schema.Type.Int:
if (nullible) return "System.Nullable<int>";
else return typeof(int).ToString();
case Schema.Type.Long:
if (nullible) return "System.Nullable<long>";
else return typeof(long).ToString();
case Schema.Type.Float:
if (nullible) return "System.Nullable<float>";
else return typeof(float).ToString();
case Schema.Type.Double:
if (nullible) return "System.Nullable<double>";
else return typeof(double).ToString();
case Schema.Type.Bytes:
return typeof(byte[]).ToString();
case Schema.Type.String:
return typeof(string).ToString();
case Schema.Type.Enumeration:
var namedSchema = schema as NamedSchema;
if (null == namedSchema)
throw new CodeGenException("Unable to cast schema into a named schema");
if (nullible)
{
nullibleEnum = true;
return "System.Nullable<" + CodeGenUtil.Instance.Mangle(namedSchema.Fullname) + ">";
}
else return CodeGenUtil.Instance.Mangle(namedSchema.Fullname);
case Schema.Type.Fixed:
case Schema.Type.Record:
case Schema.Type.Error:
namedSchema = schema as NamedSchema;
if (null == namedSchema)
throw new CodeGenException("Unable to cast schema into a named schema");
return CodeGenUtil.Instance.Mangle(namedSchema.Fullname);
case Schema.Type.Array:
var arraySchema = schema as ArraySchema;
if (null == arraySchema)
throw new CodeGenException("Unable to cast schema into an array schema");
return "List<" + getType(arraySchema.ItemSchema, false, ref nullibleEnum) + ">";
case Schema.Type.Map:
var mapSchema = schema as MapSchema;
if (null == mapSchema)
throw new CodeGenException("Unable to cast schema into a map schema");
return "Dictionary<string," + getType(mapSchema.ValueSchema, false, ref nullibleEnum) + ">";
case Schema.Type.Union:
var unionSchema = schema as UnionSchema;
if (null == unionSchema)
throw new CodeGenException("Unable to cast schema into a union schema");
Schema nullibleType = getNullableType(unionSchema);
if (null == nullibleType)
return CodeGenUtil.Object;
else
return getType(nullibleType, true, ref nullibleEnum);
}
throw new CodeGenException("Unable to generate CodeTypeReference for " + schema.Name + " type " + schema.Tag);
}
/// <summary>
/// Gets the schema of a union with null
/// </summary>
/// <param name="schema">union schema</param>
/// <returns>schema that is nullible</returns>
public static Schema getNullableType(UnionSchema schema)
{
Schema ret = null;
if (schema.Count == 2)
{
bool nullable = false;
foreach (Schema childSchema in schema.Schemas)
{
if (childSchema.Tag == Schema.Type.Null)
nullable = true;
else
ret = childSchema;
}
if (!nullable)
ret = null;
}
return ret;
}
/// <summary>
/// Creates the static schema field for class types
/// </summary>
/// <param name="schema">schema</param>
/// <param name="ctd">CodeTypeDeclaration for the class</param>
protected virtual void createSchemaField(Schema schema, CodeTypeDeclaration ctd, bool overrideFlag)
{
// create schema field
var ctrfield = new CodeTypeReference("Schema");
string schemaFname = "_SCHEMA";
var codeField = new CodeMemberField(ctrfield, schemaFname);
codeField.Attributes = MemberAttributes.Public | MemberAttributes.Static;
// create function call Schema.Parse(json)
var cpe = new CodePrimitiveExpression(schema.ToString());
var cmie = new CodeMethodInvokeExpression(
new CodeMethodReferenceExpression(new CodeTypeReferenceExpression(typeof(Schema)), "Parse"),
new CodeExpression[] { cpe });
codeField.InitExpression = cmie;
ctd.Members.Add(codeField);
// create property to get static schema field
var property = new CodeMemberProperty();
property.Attributes = MemberAttributes.Public;
if (overrideFlag) property.Attributes |= MemberAttributes.Override;
property.Name = "Schema";
property.Type = ctrfield;
property.GetStatements.Add(new CodeMethodReturnStatement(new CodeTypeReferenceExpression(ctd.Name + "." + schemaFname)));
ctd.Members.Add(property);
}
/// <summary>
/// Creates an XML documentation for the given comment
/// </summary>
/// <param name="comment">comment</param>
/// <returns>CodeCommentStatement object</returns>
protected virtual CodeCommentStatement createDocComment(string comment)
{
string text = string.Format("<summary>\r\n {0}\r\n </summary>", comment);
return new CodeCommentStatement(text, true);
}
/// <summary>
/// Writes the generated compile unit into one file
/// </summary>
/// <param name="outputFile">name of output file to write to</param>
public virtual void WriteCompileUnit(string outputFile)
{
var cscp = new CSharpCodeProvider();
var opts = new CodeGeneratorOptions();
opts.BracingStyle = "C";
opts.IndentString = "\t";
opts.BlankLinesBetweenMembers = false;
using (var outfile = new StreamWriter(outputFile))
{
cscp.GenerateCodeFromCompileUnit(CompileUnit, outfile, opts);
}
}
/// <summary>
/// Writes each types in each namespaces into individual files
/// </summary>
/// <param name="outputdir">name of directory to write to</param>
public virtual void WriteTypes(string outputdir)
{
var cscp = new CSharpCodeProvider();
var opts = new CodeGeneratorOptions();
opts.BracingStyle = "C";
opts.IndentString = "\t";
opts.BlankLinesBetweenMembers = false;
CodeNamespaceCollection nsc = CompileUnit.Namespaces;
for (int i = 0; i < nsc.Count; i++)
{
var ns = nsc[i];
string dir = outputdir + "\\" + CodeGenUtil.Instance.UnMangle(ns.Name).Replace('.', '\\');
Directory.CreateDirectory(dir);
var new_ns = new CodeNamespace(ns.Name);
new_ns.Comments.Add(CodeGenUtil.Instance.FileComment);
foreach (CodeNamespaceImport nci in CodeGenUtil.Instance.NamespaceImports)
new_ns.Imports.Add(nci);
var types = ns.Types;
for (int j = 0; j < types.Count; j++)
{
var ctd = types[j];
string file = dir + "\\" + CodeGenUtil.Instance.UnMangle(ctd.Name) + ".cs";
using (var writer = new StreamWriter(file, false))
{
new_ns.Types.Add(ctd);
cscp.GenerateCodeFromNamespace(new_ns, writer, opts);
new_ns.Types.Remove(ctd);
}
}
}
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using MSBuild = Microsoft.Build.Evaluation;
using MSBuildExecution = Microsoft.Build.Execution;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// Allows projects to group outputs according to usage.
/// </summary>
public class OutputGroup : IVsOutputGroup2
{
#region fields
private ProjectConfig projectCfg;
private ProjectNode project;
private List<Output> outputs = new List<Output>();
private Output keyOutput;
private string name;
private string targetName;
#endregion
#region properties
/// <summary>
/// Get the project configuration object associated with this output group
/// </summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Cfg")]
protected ProjectConfig ProjectCfg
{
get { return projectCfg; }
}
/// <summary>
/// Get the project object that produces this output group.
/// </summary>
protected ProjectNode Project
{
get { return project; }
}
/// <summary>
/// Gets the msbuild target name which is assciated to the outputgroup.
/// ProjectNode defines a static collection of output group names and their associated MsBuild target
/// </summary>
protected string TargetName
{
get { return targetName; }
}
#endregion
#region ctors
/// <summary>
/// Constructor for IVSOutputGroup2 implementation
/// </summary>
/// <param name="outputName">Name of the output group. See VS_OUTPUTGROUP_CNAME_Build in vsshell.idl for the list of standard values</param>
/// <param name="msBuildTargetName">MSBuild target name</param>
/// <param name="projectManager">Project that produce this output</param>
/// <param name="configuration">Configuration that produce this output</param>
public OutputGroup(string outputName, string msBuildTargetName, ProjectNode projectManager, ProjectConfig configuration)
{
if(outputName == null)
throw new ArgumentNullException("outputName");
if(msBuildTargetName == null)
throw new ArgumentNullException("outputName");
if(projectManager == null)
throw new ArgumentNullException("projectManager");
if(configuration == null)
throw new ArgumentNullException("configuration");
name = outputName;
targetName = msBuildTargetName;
project = projectManager;
projectCfg = configuration;
}
#endregion
#region virtual methods
protected virtual void Refresh()
{
// Let MSBuild know which configuration we are working with
project.SetConfiguration(projectCfg.ConfigName);
// Generate dependencies if such a task exist
const string generateDependencyList = "AllProjectOutputGroups";
if(project.BuildProject.Targets.ContainsKey(generateDependencyList))
{
bool succeeded = false;
project.BuildTarget(generateDependencyList, out succeeded);
Debug.Assert(succeeded, "Failed to build target: " + generateDependencyList);
}
// Rebuild the content of our list of output
string outputType = this.targetName + "Output";
this.outputs.Clear();
foreach (MSBuildExecution.ProjectItemInstance assembly in project.CurrentConfig.GetItems(outputType))
{
Output output = new Output(project, assembly);
this.outputs.Add(output);
// See if it is our key output
if(String.Compare(assembly.GetMetadataValue("IsKeyOutput"), true.ToString(), StringComparison.OrdinalIgnoreCase) == 0)
keyOutput = output;
}
project.SetCurrentConfiguration();
// Now that the group is built we have to check if it is invalidated by a property
// change on the project.
project.OnProjectPropertyChanged += new EventHandler<ProjectPropertyChangedArgs>(OnProjectPropertyChanged);
}
public virtual void InvalidateGroup()
{
// Set keyOutput to null so that a refresh will be performed the next time
// a property getter is called.
if(null != keyOutput)
{
// Once the group is invalidated there is no more reason to listen for events.
project.OnProjectPropertyChanged -= new EventHandler<ProjectPropertyChangedArgs>(OnProjectPropertyChanged);
}
keyOutput = null;
}
#endregion
#region event handlers
private void OnProjectPropertyChanged(object sender, ProjectPropertyChangedArgs args)
{
// In theory here we should decide if we have to invalidate the group according with the kind of property
// that is changed.
InvalidateGroup();
}
#endregion
#region IVsOutputGroup2 Members
public virtual int get_CanonicalName(out string pbstrCanonicalName)
{
pbstrCanonicalName = this.name;
return VSConstants.S_OK;
}
public virtual int get_DeployDependencies(uint celt, IVsDeployDependency[] rgpdpd, uint[] pcActual)
{
return VSConstants.E_NOTIMPL;
}
public virtual int get_Description(out string pbstrDescription)
{
pbstrDescription = null;
string description;
int hr = this.get_CanonicalName(out description);
if(ErrorHandler.Succeeded(hr))
pbstrDescription = this.Project.GetOutputGroupDescription(description);
return hr;
}
public virtual int get_DisplayName(out string pbstrDisplayName)
{
pbstrDisplayName = null;
string displayName;
int hr = this.get_CanonicalName(out displayName);
if(ErrorHandler.Succeeded(hr))
pbstrDisplayName = this.Project.GetOutputGroupDisplayName(displayName);
return hr;
}
public virtual int get_KeyOutput(out string pbstrCanonicalName)
{
pbstrCanonicalName = null;
if(keyOutput == null)
Refresh();
if(keyOutput == null)
{
pbstrCanonicalName = String.Empty;
return VSConstants.S_FALSE;
}
return keyOutput.get_CanonicalName(out pbstrCanonicalName);
}
public virtual int get_KeyOutputObject(out IVsOutput2 ppKeyOutput)
{
if(keyOutput == null)
Refresh();
ppKeyOutput = keyOutput;
if(ppKeyOutput == null)
return VSConstants.S_FALSE;
return VSConstants.S_OK;
}
public virtual int get_Outputs(uint celt, IVsOutput2[] rgpcfg, uint[] pcActual)
{
// Ensure that we are refreshed. This is somewhat of a hack that enables project to
// project reference scenarios to work. Normally, output groups are populated as part
// of build. However, in the project to project reference case, what ends up happening
// is that the referencing projects requests the referenced project's output group
// before a build is done on the referenced project.
//
// Furthermore, the project auto toolbox manager requires output groups to be populated
// on project reopen as well...
//
// In the end, this is probably the right thing to do, though -- as it keeps the output
// groups always up to date.
Refresh();
// See if only the caller only wants to know the count
if(celt == 0 || rgpcfg == null)
{
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = (uint)outputs.Count;
return VSConstants.S_OK;
}
// Fill the array with our outputs
uint count = 0;
foreach(Output output in outputs)
{
if(rgpcfg.Length > count && celt > count && output != null)
{
rgpcfg[count] = output;
++count;
}
}
if(pcActual != null && pcActual.Length > 0)
pcActual[0] = count;
// If the number asked for does not match the number returned, return S_FALSE
return (count == celt) ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public virtual int get_ProjectCfg(out IVsProjectCfg2 ppIVsProjectCfg2)
{
ppIVsProjectCfg2 = (IVsProjectCfg2)this.projectCfg;
return VSConstants.S_OK;
}
public virtual int get_Property(string pszProperty, out object pvar)
{
pvar = project.GetProjectProperty(pszProperty);
return VSConstants.S_OK;
}
#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;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.SignatureHelp.Presentation
{
internal partial class SignatureHelpPresenter
{
private class SignatureHelpPresenterSession : ForegroundThreadAffinitizedObject, ISignatureHelpPresenterSession
{
private readonly ISignatureHelpBroker _sigHelpBroker;
private readonly ITextView _textView;
private readonly ITextBuffer _subjectBuffer;
public event EventHandler<EventArgs> Dismissed;
public event EventHandler<SignatureHelpItemEventArgs> ItemSelected;
private IBidirectionalMap<SignatureHelpItem, Signature> _signatureMap;
private IList<SignatureHelpItem> _signatureHelpItems;
private SignatureHelpItem _selectedItem;
private ISignatureHelpSession _editorSessionOpt;
private bool _ignoreSelectionStatusChangedEvent;
public SignatureHelpPresenterSession(
ISignatureHelpBroker sigHelpBroker,
ITextView textView,
ITextBuffer subjectBuffer)
{
_sigHelpBroker = sigHelpBroker;
_textView = textView;
_subjectBuffer = subjectBuffer;
}
public void PresentItems(
ITrackingSpan triggerSpan,
IList<SignatureHelpItem> signatureHelpItems,
SignatureHelpItem selectedItem,
int? selectedParameter)
{
_signatureHelpItems = signatureHelpItems;
_selectedItem = selectedItem;
// Create all the editor signatures for the sig help items we have.
this.CreateSignatures(triggerSpan, selectedParameter);
// It's a new list of items. Either create the editor session if this is the
// first time, or ask the editor session that we already have to recalculate.
if (_editorSessionOpt == null)
{
// We're tracking the caret. Don't have the editor do it.
_editorSessionOpt = _sigHelpBroker.CreateSignatureHelpSession(
_textView,
triggerSpan.GetStartTrackingPoint(PointTrackingMode.Negative),
trackCaret: false);
var debugTextView = _textView as IDebuggerTextView;
if (debugTextView != null && !debugTextView.IsImmediateWindow)
{
debugTextView.HACK_StartCompletionSession(_editorSessionOpt);
}
_editorSessionOpt.Dismissed += (s, e) => OnEditorSessionDismissed();
_editorSessionOpt.SelectedSignatureChanged += OnSelectedSignatureChanged;
}
// So here's the deal. We cannot create the editor session and give it the right
// signatures (even though we know what they are). Instead, the session with
// call back into the ISignatureHelpSourceProvider (which is us) to get those
// values. It will pass itself along with the calls back into
// ISignatureHelpSourceProvider. So, in order to make that connection work, we
// add properties to the session so that we can call back into ourselves, get
// the signatures and add it to the session.
if (!_editorSessionOpt.Properties.ContainsProperty(s_augmentSessionKey))
{
_editorSessionOpt.Properties.AddProperty(s_augmentSessionKey, this);
}
try
{
// Don't want to get any callbacks while we do this.
_ignoreSelectionStatusChangedEvent = true;
_editorSessionOpt.Recalculate();
// Now let the editor know what the currently selected item is.
Contract.Requires(_signatureMap.ContainsKey(selectedItem));
Contract.ThrowIfNull(_signatureMap);
var defaultValue = _signatureMap.GetValueOrDefault(_selectedItem);
if (_editorSessionOpt != null)
{
_editorSessionOpt.SelectedSignature = defaultValue;
}
}
finally
{
_ignoreSelectionStatusChangedEvent = false;
}
}
private void CreateSignatures(
ITrackingSpan triggerSpan,
int? selectedParameter)
{
_signatureMap = BidirectionalMap<SignatureHelpItem, Signature>.Empty;
foreach (var item in _signatureHelpItems)
{
_signatureMap = _signatureMap.Add(item, new Signature(triggerSpan, item, GetParameterIndexForItem(item, selectedParameter)));
}
}
private static int GetParameterIndexForItem(SignatureHelpItem item, int? selectedParameter)
{
if (selectedParameter.HasValue)
{
if (selectedParameter.Value < item.Parameters.Length)
{
// If the selected parameter is within the range of parameters of this item then set
// that as the current parameter.
return selectedParameter.Value;
}
else if (item.IsVariadic)
{
// It wasn't in range, but the item takes an unlimited number of parameters. So
// just set current parameter to the last parameter (the variadic one).
return item.Parameters.Length - 1;
}
}
// It was out of bounds, there is no current parameter now.
return -1;
}
private void OnEditorSessionDismissed()
{
AssertIsForeground();
this.Dismissed?.Invoke(this, new EventArgs());
}
private void OnSelectedSignatureChanged(object sender, SelectedSignatureChangedEventArgs eventArgs)
{
AssertIsForeground();
if (_ignoreSelectionStatusChangedEvent)
{
return;
}
SignatureHelpItem helpItem;
Contract.ThrowIfFalse(_signatureMap.TryGetKey((Signature)eventArgs.NewSelectedSignature, out helpItem));
var helpItemSelected = this.ItemSelected;
if (helpItemSelected != null && helpItem != null)
{
helpItemSelected(this, new SignatureHelpItemEventArgs(helpItem));
}
}
public void Dismiss()
{
AssertIsForeground();
if (_editorSessionOpt == null)
{
// No editor session, nothing to do here.
return;
}
_editorSessionOpt.Dismiss();
_editorSessionOpt = null;
}
private bool ExecuteKeyboardCommand(IntellisenseKeyboardCommand command)
{
var target = _editorSessionOpt != null
? _editorSessionOpt.Presenter as IIntellisenseCommandTarget
: null;
return target != null && target.ExecuteKeyboardCommand(command);
}
public void SelectPreviousItem()
{
ExecuteKeyboardCommand(IntellisenseKeyboardCommand.Up);
}
public void SelectNextItem()
{
ExecuteKeyboardCommand(IntellisenseKeyboardCommand.Down);
}
// Call backs from our ISignatureHelpSourceProvider. Used to actually populate the vs
// session.
internal void AugmentSignatureHelpSession(IList<ISignature> signatures)
{
signatures.Clear();
signatures.AddRange(_signatureHelpItems.Select(_signatureMap.GetValueOrDefault));
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Primitives;
using osu.Framework.Utils;
using osu.Game.Extensions;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
using osu.Game.Rulesets.Osu.Objects;
using osu.Game.Screens.Edit.Compose.Components;
using osuTK;
namespace osu.Game.Rulesets.Osu.Edit
{
public class OsuSelectionHandler : EditorSelectionHandler
{
/// <summary>
/// During a transform, the initial origin is stored so it can be used throughout the operation.
/// </summary>
private Vector2? referenceOrigin;
/// <summary>
/// During a transform, the initial path types of a single selected slider are stored so they
/// can be maintained throughout the operation.
/// </summary>
private List<PathType?> referencePathTypes;
protected override void OnSelectionChanged()
{
base.OnSelectionChanged();
Quad quad = selectedMovableObjects.Length > 0 ? getSurroundingQuad(selectedMovableObjects) : new Quad();
SelectionBox.CanRotate = quad.Width > 0 || quad.Height > 0;
SelectionBox.CanScaleX = quad.Width > 0;
SelectionBox.CanScaleY = quad.Height > 0;
SelectionBox.CanReverse = EditorBeatmap.SelectedHitObjects.Count > 1 || EditorBeatmap.SelectedHitObjects.Any(s => s is Slider);
}
protected override void OnOperationEnded()
{
base.OnOperationEnded();
referenceOrigin = null;
referencePathTypes = null;
}
public override bool HandleMovement(MoveSelectionEvent<HitObject> moveEvent)
{
var hitObjects = selectedMovableObjects;
// this will potentially move the selection out of bounds...
foreach (var h in hitObjects)
h.Position += this.ScreenSpaceDeltaToParentSpace(moveEvent.ScreenSpaceDelta);
// but this will be corrected.
moveSelectionInBounds();
return true;
}
public override bool HandleReverse()
{
var hitObjects = EditorBeatmap.SelectedHitObjects;
double endTime = hitObjects.Max(h => h.GetEndTime());
double startTime = hitObjects.Min(h => h.StartTime);
bool moreThanOneObject = hitObjects.Count > 1;
foreach (var h in hitObjects)
{
if (moreThanOneObject)
h.StartTime = endTime - (h.GetEndTime() - startTime);
if (h is Slider slider)
{
var points = slider.Path.ControlPoints.ToArray();
Vector2 endPos = points.Last().Position.Value;
slider.Path.ControlPoints.Clear();
slider.Position += endPos;
PathType? lastType = null;
for (var i = 0; i < points.Length; i++)
{
var p = points[i];
p.Position.Value -= endPos;
// propagate types forwards to last null type
if (i == points.Length - 1)
p.Type.Value = lastType;
else if (p.Type.Value != null)
{
var newType = p.Type.Value;
p.Type.Value = lastType;
lastType = newType;
}
slider.Path.ControlPoints.Insert(0, p);
}
}
}
return true;
}
public override bool HandleFlip(Direction direction)
{
var hitObjects = selectedMovableObjects;
var selectedObjectsQuad = getSurroundingQuad(hitObjects);
foreach (var h in hitObjects)
{
h.Position = GetFlippedPosition(direction, selectedObjectsQuad, h.Position);
if (h is Slider slider)
{
foreach (var point in slider.Path.ControlPoints)
{
point.Position.Value = new Vector2(
(direction == Direction.Horizontal ? -1 : 1) * point.Position.Value.X,
(direction == Direction.Vertical ? -1 : 1) * point.Position.Value.Y
);
}
}
}
return true;
}
public override bool HandleScale(Vector2 scale, Anchor reference)
{
adjustScaleFromAnchor(ref scale, reference);
var hitObjects = selectedMovableObjects;
// for the time being, allow resizing of slider paths only if the slider is
// the only hit object selected. with a group selection, it's likely the user
// is not looking to change the duration of the slider but expand the whole pattern.
if (hitObjects.Length == 1 && hitObjects.First() is Slider slider)
scaleSlider(slider, scale);
else
scaleHitObjects(hitObjects, reference, scale);
moveSelectionInBounds();
return true;
}
private static void adjustScaleFromAnchor(ref Vector2 scale, Anchor reference)
{
// cancel out scale in axes we don't care about (based on which drag handle was used).
if ((reference & Anchor.x1) > 0) scale.X = 0;
if ((reference & Anchor.y1) > 0) scale.Y = 0;
// reverse the scale direction if dragging from top or left.
if ((reference & Anchor.x0) > 0) scale.X = -scale.X;
if ((reference & Anchor.y0) > 0) scale.Y = -scale.Y;
}
public override bool HandleRotation(float delta)
{
var hitObjects = selectedMovableObjects;
Quad quad = getSurroundingQuad(hitObjects);
referenceOrigin ??= quad.Centre;
foreach (var h in hitObjects)
{
h.Position = RotatePointAroundOrigin(h.Position, referenceOrigin.Value, delta);
if (h is IHasPath path)
{
foreach (var point in path.Path.ControlPoints)
point.Position.Value = RotatePointAroundOrigin(point.Position.Value, Vector2.Zero, delta);
}
}
// this isn't always the case but let's be lenient for now.
return true;
}
private void scaleSlider(Slider slider, Vector2 scale)
{
referencePathTypes ??= slider.Path.ControlPoints.Select(p => p.Type.Value).ToList();
Quad sliderQuad = GetSurroundingQuad(slider.Path.ControlPoints.Select(p => p.Position.Value));
// Limit minimum distance between control points after scaling to almost 0. Less than 0 causes the slider to flip, exactly 0 causes a crash through division by 0.
scale = Vector2.ComponentMax(new Vector2(Precision.FLOAT_EPSILON), sliderQuad.Size + scale) - sliderQuad.Size;
Vector2 pathRelativeDeltaScale = new Vector2(
sliderQuad.Width == 0 ? 0 : 1 + scale.X / sliderQuad.Width,
sliderQuad.Height == 0 ? 0 : 1 + scale.Y / sliderQuad.Height);
Queue<Vector2> oldControlPoints = new Queue<Vector2>();
foreach (var point in slider.Path.ControlPoints)
{
oldControlPoints.Enqueue(point.Position.Value);
point.Position.Value *= pathRelativeDeltaScale;
}
// Maintain the path types in case they were defaulted to bezier at some point during scaling
for (int i = 0; i < slider.Path.ControlPoints.Count; ++i)
slider.Path.ControlPoints[i].Type.Value = referencePathTypes[i];
//if sliderhead or sliderend end up outside playfield, revert scaling.
Quad scaledQuad = getSurroundingQuad(new OsuHitObject[] { slider });
(bool xInBounds, bool yInBounds) = isQuadInBounds(scaledQuad);
if (xInBounds && yInBounds && slider.Path.HasValidLength)
return;
foreach (var point in slider.Path.ControlPoints)
point.Position.Value = oldControlPoints.Dequeue();
}
private void scaleHitObjects(OsuHitObject[] hitObjects, Anchor reference, Vector2 scale)
{
scale = getClampedScale(hitObjects, reference, scale);
Quad selectionQuad = getSurroundingQuad(hitObjects);
foreach (var h in hitObjects)
h.Position = GetScaledPosition(reference, scale, selectionQuad, h.Position);
}
private (bool X, bool Y) isQuadInBounds(Quad quad)
{
bool xInBounds = (quad.TopLeft.X >= 0) && (quad.BottomRight.X <= DrawWidth);
bool yInBounds = (quad.TopLeft.Y >= 0) && (quad.BottomRight.Y <= DrawHeight);
return (xInBounds, yInBounds);
}
private void moveSelectionInBounds()
{
var hitObjects = selectedMovableObjects;
Quad quad = getSurroundingQuad(hitObjects);
Vector2 delta = Vector2.Zero;
if (quad.TopLeft.X < 0)
delta.X -= quad.TopLeft.X;
if (quad.TopLeft.Y < 0)
delta.Y -= quad.TopLeft.Y;
if (quad.BottomRight.X > DrawWidth)
delta.X -= quad.BottomRight.X - DrawWidth;
if (quad.BottomRight.Y > DrawHeight)
delta.Y -= quad.BottomRight.Y - DrawHeight;
foreach (var h in hitObjects)
h.Position += delta;
}
/// <summary>
/// Clamp scale for multi-object-scaling where selection does not exceed playfield bounds or flip.
/// </summary>
/// <param name="hitObjects">The hitobjects to be scaled</param>
/// <param name="reference">The anchor from which the scale operation is performed</param>
/// <param name="scale">The scale to be clamped</param>
/// <returns>The clamped scale vector</returns>
private Vector2 getClampedScale(OsuHitObject[] hitObjects, Anchor reference, Vector2 scale)
{
float xOffset = ((reference & Anchor.x0) > 0) ? -scale.X : 0;
float yOffset = ((reference & Anchor.y0) > 0) ? -scale.Y : 0;
Quad selectionQuad = getSurroundingQuad(hitObjects);
//todo: this is not always correct for selections involving sliders. This approximation assumes each point is scaled independently, but sliderends move with the sliderhead.
Quad scaledQuad = new Quad(selectionQuad.TopLeft.X + xOffset, selectionQuad.TopLeft.Y + yOffset, selectionQuad.Width + scale.X, selectionQuad.Height + scale.Y);
//max Size -> playfield bounds
if (scaledQuad.TopLeft.X < 0)
scale.X += scaledQuad.TopLeft.X;
if (scaledQuad.TopLeft.Y < 0)
scale.Y += scaledQuad.TopLeft.Y;
if (scaledQuad.BottomRight.X > DrawWidth)
scale.X -= scaledQuad.BottomRight.X - DrawWidth;
if (scaledQuad.BottomRight.Y > DrawHeight)
scale.Y -= scaledQuad.BottomRight.Y - DrawHeight;
//min Size -> almost 0. Less than 0 causes the quad to flip, exactly 0 causes scaling to get stuck at minimum scale.
Vector2 scaledSize = selectionQuad.Size + scale;
Vector2 minSize = new Vector2(Precision.FLOAT_EPSILON);
scale = Vector2.ComponentMax(minSize, scaledSize) - selectionQuad.Size;
return scale;
}
/// <summary>
/// Returns a gamefield-space quad surrounding the provided hit objects.
/// </summary>
/// <param name="hitObjects">The hit objects to calculate a quad for.</param>
private Quad getSurroundingQuad(OsuHitObject[] hitObjects) =>
GetSurroundingQuad(hitObjects.SelectMany(h =>
{
if (h is IHasPath path)
{
return new[]
{
h.Position,
// can't use EndPosition for reverse slider cases.
h.Position + path.Path.PositionAt(1)
};
}
return new[] { h.Position };
}));
/// <summary>
/// All osu! hitobjects which can be moved/rotated/scaled.
/// </summary>
private OsuHitObject[] selectedMovableObjects => SelectedItems.OfType<OsuHitObject>()
.Where(h => !(h is Spinner))
.ToArray();
}
}
| |
// ************************ ParseSingleQuotes : char ************************
//
// group newline = { '\n', '\r' }
// ParseSingleQuote : newline = decline, '\'' = accept, '\\' = EscapedChar,
// default = ParseSingleQuote;
// EscapedChar : newline = decline, default = ParseSingleQuote;
//
//
// This file was automatically generated from a tool that converted the
// above state machine definition into this state machine class.
// Any changes to this code will be replaced the next time the code is generated.
using System;
using System.Collections.Generic;
namespace test
{
public class ParseSingleQuotes
{
public enum States
{
ParseSingleQuote = 0, EscapedChar = 1,
}
private States? state = null;
public States? CurrentState { get { return state; } }
private char currentCommand;
public char CurrentCommand { get { return currentCommand; } }
private bool reset = false;
private Action<char> onParseSingleQuoteState = null;
private Action<char> onParseSingleQuoteEnter = null;
private Action<char> onParseSingleQuoteExit = null;
private Action<char> onEscapedCharState = null;
private Action<char> onEscapedCharEnter = null;
private Action<char> onEscapedCharExit = null;
private Action<char> onAccept = null;
private Action<char> onDecline = null;
private Action<char> onEnd = null;
public bool? Input(Queue<char> data)
{
if (reset)
state = null;
bool? result = null;
if (data == null)
return null;
Reset:
reset = false;
switch (state)
{
case null:
if (data.Count > 0)
{
state = States.ParseSingleQuote;
goto ResumeParseSingleQuote;
}
else
goto End;
case States.ParseSingleQuote:
goto ResumeParseSingleQuote;
case States.EscapedChar:
goto ResumeEscapedChar;
}
EnterParseSingleQuote:
state = States.ParseSingleQuote;
if (onParseSingleQuoteEnter != null)
onParseSingleQuoteEnter(currentCommand);
ParseSingleQuote:
if (onParseSingleQuoteState != null)
onParseSingleQuoteState(currentCommand);
ResumeParseSingleQuote:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\n':
if (onParseSingleQuoteExit != null)
onParseSingleQuoteExit(currentCommand);
goto Decline;
case '\r':
if (onParseSingleQuoteExit != null)
onParseSingleQuoteExit(currentCommand);
goto Decline;
case '\'':
if (onParseSingleQuoteExit != null)
onParseSingleQuoteExit(currentCommand);
goto Accept;
case '\\':
if (onParseSingleQuoteExit != null)
onParseSingleQuoteExit(currentCommand);
goto EnterEscapedChar;
default:
goto ParseSingleQuote;
}
EnterEscapedChar:
state = States.EscapedChar;
if (onEscapedCharEnter != null)
onEscapedCharEnter(currentCommand);
if (onEscapedCharState != null)
onEscapedCharState(currentCommand);
ResumeEscapedChar:
if (data.Count > 0)
currentCommand = data.Dequeue();
else
goto End;
switch (currentCommand)
{
case '\n':
if (onEscapedCharExit != null)
onEscapedCharExit(currentCommand);
goto Decline;
case '\r':
if (onEscapedCharExit != null)
onEscapedCharExit(currentCommand);
goto Decline;
default:
if (onEscapedCharExit != null)
onEscapedCharExit(currentCommand);
goto EnterParseSingleQuote;
}
Accept:
result = true;
state = null;
if (onAccept != null)
onAccept(currentCommand);
goto End;
Decline:
result = false;
state = null;
if (onDecline != null)
onDecline(currentCommand);
goto End;
End:
if (onEnd != null)
onEnd(currentCommand);
if (reset)
{
goto Reset;
}
return result;
}
public void AddOnParseSingleQuote(Action<char> addedFunc)
{
onParseSingleQuoteState += addedFunc;
}
public void AddOnEscapedChar(Action<char> addedFunc)
{
onEscapedCharState += addedFunc;
}
public void AddOnParseSingleQuoteEnter(Action<char> addedFunc)
{
onParseSingleQuoteEnter += addedFunc;
}
public void AddOnEscapedCharEnter(Action<char> addedFunc)
{
onEscapedCharEnter += addedFunc;
}
public void AddOnParseSingleQuoteExit(Action<char> addedFunc)
{
onParseSingleQuoteExit += addedFunc;
}
public void AddOnEscapedCharExit(Action<char> addedFunc)
{
onEscapedCharExit += addedFunc;
}
public void AddOnAccept(Action<char> addedFunc)
{
onAccept += addedFunc;
}
public void AddOnDecline(Action<char> addedFunc)
{
onDecline += addedFunc;
}
public void AddOnEnd(Action<char> addedFunc)
{
onEnd += addedFunc;
}
internal void addOnAllStates( Action<char> addedFunc )
{
onParseSingleQuoteState += addedFunc;
onEscapedCharState += addedFunc;
}
public void ResetStateOnEnd()
{
state = null;
reset = true;
}
}
}
| |
using System;
using it.unifi.dsi.stlab.networkreasoner.model.gas;
namespace it.unifi.dsi.stlab.networkreasoner.gas.system.formulae
{
public class GasFormulaVisitorExactlyDimensioned : GasFormulaVisitor
{
// for ease the implementation we assume that the ambiental
// parameters are passed from the outside and stored here
// as an instance variable.
public AmbientParameters AmbientParameters{ get; set; }
#region GasFormulaVisitor implementation
public virtual Double visitCoefficientFormulaForNodeWithSupplyGadget (
CoefficientFormulaForNodeWithSupplyGadget aSupplyNodeFormula)
{
var AirPressureInBar = this.computeAirPressureFromHeightHolder (
aSupplyNodeFormula);
var numerator = aSupplyNodeFormula.GadgetSetupPressureInMillibar / 1000d +
AirPressureInBar;
var denominator = AmbientParameters.RefPressureInBar;
var Hsetup = Math.Pow (numerator / denominator, 2d);
return Hsetup;
}
public double visitAirPressureFormulaForNodes (
AirPressureFormulaForNodes anAirPressureFormula)
{
double airPressureInBar = AmbientParameters.AirPressureInBar *
Math.Exp (-(AmbientParameters.GravitationalAcceleration * anAirPressureFormula.NodeHeight) /
(AmbientParameters.AirRconstant () * AmbientParameters.AirTemperatureInKelvin)
);
return airPressureInBar;
}
public virtual double visitRelativePressureFromAdimensionalPressureFormulaForNodes (
RelativePressureFromAdimensionalPressureFormulaForNodes aRelativePressureFromAdimensionalPressureFormula)
{
var AirPressureInBar = this.computeAirPressureFromHeightHolder (
aRelativePressureFromAdimensionalPressureFormula);
var result = Math.Sqrt (aRelativePressureFromAdimensionalPressureFormula.AdimensionalPressure) *
AmbientParameters.RefPressureInBar;
return (result - AirPressureInBar) * 1e3;
}
public virtual double visitAbsolutePressureFromAdimensionalPressureFormulaForNodes (
AbsolutePressureFromAdimensionalPressureFormulaForNodes aAbsolutePressureFromAdimensionalPressureFormula)
{
var result = Math.Sqrt (aAbsolutePressureFromAdimensionalPressureFormula.AdimensionalPressure) *
AmbientParameters.RefPressureInBar;
return result;
}
public virtual double visitCovariantLittleKFormula (
CovariantLittleKFormula covariantLittleKFormula)
{
return this.AmbientParameters.Rconstant () +
this.weightedHeightsDifferenceFor (covariantLittleKFormula);
}
public virtual double visitControVariantLittleKFormula (
ControVariantLittleKFormula controVariantLittleKFormula)
{
return this.AmbientParameters.Rconstant () -
this.weightedHeightsDifferenceFor (controVariantLittleKFormula);
}
public double visitKvalueFormula (KvalueFormula aKvalueFormula)
{
var f = aKvalueFormula.EdgeFvalue;
var A = this.AmbientParameters.Aconstant () /
Math.Pow (aKvalueFormula.EdgeDiameterInMillimeters / 1000d, 5d);
var unknownForStartNode = aKvalueFormula.UnknownForEdgeStartNode;
var unknownForEndNode = aKvalueFormula.UnknownForEdgeEndNode;
var weightedHeightsDifference = Math.Max (Math.Abs (
aKvalueFormula.EdgeCovariantLittleK * unknownForStartNode -
aKvalueFormula.EdgeControVariantLittleK * unknownForEndNode
), 0.1d);
var length = aKvalueFormula.EdgeLength;
var K = 3600d / Math.Sqrt (f * A * length * weightedHeightsDifference);
return K;
}
public AmatrixQuadruplet visitAmatrixQuadrupletFormulaForSwitchedOnEdges (
AmatrixQuadrupletFormulaForSwitchedOnEdges AmatrixQuadrupletFormulaForSwitchedOnEdges)
{
double coVariant;
double controVariant;
computeCovariantAndControVariantFromKvalueHolder (
AmatrixQuadrupletFormulaForSwitchedOnEdges,
out coVariant, out controVariant);
double initialValue = 0d;
AmatrixQuadruplet result = new AmatrixQuadruplet ();
result.StartNodeStartNodeUpdater = cumulate => -coVariant + cumulate;
result.StartNodeStartNodeInitialValue = initialValue;
result.StartNodeEndNodeUpdater = cumulate => controVariant + cumulate;
result.StartNodeEndNodeInitialValue = initialValue;
result.EndNodeStartNodeUpdater = cumulate => coVariant + cumulate;
result.EndNodeStartNodeInitialValue = initialValue;
result.EndNodeEndNodeUpdater = cumulate => -controVariant + cumulate;
result.EndNodeEndNodeInitialValue = initialValue;
return result;
}
public AmatrixQuadruplet visitJacobianMatrixQuadrupletFormulaForSwitchedOnEdges (
JacobianMatrixQuadrupletFormulaForSwitchedOnEdges
jacobianMatrixQuadrupletFormulaForSwitchedOnEdges
)
{
double coVariant;
double controVariant;
computeCovariantAndControVariantFromKvalueHolder (
jacobianMatrixQuadrupletFormulaForSwitchedOnEdges,
out coVariant, out controVariant);
double initialValue = 0d;
AmatrixQuadruplet result = new AmatrixQuadruplet ();
result.StartNodeStartNodeUpdater = cumulate => -coVariant / 2d + cumulate;
result.StartNodeStartNodeInitialValue = initialValue;
result.StartNodeEndNodeUpdater = cumulate => controVariant / 2d + cumulate;
result.StartNodeEndNodeInitialValue = initialValue;
result.EndNodeStartNodeUpdater = cumulate => coVariant / 2d + cumulate;
result.EndNodeStartNodeInitialValue = initialValue;
result.EndNodeEndNodeUpdater = cumulate => -controVariant / 2d + cumulate;
result.EndNodeEndNodeInitialValue = initialValue;
return result;
}
public double visitQvalueFormula (
QvalueFormula QvalueFormula)
{
var weightedUnknownsDifference =
QvalueFormula.EdgeCovariantLittleK * QvalueFormula.UnknownForEdgeStartNode -
QvalueFormula.EdgeControVariantLittleK * QvalueFormula.UnknownForEdgeEndNode;
return QvalueFormula.EdgeKvalue * weightedUnknownsDifference;
}
public double visitFvalueFormula (FvalueFormula FvalueFormula)
{
double numeratorForRe = Math.Abs (FvalueFormula.EdgeQvalue) / 900.0d *
this.AmbientParameters.RefDensity ();
var denominatorForRe = Math.PI * (FvalueFormula.EdgeDiameterInMillimeters / 1000d) *
this.AmbientParameters.ViscosityInPascalTimesSecond;
var Re = Math.Max (numeratorForRe / denominatorForRe, 1.0d);
// Colebrook equation
var augend = FvalueFormula.EdgeRoughnessInMicron /
(FvalueFormula.EdgeDiameterInMillimeters * 1000d * 3.71);
var addend = 2.51d / (Re * Math.Sqrt (FvalueFormula.EdgeFvalue));
var toInvert = -2d * Math.Log10 (augend + addend);
var Fvalue = Math.Pow (1d / toInvert, 2d);
if (Re < 2000.0d) {
Fvalue = 64.0d / Re;
} else if (Re < 4000.0d) {
Fvalue = .00277 * Math.Pow (Re, .3219);
}
/* Renouard equation
var Fvalue = 0.172d * Math.Pow (Re, -0.18d);
if (Re < 1365.0d) {
Fvalue = 64.0d / Re;
}
*/
return Fvalue;
}
public double visitVelocityValueFormula (VelocityValueFormula velocityValueFormula)
{
double Qvalue = velocityValueFormula.Qvalue;
double diameter = velocityValueFormula.Diameter;
double absolutePressureOfStartNode = velocityValueFormula.AbsolutePressureOfStartNode;
double absolutePressureOfEndNode = velocityValueFormula.AbsolutePressureOfEndNode;
var minPressure = Math.Min (absolutePressureOfStartNode, absolutePressureOfEndNode);
var numerator = (Qvalue / 3600d) * AmbientParameters.RefPressureInBar / minPressure;
var denominator = Math.PI * Math.Pow (diameter * 1e-3, 2d) / 4d;
var result = numerator / denominator;
return result;
}
#endregion
#region Utility methods, most of them allow behavior factorization.
protected virtual double weightedHeightsDifferenceFor (
AbstractLittleKFormula abstractLittleKFormula)
{
var difference = abstractLittleKFormula.HeightOfStartNode -
abstractLittleKFormula.HeightOfEndNode;
var rate = this.AmbientParameters.GravitationalAcceleration /
this.AmbientParameters.ElementTemperatureInKelvin;
return rate * difference;
}
protected virtual double computeAirPressureFromHeightHolder (
NodeHeightHolder nodeHeightHolder)
{
var airPressureFormula = new AirPressureFormulaForNodes ();
airPressureFormula.NodeHeight = nodeHeightHolder.NodeHeight;
var airPressureInBar = airPressureFormula.accept (this);
return airPressureInBar;
}
protected virtual void computeCovariantAndControVariantFromKvalueHolder (
KvalueAndLittleKHolder holder,
out double coVariant,
out double controVariant)
{
coVariant = holder.EdgeKvalue *
holder.EdgeCovariantLittleK;
controVariant = holder.EdgeKvalue *
holder.EdgeControVariantLittleK;
}
#endregion
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using Common.Logging;
using Spring.Data.Core;
using Spring.Transaction;
using Spring.Transaction.Support;
using Spring.Util;
#if NETSTANDARD
using Experimental.System.Messaging;
#else
using System.Messaging;
#endif
namespace Spring.Messaging.Core
{
/// <summary>
/// <see cref="IPlatformTransactionManager"/> implementation for MSMQ. Binds a
/// MessageQueueTransaction to the thread.
/// </summary>
/// <remarks>
/// <para>
/// This local strategy is an alternative to executing MSMQ operations within
/// DTC transactions. Its advantage is that multiple MSMQ operations can
/// easily participate within the same local MessagingTransaction transparently when
/// using the <see cref="MessageQueueTemplate"/> class for send and recieve operations
/// and not pay the overhead of a DTC transaction.
/// </para>
/// <para>Transaction synchronization is turned off by default, as this manager might
/// be used alongside a IDbProvider-based Spring transaction manager such as the
/// ADO.NET <see cref="AdoPlatformTransactionManager"/>.
/// which has stronger needs for synchronization.</para>
/// </remarks>
/// <author>Mark Pollack</author>
public class MessageQueueTransactionManager : AbstractPlatformTransactionManager
{
/// <summary>
/// Location where the message transaction is stored in thread local storage.
/// </summary>
public static readonly string CURRENT_TRANSACTION_SLOTNAME =
UniqueKey.GetTypeScopedString(typeof (MessageQueueTransaction), "Current");
#region Logging Definition
private static readonly ILog LOG = LogManager.GetLogger(typeof (MessageQueueTransactionManager));
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="MessageQueueTransactionManager"/> class.
/// </summary>
/// <remarks>
/// Turns off transaction synchronization by default, as this manager might
/// be used alongside a DbProvider-based Spring transaction manager like
/// AdoPlatformTransactionManager, which has stronger needs for synchronization.
/// Only one manager is allowed to drive synchronization at any point of time.
/// </remarks>
public MessageQueueTransactionManager()
{
TransactionSynchronization = TransactionSynchronizationState.Never;
}
/// <summary>
/// Return the current transaction object.
/// </summary>
/// <returns>The current transaction object.</returns>
/// <exception cref="Spring.Transaction.CannotCreateTransactionException">
/// If transaction support is not available.
/// </exception>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of lookup or system errors.
/// </exception>
protected override object DoGetTransaction()
{
MessageQueueTransactionObject txObject = new MessageQueueTransactionObject();
txObject.ResourceHolder =
(MessageQueueResourceHolder) TransactionSynchronizationManager.GetResource(CURRENT_TRANSACTION_SLOTNAME);
return txObject;
}
/// <summary>
/// Check if the given transaction object indicates an existing transaction
/// (that is, a transaction which has already started).
/// </summary>
/// <param name="transaction">MessageQueueTransactionObject object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <returns>
/// True if there is an existing transaction.
/// </returns>
protected override bool IsExistingTransaction(object transaction)
{
MessageQueueTransactionObject txObject = (MessageQueueTransactionObject) transaction;
return (txObject.ResourceHolder != null);
}
/// <summary>
/// Begin a new transaction with the given transaction definition.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <param name="definition"><see cref="Spring.Transaction.ITransactionDefinition"/> instance, describing
/// propagation behavior, isolation level, timeout etc.</param>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of creation or system errors.
/// </exception>
protected override void DoBegin(object transaction, ITransactionDefinition definition)
{
MessageQueueTransactionObject txObject = (MessageQueueTransactionObject) transaction;
MessageQueueTransaction mqt = new MessageQueueTransaction();
mqt.Begin();
txObject.ResourceHolder = new MessageQueueResourceHolder(mqt);
txObject.ResourceHolder.SynchronizedWithTransaction = true;
int timeout = DetermineTimeout(definition);
if (timeout != DefaultTransactionDefinition.TIMEOUT_DEFAULT)
{
txObject.ResourceHolder.TimeoutInSeconds = timeout;
}
TransactionSynchronizationManager.BindResource(CURRENT_TRANSACTION_SLOTNAME, txObject.ResourceHolder);
}
/// <summary>
/// Suspend the resources of the current transaction.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <returns>
/// An object that holds suspended resources (will be kept unexamined for passing it into
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoResume"/>.)
/// </returns>
protected override object DoSuspend(object transaction)
{
MessageQueueTransactionObject txObject = (MessageQueueTransactionObject) transaction;
txObject.ResourceHolder = null;
return TransactionSynchronizationManager.UnbindResource(CURRENT_TRANSACTION_SLOTNAME);
}
/// <summary>
/// Resume the resources of the current transaction.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <param name="suspendedResources">The object that holds suspended resources as returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoSuspend"/>.</param>
protected override void DoResume(object transaction, object suspendedResources)
{
MessageQueueResourceHolder queueHolder = (MessageQueueResourceHolder) suspendedResources;
TransactionSynchronizationManager.BindResource(CURRENT_TRANSACTION_SLOTNAME, queueHolder);
}
/// <summary>
/// Perform an actual commit on the given transaction.
/// </summary>
/// <param name="status">The status representation of the transaction.</param>
/// <remarks>
/// <p>
/// An implementation does not need to check the rollback-only flag.
/// </p>
/// </remarks>
protected override void DoCommit(DefaultTransactionStatus status)
{
MessageQueueTransactionObject txObject = (MessageQueueTransactionObject) status.Transaction;
MessageQueueTransaction transaction = txObject.ResourceHolder.MessageQueueTransaction;
try
{
if (LOG.IsDebugEnabled)
{
LOG.Debug("Committing MessageQueueTransaction");
}
transaction.Commit();
}
catch (MessageQueueException ex)
{
throw new TransactionSystemException("Could not commit DefaultMessageQueue transaction", ex);
}
}
/// <summary>
/// Perform an actual rollback on the given transaction, calls Transaction.Abort().
/// </summary>
/// <param name="status">The status representation of the transaction.</param>
/// <remarks>
/// An implementation does not need to check the new transaction flag.
/// </remarks>
protected override void DoRollback(DefaultTransactionStatus status)
{
MessageQueueTransactionObject txObject = (MessageQueueTransactionObject) status.Transaction;
MessageQueueTransaction transaction = txObject.ResourceHolder.MessageQueueTransaction;
try
{
if (LOG.IsDebugEnabled)
{
LOG.Debug("Committing MessageQueueTransaction");
}
transaction.Abort();
}
catch (MessageQueueException ex)
{
throw new TransactionSystemException("Could not roll back DefaultMessageQueue transaction", ex);
}
}
/// <summary>
/// Set the given transaction rollback-only. Only called on rollback
/// if the current transaction takes part in an existing one.
/// </summary>
/// <param name="status">The status representation of the transaction.</param>
/// <remarks>Default implementation throws an IllegalTransactionStateException,
/// assuming that participating in existing transactions is generally not
/// supported. Subclasses are of course encouraged to provide such support.
/// </remarks>
/// <exception cref="Spring.Transaction.TransactionException">
/// In the case of system errors.
/// </exception>
protected override void DoSetRollbackOnly(DefaultTransactionStatus status)
{
MessageQueueTransactionObject txObject = (MessageQueueTransactionObject) status.Transaction;
txObject.ResourceHolder.RollbackOnly = true;
}
/// <summary>
/// Cleanup resources after transaction completion.
/// </summary>
/// <param name="transaction">Transaction object returned by
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoGetTransaction"/>.</param>
/// <remarks>
/// <para>
/// Called after <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoCommit"/>
/// and
/// <see cref="Spring.Transaction.Support.AbstractPlatformTransactionManager.DoRollback"/>
/// execution on any outcome.
/// </para>
/// </remarks>
protected override void DoCleanupAfterCompletion(object transaction)
{
MessageQueueTransactionObject txObject = (MessageQueueTransactionObject) transaction;
TransactionSynchronizationManager.UnbindResource(CURRENT_TRANSACTION_SLOTNAME);
txObject.ResourceHolder.Clear();
}
private class MessageQueueTransactionObject : ISmartTransactionObject
{
private MessageQueueResourceHolder resourceHolder;
public MessageQueueResourceHolder ResourceHolder
{
get { return resourceHolder; }
set { resourceHolder = value; }
}
#region ISmartTransactionObject Members
public bool RollbackOnly
{
get { return resourceHolder.RollbackOnly; }
}
#endregion
}
}
}
| |
using System;
using System.Diagnostics;
using u8 = System.Byte;
using u32 = System.UInt32;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that are called by the parser
** to handle UPDATE statements.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
**
*************************************************************************
*/
//#include "sqliteInt.h"
#if !SQLITE_OMIT_VIRTUALTABLE
/* Forward declaration */
//static void updateVirtualTable(
//Parse pParse, /* The parsing context */
//SrcList pSrc, /* The virtual table to be modified */
//Table pTab, /* The virtual table */
//ExprList pChanges, /* The columns to change in the UPDATE statement */
//Expr pRowidExpr, /* Expression used to recompute the rowid */
//int aXRef, /* Mapping from columns of pTab to entries in pChanges */
//Expr *pWhere, /* WHERE clause of the UPDATE statement */
//int onError /* ON CONFLICT strategy */
//);
#endif // * SQLITE_OMIT_VIRTUALTABLE */
/*
** The most recently coded instruction was an OP_Column to retrieve the
** i-th column of table pTab. This routine sets the P4 parameter of the
** OP_Column to the default value, if any.
**
** The default value of a column is specified by a DEFAULT clause in the
** column definition. This was either supplied by the user when the table
** was created, or added later to the table definition by an ALTER TABLE
** command. If the latter, then the row-records in the table btree on disk
** may not contain a value for the column and the default value, taken
** from the P4 parameter of the OP_Column instruction, is returned instead.
** If the former, then all row-records are guaranteed to include a value
** for the column and the P4 value is not required.
**
** Column definitions created by an ALTER TABLE command may only have
** literal default values specified: a number, null or a string. (If a more
** complicated default expression value was provided, it is evaluated
** when the ALTER TABLE is executed and one of the literal values written
** into the sqlite_master table.)
**
** Therefore, the P4 parameter is only required if the default value for
** the column is a literal number, string or null. The sqlite3ValueFromExpr()
** function is capable of transforming these types of expressions into
** sqlite3_value objects.
**
** If parameter iReg is not negative, code an OP_RealAffinity instruction
** on register iReg. This is used when an equivalent integer value is
** stored in place of an 8-byte floating point value in order to save
** space.
*/
static void sqlite3ColumnDefault( Vdbe v, Table pTab, int i, int iReg )
{
Debug.Assert( pTab != null );
if ( null == pTab.pSelect )
{
sqlite3_value pValue = new sqlite3_value();
int enc = ENC( sqlite3VdbeDb( v ) );
Column pCol = pTab.aCol[i];
#if SQLITE_DEBUG
VdbeComment( v, "%s.%s", pTab.zName, pCol.zName );
#endif
Debug.Assert( i < pTab.nCol );
sqlite3ValueFromExpr( sqlite3VdbeDb( v ), pCol.pDflt, enc,
pCol.affinity, ref pValue );
if ( pValue != null )
{
sqlite3VdbeChangeP4( v, -1, pValue, P4_MEM );
}
#if !SQLITE_OMIT_FLOATING_POINT
if ( iReg >= 0 && pTab.aCol[i].affinity == SQLITE_AFF_REAL )
{
sqlite3VdbeAddOp1( v, OP_RealAffinity, iReg );
}
#endif
}
}
/*
** Process an UPDATE statement.
**
** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
** \_______/ \________/ \______/ \________________/
* onError pTabList pChanges pWhere
*/
static void sqlite3Update(
Parse pParse, /* The parser context */
SrcList pTabList, /* The table in which we should change things */
ExprList pChanges, /* Things to be changed */
Expr pWhere, /* The WHERE clause. May be null */
int onError /* How to handle constraint errors */
)
{
int i, j; /* Loop counters */
Table pTab; /* The table to be updated */
int addr = 0; /* VDBE instruction address of the start of the loop */
WhereInfo pWInfo; /* Information about the WHERE clause */
Vdbe v; /* The virtual database engine */
Index pIdx; /* For looping over indices */
int nIdx; /* Number of indices that need updating */
int iCur; /* VDBE Cursor number of pTab */
sqlite3 db; /* The database structure */
int[] aRegIdx = null; /* One register assigned to each index to be updated */
int[] aXRef = null; /* aXRef[i] is the index in pChanges.a[] of the
** an expression for the i-th column of the table.
** aXRef[i]==-1 if the i-th column is not changed. */
bool chngRowid; /* True if the record number is being changed */
Expr pRowidExpr = null; /* Expression defining the new record number */
bool openAll = false; /* True if all indices need to be opened */
AuthContext sContext; /* The authorization context */
NameContext sNC; /* The name-context to resolve expressions in */
int iDb; /* Database containing the table being updated */
bool okOnePass; /* True for one-pass algorithm without the FIFO */
bool hasFK; /* True if foreign key processing is required */
#if !SQLITE_OMIT_TRIGGER
bool isView; /* True when updating a view (INSTEAD OF trigger) */
Trigger pTrigger; /* List of triggers on pTab, if required */
int tmask = 0; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
#endif
int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
/* Register Allocations */
int regRowCount = 0; /* A count of rows changed */
int regOldRowid; /* The old rowid */
int regNewRowid; /* The new rowid */
int regNew;
int regOld = 0;
int regRowSet = 0; /* Rowset of rows to be updated */
sContext = new AuthContext(); //memset( &sContext, 0, sizeof( sContext ) );
db = pParse.db;
if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
{
goto update_cleanup;
}
Debug.Assert( pTabList.nSrc == 1 );
/* Locate the table which we want to update.
*/
pTab = sqlite3SrcListLookup( pParse, pTabList );
if ( pTab == null )
goto update_cleanup;
iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
/* Figure out if we have any triggers and if the table being
** updated is a view.
*/
#if !SQLITE_OMIT_TRIGGER
pTrigger = sqlite3TriggersExist( pParse, pTab, TK_UPDATE, pChanges, out tmask );
isView = pTab.pSelect != null;
Debug.Assert( pTrigger != null || tmask == 0 );
#else
const Trigger pTrigger = null;//# define pTrigger 0
const int tmask = 0; //# define tmask 0
#endif
#if SQLITE_OMIT_TRIGGER || SQLITE_OMIT_VIEW
// # undef isView
const bool isView = false; //# define isView 0
#endif
if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
{
goto update_cleanup;
}
if ( sqlite3IsReadOnly( pParse, pTab, tmask ) )
{
goto update_cleanup;
}
aXRef = new int[pTab.nCol];// sqlite3DbMallocRaw(db, sizeof(int) * pTab.nCol);
//if ( aXRef == null ) goto update_cleanup;
for ( i = 0; i < pTab.nCol; i++ )
aXRef[i] = -1;
/* Allocate a cursors for the main database table and for all indices.
** The index cursors might not be used, but if they are used they
** need to occur right after the database cursor. So go ahead and
** allocate enough space, just in case.
*/
pTabList.a[0].iCursor = iCur = pParse.nTab++;
for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
{
pParse.nTab++;
}
/* Initialize the name-context */
sNC = new NameContext();// memset(&sNC, 0, sNC).Length;
sNC.pParse = pParse;
sNC.pSrcList = pTabList;
/* Resolve the column names in all the expressions of the
** of the UPDATE statement. Also find the column index
** for each column to be updated in the pChanges array. For each
** column to be updated, make sure we have authorization to change
** that column.
*/
chngRowid = false;
for ( i = 0; i < pChanges.nExpr; i++ )
{
if ( sqlite3ResolveExprNames( sNC, ref pChanges.a[i].pExpr ) != 0 )
{
goto update_cleanup;
}
for ( j = 0; j < pTab.nCol; j++ )
{
if ( pTab.aCol[j].zName.Equals( pChanges.a[i].zName, StringComparison.InvariantCultureIgnoreCase ) )
{
if ( j == pTab.iPKey )
{
chngRowid = true;
pRowidExpr = pChanges.a[i].pExpr;
}
aXRef[j] = i;
break;
}
}
if ( j >= pTab.nCol )
{
if ( sqlite3IsRowid( pChanges.a[i].zName ) )
{
chngRowid = true;
pRowidExpr = pChanges.a[i].pExpr;
}
else
{
sqlite3ErrorMsg( pParse, "no such column: %s", pChanges.a[i].zName );
pParse.checkSchema = 1;
goto update_cleanup;
}
}
#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION
{
int rc;
rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab.zName,
pTab.aCol[j].zName, db.aDb[iDb].zName);
if( rc==SQLITE_DENY ){
goto update_cleanup;
}else if( rc==SQLITE_IGNORE ){
aXRef[j] = -1;
}
}
#endif
}
hasFK = sqlite3FkRequired( pParse, pTab, aXRef, chngRowid ? 1 : 0 ) != 0;
/* Allocate memory for the array aRegIdx[]. There is one entry in the
** array for each index associated with table being updated. Fill in
** the value with a register number for indices that are to be used
** and with zero for unused indices.
*/
for ( nIdx = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, nIdx++ )
{
}
if ( nIdx > 0 )
{
aRegIdx = new int[nIdx]; // sqlite3DbMallocRaw(db, Index*.Length * nIdx);
if ( aRegIdx == null )
goto update_cleanup;
}
for ( j = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, j++ )
{
int reg;
if ( hasFK || chngRowid )
{
reg = ++pParse.nMem;
}
else
{
reg = 0;
for ( i = 0; i < pIdx.nColumn; i++ )
{
if ( aXRef[pIdx.aiColumn[i]] >= 0 )
{
reg = ++pParse.nMem;
break;
}
}
}
aRegIdx[j] = reg;
}
/* Begin generating code. */
v = sqlite3GetVdbe( pParse );
if ( v == null )
goto update_cleanup;
if ( pParse.nested == 0 )
sqlite3VdbeCountChanges( v );
sqlite3BeginWriteOperation( pParse, 1, iDb );
#if !SQLITE_OMIT_VIRTUALTABLE
/* Virtual tables must be handled separately */
if ( IsVirtual( pTab ) )
{
updateVirtualTable( pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
pWhere, onError );
pWhere = null;
pTabList = null;
goto update_cleanup;
}
#endif
/* Allocate required registers. */
regOldRowid = regNewRowid = ++pParse.nMem;
if ( pTrigger != null || hasFK )
{
regOld = pParse.nMem + 1;
pParse.nMem += pTab.nCol;
}
if ( chngRowid || pTrigger != null || hasFK )
{
regNewRowid = ++pParse.nMem;
}
regNew = pParse.nMem + 1;
pParse.nMem += pTab.nCol;
/* Start the view context. */
if ( isView )
{
sqlite3AuthContextPush( pParse, sContext, pTab.zName );
}
/* If we are trying to update a view, realize that view into
** a ephemeral table.
*/
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
if ( isView )
{
sqlite3MaterializeView( pParse, pTab, pWhere, iCur );
}
#endif
/* Resolve the column names in all the expressions in the
** WHERE clause.
*/
if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 )
{
goto update_cleanup;
}
/* Begin the database scan
*/
sqlite3VdbeAddOp2( v, OP_Null, 0, regOldRowid );
ExprList NullOrderby = null;
pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref NullOrderby, WHERE_ONEPASS_DESIRED );
if ( pWInfo == null )
goto update_cleanup;
okOnePass = pWInfo.okOnePass != 0;
/* Remember the rowid of every item to be updated.
*/
sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regOldRowid );
if ( !okOnePass )
{
regRowSet = ++pParse.nMem;
sqlite3VdbeAddOp2( v, OP_RowSetAdd, regRowSet, regOldRowid );
}
/* End the database scan loop.
*/
sqlite3WhereEnd( pWInfo );
/* Initialize the count of updated rows
*/
if ( ( db.flags & SQLITE_CountRows ) != 0 && null == pParse.pTriggerTab )
{
regRowCount = ++pParse.nMem;
sqlite3VdbeAddOp2( v, OP_Integer, 0, regRowCount );
}
if ( !isView )
{
/*
** Open every index that needs updating. Note that if any
** index could potentially invoke a REPLACE conflict resolution
** action, then we need to open all indices because we might need
** to be deleting some records.
*/
if ( !okOnePass )
sqlite3OpenTable( pParse, iCur, iDb, pTab, OP_OpenWrite );
if ( onError == OE_Replace )
{
openAll = true;
}
else
{
openAll = false;
for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
{
if ( pIdx.onError == OE_Replace )
{
openAll = true;
break;
}
}
}
for ( i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++ )
{
if ( openAll || aRegIdx[i] > 0 )
{
KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx );
sqlite3VdbeAddOp4( v, OP_OpenWrite, iCur + i + 1, pIdx.tnum, iDb,
pKey, P4_KEYINFO_HANDOFF );
Debug.Assert( pParse.nTab > iCur + i + 1 );
}
}
}
/* Top of the update loop */
if ( okOnePass )
{
int a1 = sqlite3VdbeAddOp1( v, OP_NotNull, regOldRowid );
addr = sqlite3VdbeAddOp0( v, OP_Goto );
sqlite3VdbeJumpHere( v, a1 );
}
else
{
addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, regRowSet, 0, regOldRowid );
}
/* Make cursor iCur point to the record that is being updated. If
** this record does not exist for some reason (deleted by a trigger,
** for example, then jump to the next iteration of the RowSet loop. */
sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, regOldRowid );
/* If the record number will change, set register regNewRowid to
** contain the new value. If the record number is not being modified,
** then regNewRowid is the same register as regOldRowid, which is
** already populated. */
Debug.Assert( chngRowid || pTrigger != null || hasFK || regOldRowid == regNewRowid );
if ( chngRowid )
{
sqlite3ExprCode( pParse, pRowidExpr, regNewRowid );
sqlite3VdbeAddOp1( v, OP_MustBeInt, regNewRowid );
}
/* If there are triggers on this table, populate an array of registers
** with the required old.* column data. */
if ( hasFK || pTrigger != null )
{
u32 oldmask = ( hasFK ? sqlite3FkOldmask( pParse, pTab ) : 0 );
oldmask |= sqlite3TriggerColmask( pParse,
pTrigger, pChanges, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onError
);
for ( i = 0; i < pTab.nCol; i++ )
{
if ( aXRef[i] < 0 || oldmask == 0xffffffff || ( i < 32 && 0 != ( oldmask & ( 1 << i ) ) ) )
{
sqlite3ExprCodeGetColumnOfTable( v, pTab, iCur, i, regOld + i );
}
else
{
sqlite3VdbeAddOp2( v, OP_Null, 0, regOld + i );
}
}
if ( chngRowid == false )
{
sqlite3VdbeAddOp2( v, OP_Copy, regOldRowid, regNewRowid );
}
}
/* Populate the array of registers beginning at regNew with the new
** row data. This array is used to check constaints, create the new
** table and index records, and as the values for any new.* references
** made by triggers.
**
** If there are one or more BEFORE triggers, then do not populate the
** registers associated with columns that are (a) not modified by
** this UPDATE statement and (b) not accessed by new.* references. The
** values for registers not modified by the UPDATE must be reloaded from
** the database after the BEFORE triggers are fired anyway (as the trigger
** may have modified them). So not loading those that are not going to
** be used eliminates some redundant opcodes.
*/
newmask = (int)sqlite3TriggerColmask(
pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
);
for ( i = 0; i < pTab.nCol; i++ )
{
if ( i == pTab.iPKey )
{
sqlite3VdbeAddOp2( v, OP_Null, 0, regNew + i );
}
else
{
j = aXRef[i];
if ( j >= 0 )
{
sqlite3ExprCode( pParse, pChanges.a[j].pExpr, regNew + i );
}
else if ( 0 == ( tmask & TRIGGER_BEFORE ) || i > 31 || ( newmask & ( 1 << i ) ) != 0 )
{
/* This branch loads the value of a column that will not be changed
** into a register. This is done if there are no BEFORE triggers, or
** if there are one or more BEFORE triggers that use this value via
** a new.* reference in a trigger program.
*/
testcase( i == 31 );
testcase( i == 32 );
sqlite3VdbeAddOp3( v, OP_Column, iCur, i, regNew + i );
sqlite3ColumnDefault( v, pTab, i, regNew + i );
}
}
}
/* Fire any BEFORE UPDATE triggers. This happens before constraints are
** verified. One could argue that this is wrong.
*/
if ( ( tmask & TRIGGER_BEFORE ) != 0 )
{
sqlite3VdbeAddOp2( v, OP_Affinity, regNew, pTab.nCol );
sqlite3TableAffinityStr( v, pTab );
sqlite3CodeRowTrigger( pParse, pTrigger, TK_UPDATE, pChanges,
TRIGGER_BEFORE, pTab, regOldRowid, onError, addr );
/* The row-trigger may have deleted the row being updated. In this
** case, jump to the next row. No updates or AFTER triggers are
** required. This behaviour - what happens when the row being updated
** is deleted or renamed by a BEFORE trigger - is left undefined in the
** documentation.
*/
sqlite3VdbeAddOp3( v, OP_NotExists, iCur, addr, regOldRowid );
/* If it did not delete it, the row-trigger may still have modified
** some of the columns of the row being updated. Load the values for
** all columns not modified by the update statement into their
** registers in case this has happened.
*/
for ( i = 0; i < pTab.nCol; i++ )
{
if ( aXRef[i] < 0 && i != pTab.iPKey )
{
sqlite3VdbeAddOp3( v, OP_Column, iCur, i, regNew + i );
sqlite3ColumnDefault( v, pTab, i, regNew + i );
}
}
}
if ( !isView )
{
int j1; /* Address of jump instruction */
/* Do constraint checks. */
int iDummy;
sqlite3GenerateConstraintChecks( pParse, pTab, iCur, regNewRowid,
aRegIdx, ( chngRowid ? regOldRowid : 0 ), true, onError, addr, out iDummy );
/* Do FK constraint checks. */
if ( hasFK )
{
sqlite3FkCheck( pParse, pTab, regOldRowid, 0 );
}
/* Delete the index entries associated with the current record. */
j1 = sqlite3VdbeAddOp3( v, OP_NotExists, iCur, 0, regOldRowid );
sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx );
/* If changing the record number, delete the old record. */
if ( hasFK || chngRowid )
{
sqlite3VdbeAddOp2( v, OP_Delete, iCur, 0 );
}
sqlite3VdbeJumpHere( v, j1 );
if ( hasFK )
{
sqlite3FkCheck( pParse, pTab, 0, regNewRowid );
}
/* Insert the new index entries and the new record. */
sqlite3CompleteInsertion( pParse, pTab, iCur, regNewRowid, aRegIdx, true, false, false );
/* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
** handle rows (possibly in other tables) that refer via a foreign key
** to the row just updated. */
if ( hasFK )
{
sqlite3FkActions( pParse, pTab, pChanges, regOldRowid );
}
}
/* Increment the row counter
*/
if ( ( db.flags & SQLITE_CountRows ) != 0 && null == pParse.pTriggerTab )
{
sqlite3VdbeAddOp2( v, OP_AddImm, regRowCount, 1 );
}
sqlite3CodeRowTrigger( pParse, pTrigger, TK_UPDATE, pChanges,
TRIGGER_AFTER, pTab, regOldRowid, onError, addr );
/* Repeat the above with the next record to be updated, until
** all record selected by the WHERE clause have been updated.
*/
sqlite3VdbeAddOp2( v, OP_Goto, 0, addr );
sqlite3VdbeJumpHere( v, addr );
/* Close all tables */
for ( i = 0, pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext, i++ )
{
if ( openAll || aRegIdx[i] > 0 )
{
sqlite3VdbeAddOp2( v, OP_Close, iCur + i + 1, 0 );
}
}
sqlite3VdbeAddOp2( v, OP_Close, iCur, 0 );
/* Update the sqlite_sequence table by storing the content of the
** maximum rowid counter values recorded while inserting into
** autoincrement tables.
*/
if ( pParse.nested == 0 && pParse.pTriggerTab == null )
{
sqlite3AutoincrementEnd( pParse );
}
/*
** Return the number of rows that were changed. If this routine is
** generating code because of a call to sqlite3NestedParse(), do not
** invoke the callback function.
*/
if ( ( db.flags & SQLITE_CountRows ) != 0 && null == pParse.pTriggerTab && 0 == pParse.nested )
{
sqlite3VdbeAddOp2( v, OP_ResultRow, regRowCount, 1 );
sqlite3VdbeSetNumCols( v, 1 );
sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC );
}
update_cleanup:
#if NO_SQLITE_OMIT_AUTHORIZATION //#if !SQLITE_OMIT_AUTHORIZATION
sqlite3AuthContextPop(sContext);
#endif
sqlite3DbFree( db, ref aRegIdx );
sqlite3DbFree( db, ref aXRef );
sqlite3SrcListDelete( db, ref pTabList );
sqlite3ExprListDelete( db, ref pChanges );
sqlite3ExprDelete( db, ref pWhere );
return;
}
/* Make sure "isView" and other macros defined above are undefined. Otherwise
** thely may interfere with compilation of other functions in this file
** (or in another file, if this file becomes part of the amalgamation). */
//#if isView
// #undef isView
//#endif
//#if pTrigger
// #undef pTrigger
//#endif
#if !SQLITE_OMIT_VIRTUALTABLE
/*
** Generate code for an UPDATE of a virtual table.
**
** The strategy is that we create an ephemerial table that contains
** for each row to be changed:
**
** (A) The original rowid of that row.
** (B) The revised rowid for the row. (note1)
** (C) The content of every column in the row.
**
** Then we loop over this ephemeral table and for each row in
** the ephermeral table call VUpdate.
**
** When finished, drop the ephemeral table.
**
** (note1) Actually, if we know in advance that (A) is always the same
** as (B) we only store (A), then duplicate (A) when pulling
** it out of the ephemeral table before calling VUpdate.
*/
static void updateVirtualTable(
Parse pParse, /* The parsing context */
SrcList pSrc, /* The virtual table to be modified */
Table pTab, /* The virtual table */
ExprList pChanges, /* The columns to change in the UPDATE statement */
Expr pRowid, /* Expression used to recompute the rowid */
int[] aXRef, /* Mapping from columns of pTab to entries in pChanges */
Expr pWhere, /* WHERE clause of the UPDATE statement */
int onError /* ON CONFLICT strategy */
)
{
Vdbe v = pParse.pVdbe; /* Virtual machine under construction */
ExprList pEList = null; /* The result set of the SELECT statement */
Select pSelect = null; /* The SELECT statement */
Expr pExpr; /* Temporary expression */
int ephemTab; /* Table holding the result of the SELECT */
int i; /* Loop counter */
int addr; /* Address of top of loop */
int iReg; /* First register in set passed to OP_VUpdate */
sqlite3 db = pParse.db; /* Database connection */
VTable pVTab = sqlite3GetVTable( db, pTab );
SelectDest dest = new SelectDest();
/* Construct the SELECT statement that will find the new values for
** all updated rows.
*/
pEList = sqlite3ExprListAppend( pParse, 0, sqlite3Expr( db, TK_ID, "_rowid_" ) );
if ( pRowid != null)
{
pEList = sqlite3ExprListAppend( pParse, pEList,
sqlite3ExprDup( db, pRowid, 0 ) );
}
Debug.Assert( pTab.iPKey < 0 );
for ( i = 0; i < pTab.nCol; i++ )
{
if ( aXRef[i] >= 0 )
{
pExpr = sqlite3ExprDup( db, pChanges.a[aXRef[i]].pExpr, 0 );
}
else
{
pExpr = sqlite3Expr( db, TK_ID, pTab.aCol[i].zName );
}
pEList = sqlite3ExprListAppend( pParse, pEList, pExpr );
}
pSelect = sqlite3SelectNew( pParse, pEList, pSrc, pWhere, null, null, null, 0, null, null );
/* Create the ephemeral table into which the update results will
** be stored.
*/
Debug.Assert( v != null);
ephemTab = pParse.nTab++;
sqlite3VdbeAddOp2( v, OP_OpenEphemeral, ephemTab, pTab.nCol + 1 + ( ( pRowid != null ) ? 1 : 0 ) );
sqlite3VdbeChangeP5( v, BTREE_UNORDERED );
/* fill the ephemeral table
*/
sqlite3SelectDestInit( dest, SRT_Table, ephemTab );
sqlite3Select( pParse, pSelect, ref dest );
/* Generate code to scan the ephemeral table and call VUpdate. */
iReg = ++pParse.nMem;
pParse.nMem += pTab.nCol + 1;
addr = sqlite3VdbeAddOp2( v, OP_Rewind, ephemTab, 0 );
sqlite3VdbeAddOp3( v, OP_Column, ephemTab, 0, iReg );
sqlite3VdbeAddOp3( v, OP_Column, ephemTab, ( pRowid != null ? 1 : 0 ), iReg + 1 );
for ( i = 0; i < pTab.nCol; i++ )
{
sqlite3VdbeAddOp3( v, OP_Column, ephemTab, i + 1 + ( ( pRowid != null ) ? 1 : 0 ), iReg + 2 + i );
}
sqlite3VtabMakeWritable( pParse, pTab );
sqlite3VdbeAddOp4( v, OP_VUpdate, 0, pTab.nCol + 2, iReg, pVTab, P4_VTAB );
sqlite3VdbeChangeP5( v, (byte)( onError == OE_Default ? OE_Abort : onError ) );
sqlite3MayAbort( pParse );
sqlite3VdbeAddOp2( v, OP_Next, ephemTab, addr + 1 );
sqlite3VdbeJumpHere( v, addr );
sqlite3VdbeAddOp2( v, OP_Close, ephemTab, 0 );
/* Cleanup */
sqlite3SelectDelete( db, ref pSelect );
}
#endif // * SQLITE_OMIT_VIRTUALTABLE */
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gaxgrpc = Google.Api.Gax.Grpc;
using lro = Google.LongRunning;
using wkt = Google.Protobuf.WellKnownTypes;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using xunit = Xunit;
namespace Google.Cloud.Gaming.V1Beta.Tests
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedGameServerClustersServiceClientTest
{
[xunit::FactAttribute]
public void GetGameServerClusterRequestObject()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
GameServerCluster expectedResponse = new GameServerCluster
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ConnectionInfo = new GameServerClusterConnectionInfo(),
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerCluster(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
GameServerCluster response = client.GetGameServerCluster(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerClusterRequestObjectAsync()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
GameServerCluster expectedResponse = new GameServerCluster
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ConnectionInfo = new GameServerClusterConnectionInfo(),
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerClusterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerCluster>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
GameServerCluster responseCallSettings = await client.GetGameServerClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerCluster responseCancellationToken = await client.GetGameServerClusterAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerCluster()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
GameServerCluster expectedResponse = new GameServerCluster
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ConnectionInfo = new GameServerClusterConnectionInfo(),
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerCluster(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
GameServerCluster response = client.GetGameServerCluster(request.Name);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerClusterAsync()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
GameServerCluster expectedResponse = new GameServerCluster
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ConnectionInfo = new GameServerClusterConnectionInfo(),
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerClusterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerCluster>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
GameServerCluster responseCallSettings = await client.GetGameServerClusterAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerCluster responseCancellationToken = await client.GetGameServerClusterAsync(request.Name, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void GetGameServerClusterResourceNames()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
GameServerCluster expectedResponse = new GameServerCluster
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ConnectionInfo = new GameServerClusterConnectionInfo(),
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerCluster(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
GameServerCluster response = client.GetGameServerCluster(request.GameServerClusterName);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task GetGameServerClusterResourceNamesAsync()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
GetGameServerClusterRequest request = new GetGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
};
GameServerCluster expectedResponse = new GameServerCluster
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
CreateTime = new wkt::Timestamp(),
UpdateTime = new wkt::Timestamp(),
Labels =
{
{
"key8a0b6e3c",
"value60c16320"
},
},
ConnectionInfo = new GameServerClusterConnectionInfo(),
Etag = "etage8ad7218",
Description = "description2cf9da67",
};
mockGrpcClient.Setup(x => x.GetGameServerClusterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<GameServerCluster>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
GameServerCluster responseCallSettings = await client.GetGameServerClusterAsync(request.GameServerClusterName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
GameServerCluster responseCancellationToken = await client.GetGameServerClusterAsync(request.GameServerClusterName, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PreviewCreateGameServerClusterRequestObject()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewCreateGameServerClusterRequest request = new PreviewCreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "game_server_cluster_ida2310829",
GameServerCluster = new GameServerCluster(),
PreviewTime = new wkt::Timestamp(),
};
PreviewCreateGameServerClusterResponse expectedResponse = new PreviewCreateGameServerClusterResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewCreateGameServerCluster(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
PreviewCreateGameServerClusterResponse response = client.PreviewCreateGameServerCluster(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PreviewCreateGameServerClusterRequestObjectAsync()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewCreateGameServerClusterRequest request = new PreviewCreateGameServerClusterRequest
{
ParentAsRealmName = RealmName.FromProjectLocationRealm("[PROJECT]", "[LOCATION]", "[REALM]"),
GameServerClusterId = "game_server_cluster_ida2310829",
GameServerCluster = new GameServerCluster(),
PreviewTime = new wkt::Timestamp(),
};
PreviewCreateGameServerClusterResponse expectedResponse = new PreviewCreateGameServerClusterResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewCreateGameServerClusterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PreviewCreateGameServerClusterResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
PreviewCreateGameServerClusterResponse responseCallSettings = await client.PreviewCreateGameServerClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PreviewCreateGameServerClusterResponse responseCancellationToken = await client.PreviewCreateGameServerClusterAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PreviewDeleteGameServerClusterRequestObject()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewDeleteGameServerClusterRequest request = new PreviewDeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
PreviewTime = new wkt::Timestamp(),
};
PreviewDeleteGameServerClusterResponse expectedResponse = new PreviewDeleteGameServerClusterResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewDeleteGameServerCluster(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
PreviewDeleteGameServerClusterResponse response = client.PreviewDeleteGameServerCluster(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PreviewDeleteGameServerClusterRequestObjectAsync()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewDeleteGameServerClusterRequest request = new PreviewDeleteGameServerClusterRequest
{
GameServerClusterName = GameServerClusterName.FromProjectLocationRealmCluster("[PROJECT]", "[LOCATION]", "[REALM]", "[CLUSTER]"),
PreviewTime = new wkt::Timestamp(),
};
PreviewDeleteGameServerClusterResponse expectedResponse = new PreviewDeleteGameServerClusterResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewDeleteGameServerClusterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PreviewDeleteGameServerClusterResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
PreviewDeleteGameServerClusterResponse responseCallSettings = await client.PreviewDeleteGameServerClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PreviewDeleteGameServerClusterResponse responseCancellationToken = await client.PreviewDeleteGameServerClusterAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public void PreviewUpdateGameServerClusterRequestObject()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewUpdateGameServerClusterRequest request = new PreviewUpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new wkt::FieldMask(),
PreviewTime = new wkt::Timestamp(),
};
PreviewUpdateGameServerClusterResponse expectedResponse = new PreviewUpdateGameServerClusterResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewUpdateGameServerCluster(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
PreviewUpdateGameServerClusterResponse response = client.PreviewUpdateGameServerCluster(request);
xunit::Assert.Same(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[xunit::FactAttribute]
public async stt::Task PreviewUpdateGameServerClusterRequestObjectAsync()
{
moq::Mock<GameServerClustersService.GameServerClustersServiceClient> mockGrpcClient = new moq::Mock<GameServerClustersService.GameServerClustersServiceClient>(moq::MockBehavior.Strict);
mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object);
PreviewUpdateGameServerClusterRequest request = new PreviewUpdateGameServerClusterRequest
{
GameServerCluster = new GameServerCluster(),
UpdateMask = new wkt::FieldMask(),
PreviewTime = new wkt::Timestamp(),
};
PreviewUpdateGameServerClusterResponse expectedResponse = new PreviewUpdateGameServerClusterResponse
{
Etag = "etage8ad7218",
TargetState = new TargetState(),
};
mockGrpcClient.Setup(x => x.PreviewUpdateGameServerClusterAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PreviewUpdateGameServerClusterResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
GameServerClustersServiceClient client = new GameServerClustersServiceClientImpl(mockGrpcClient.Object, null);
PreviewUpdateGameServerClusterResponse responseCallSettings = await client.PreviewUpdateGameServerClusterAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
xunit::Assert.Same(expectedResponse, responseCallSettings);
PreviewUpdateGameServerClusterResponse responseCancellationToken = await client.PreviewUpdateGameServerClusterAsync(request, st::CancellationToken.None);
xunit::Assert.Same(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
}
}
| |
// 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;
namespace System.IO
{
public sealed partial class DirectoryInfo : FileSystemInfo
{
private string _name;
public DirectoryInfo(string path)
{
Init(originalPath: PathHelpers.ShouldReviseDirectoryPathToCurrent(path) ? "." : path,
fullPath: Path.GetFullPath(path),
isNormalized: true);
}
internal DirectoryInfo(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
{
Init(originalPath, fullPath, fileName, isNormalized);
}
private void Init(string originalPath, string fullPath = null, string fileName = null, bool isNormalized = false)
{
// Want to throw the original argument name
OriginalPath = originalPath ?? throw new ArgumentNullException("path");
fullPath = fullPath ?? originalPath;
Debug.Assert(!isNormalized || !PathInternal.IsPartiallyQualified(fullPath), "should be fully qualified if normalized");
fullPath = isNormalized ? fullPath : Path.GetFullPath(fullPath);
_name = fileName ?? (PathHelpers.IsRoot(fullPath) ?
fullPath :
Path.GetFileName(PathHelpers.TrimEndingDirectorySeparator(fullPath)));
FullPath = fullPath;
DisplayPath = PathHelpers.ShouldReviseDirectoryPathToCurrent(originalPath) ? "." : originalPath;
}
public override string Name => _name;
public DirectoryInfo Parent
{
get
{
string s = FullPath;
// FullPath might end in either "parent\child" or "parent\child", and in either case we want
// the parent of child, not the child. Trim off an ending directory separator if there is one,
// but don't mangle the root.
if (!PathHelpers.IsRoot(s))
{
s = PathHelpers.TrimEndingDirectorySeparator(s);
}
string parentName = Path.GetDirectoryName(s);
return parentName != null ?
new DirectoryInfo(parentName, null) :
null;
}
}
public DirectoryInfo CreateSubdirectory(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
return CreateSubdirectoryHelper(path);
}
private DirectoryInfo CreateSubdirectoryHelper(string path)
{
Debug.Assert(path != null);
PathHelpers.ThrowIfEmptyOrRootedPath(path);
string newDirs = Path.Combine(FullPath, path);
string fullPath = Path.GetFullPath(newDirs);
if (0 != string.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.StringComparison))
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath), nameof(path));
}
FileSystem.CreateDirectory(fullPath);
// Check for read permission to directory we hand back by calling this constructor.
return new DirectoryInfo(fullPath);
}
public void Create()
{
FileSystem.CreateDirectory(FullPath);
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
public override bool Exists
{
get
{
try
{
return ExistsCore;
}
catch
{
return false;
}
}
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
public FileInfo[] GetFiles(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
public FileInfo[] GetFiles(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
return InternalGetFiles(searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (i.e. "*.txt").
private FileInfo[] InternalGetFiles(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> enumerable = (IEnumerable<FileInfo>)FileSystem.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of Files in the DirectoryInfo specified by path
public FileInfo[] GetFiles()
{
return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current directory.
public DirectoryInfo[] GetDirectories()
{
return InternalGetDirectories("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
public FileSystemInfo[] GetFileSystemInfos(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
return InternalGetFileSystemInfos(searchPattern, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (i.e. "*.txt").
private FileSystemInfo[] InternalGetFileSystemInfos(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileSystemInfo> enumerable = FileSystem.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
return EnumerableHelpers.ToArray(enumerable);
}
// Returns an array of strongly typed FileSystemInfo entries which will contain a listing
// of all the files and directories.
public FileSystemInfo[] GetFileSystemInfos()
{
return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
public DirectoryInfo[] GetDirectories(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
return InternalGetDirectories(searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (i.e. "System*" could match the System & System32
// directories).
private DirectoryInfo[] InternalGetDirectories(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
return EnumerableHelpers.ToArray(enumerable);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories()
{
return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<DirectoryInfo> EnumerateDirectories(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
return InternalEnumerateDirectories(searchPattern, searchOption);
}
private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<DirectoryInfo>)FileSystem.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories);
}
public IEnumerable<FileInfo> EnumerateFiles()
{
return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileInfo> EnumerateFiles(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
return InternalEnumerateFiles(searchPattern, searchOption);
}
private IEnumerable<FileInfo> InternalEnumerateFiles(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return (IEnumerable<FileInfo>)FileSystem.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()
{
return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly);
}
public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(string searchPattern, SearchOption searchOption)
{
if (searchPattern == null)
throw new ArgumentNullException(nameof(searchPattern));
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException(nameof(searchOption), SR.ArgumentOutOfRange_Enum);
return InternalEnumerateFileSystemInfos(searchPattern, searchOption);
}
private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(string searchPattern, SearchOption searchOption)
{
Debug.Assert(searchPattern != null);
Debug.Assert(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return FileSystem.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
//
public DirectoryInfo Root
{
get
{
string rootPath = Path.GetPathRoot(FullPath);
return new DirectoryInfo(rootPath);
}
}
public void MoveTo(string destDirName)
{
if (destDirName == null)
throw new ArgumentNullException(nameof(destDirName));
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, nameof(destDirName));
string destination = Path.GetFullPath(destDirName);
string destinationWithSeparator = destination;
if (destinationWithSeparator[destinationWithSeparator.Length - 1] != Path.DirectorySeparatorChar)
destinationWithSeparator = destinationWithSeparator + PathHelpers.DirectorySeparatorCharAsString;
string fullSourcePath;
if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar)
fullSourcePath = FullPath;
else
fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString;
StringComparison pathComparison = PathInternal.StringComparison;
if (string.Equals(fullSourcePath, destinationWithSeparator, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
string sourceRoot = Path.GetPathRoot(fullSourcePath);
string destinationRoot = Path.GetPathRoot(destinationWithSeparator);
if (!string.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
// Windows will throw if the source file/directory doesn't exist, we preemptively check
// to make sure our cross platform behavior matches NetFX behavior.
if (!Exists && !FileSystem.FileExists(FullPath))
throw new DirectoryNotFoundException(SR.Format(SR.IO_PathNotFound_Path, FullPath));
if (FileSystem.DirectoryExists(destinationWithSeparator))
throw new IOException(SR.Format(SR.IO_AlreadyExists_Name, destinationWithSeparator));
FileSystem.MoveDirectory(FullPath, destination);
Init(originalPath: destDirName,
fullPath: destinationWithSeparator,
fileName: _name,
isNormalized: true);
// Flush any cached information about the directory.
Invalidate();
}
public override void Delete()
{
FileSystem.RemoveDirectory(FullPath, false);
}
public void Delete(bool recursive)
{
FileSystem.RemoveDirectory(FullPath, recursive);
}
/// <summary>
/// Returns the original path. Use FullPath or Name properties for the path / directory name.
/// </summary>
public override string ToString()
{
return DisplayPath;
}
}
}
| |
/***************************************************************************
* HttpFileDownloadGroup.cs
*
* Copyright (C) 2007 Michael C. Urbanski
* Written by Mike Urbanski <michael.c.urbanski@gmail.com>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* 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.Timers; // migrate to System.Threading.Timer
using System.Threading;
using System.ComponentModel;
using System.Collections.Generic;
using Migo.Net;
using Migo.TaskCore;
using Migo.TaskCore.Collections;
// Write Dispose method
namespace Migo.DownloadCore
{
public class HttpFileDownloadGroup : TaskGroup<HttpFileDownloadTask>
{
DownloadGroupStatusManager dsm;
private DateTime lastTick;
private bool disposed;
private long transferRate;
private long transferRatePreviously;
private long bytesThisInterval = 0;
private System.Timers.Timer transferTimer;
private Dictionary<HttpFileDownloadTask,long> transferRateDict;
public HttpFileDownloadGroup (int maxDownloads, TaskCollection<HttpFileDownloadTask> tasks)
: base (maxDownloads, tasks, new DownloadGroupStatusManager ())
{
dsm = StatusManager as DownloadGroupStatusManager;
transferRateDict =
new Dictionary<HttpFileDownloadTask,long> (dsm.MaxRunningTasks);
InitTransferTimer ();
}
public override void Dispose ()
{
Dispose (null);
}
public override void Dispose (AutoResetEvent handle)
{
if (SetDisposed ()) {
if (transferTimer != null) {
transferTimer.Enabled = false;
transferTimer.Elapsed -= OnTransmissionTimerElapsedHandler;
transferTimer.Dispose ();
transferTimer = null;
}
base.Dispose (handle);
}
}
private bool SetDisposed ()
{
bool ret = false;
lock (SyncRoot) {
if (!disposed) {
ret = disposed = true;
}
}
return ret;
}
protected override void OnStarted ()
{
lock (SyncRoot) {
transferTimer.Enabled = true;
base.OnStarted ();
}
}
protected override void OnStopped ()
{
lock (SyncRoot) {
transferTimer.Enabled = false;
base.OnStopped ();
}
}
protected override void OnTaskStarted (HttpFileDownloadTask task)
{
lock (SyncRoot) {
transferRateDict.Add (task, task.BytesReceived);
base.OnTaskStarted (task);
}
}
protected override void OnTaskStopped (HttpFileDownloadTask task)
{
lock (SyncRoot) {
if (transferRateDict.ContainsKey (task)) {
long bytesLastCheck = transferRateDict[task];
if (task.BytesReceived > bytesLastCheck) {
bytesThisInterval += (task.BytesReceived - bytesLastCheck);
}
transferRateDict.Remove (task);
}
base.OnTaskStopped (task);
}
}
protected virtual void SetTransferRate (long bytesPerSecond)
{
lock (SyncRoot) {
dsm.SetTransferRate (bytesPerSecond);
}
}
private void InitTransferTimer ()
{
transferTimer = new System.Timers.Timer ();
transferTimer.Elapsed += OnTransmissionTimerElapsedHandler;
transferTimer.Interval = (1500 * 1); // 1.5 seconds
transferTimer.Enabled = false;
}
private long CalculateTransferRate ()
{
long bytesPerSecond;
TimeSpan duration = (DateTime.Now - lastTick);
double secondsElapsed = duration.TotalSeconds;
if ((int)secondsElapsed == 0) {
return 0;
}
long tmpCur;
long tmpPrev;
foreach (HttpFileDownloadTask dt in CurrentTasks) {
tmpCur = dt.BytesReceived;
tmpPrev = transferRateDict[dt];
transferRateDict[dt] = tmpCur;
bytesThisInterval += (tmpCur - tmpPrev);
}
bytesPerSecond = (long) (
(bytesThisInterval / secondsElapsed)
);
lastTick = DateTime.Now;
bytesThisInterval = 0;
return bytesPerSecond;
}
protected override void Reset ()
{
lastTick = DateTime.Now;
transferRate = -1;
transferRatePreviously = -1;
base.Reset ();
}
protected virtual void OnTransmissionTimerElapsedHandler (object source,
ElapsedEventArgs e)
{
lock (SyncRoot) {
UpdateTransferRate ();
}
}
protected virtual void UpdateTransferRate ()
{
transferRate = CalculateTransferRate ();
if (transferRatePreviously == 0) {
transferRatePreviously = transferRate;
}
transferRate = ((transferRate + transferRatePreviously) / 2);
SetTransferRate (transferRate);
transferRatePreviously = transferRate;
}
}
}
| |
//
// CoverArtEditor.cs
//
// Author:
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Text;
using System.Collections.Generic;
using Mono.Unix;
using Mono.Addins;
using Gtk;
using Hyena;
using Hyena.Gui;
using Hyena.Widgets;
using Banshee.Base;
using Banshee.Kernel;
using Banshee.Sources;
using Banshee.ServiceStack;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration.Schema;
using Banshee.Widgets;
using Banshee.Gui.DragDrop;
namespace Banshee.Collection.Gui
{
public class CoverArtEditor
{
public static Widget For (Widget widget, Func<int, int, bool> is_sensitive, Func<TrackInfo> get_track, System.Action on_updated)
{
return new EditorBox (widget) {
IsSensitive = is_sensitive,
GetTrack = get_track,
OnUpdated = on_updated
};
}
private class EditorBox : EventBox
{
public Func<int, int, bool> IsSensitive;
public Func<TrackInfo> GetTrack;
public System.Action OnUpdated;
public EditorBox (Widget child)
{
Child = child;
VisibleWindow = false;
ButtonPressEvent += (o, a) => {
if (a.Event.Button == 3 && IsSensitive ((int)a.Event.X, (int)a.Event.Y)) {
var menu = new Menu ();
var choose = new MenuItem (Catalog.GetString ("Choose New Cover Art..."));
choose.Activated += delegate {
try {
var track = GetTrack ();
if (track != null) {
var dialog = new Banshee.Gui.Dialogs.ImageFileChooserDialog ();
var resp = dialog.Run ();
string filename = dialog.Filename;
dialog.Destroy ();
if (resp == (int)Gtk.ResponseType.Ok) {
SetCoverArt (track, filename);
}
}
} catch (Exception e) {
Log.Exception (e);
}
};
var delete = new MenuItem (Catalog.GetString ("Delete This Cover Art"));
delete.Activated += delegate {
try {
var track = GetTrack ();
if (track != null) {
DeleteCoverArt (track);
NotifyUpdated (track);
}
} catch (Exception e) {
Log.Exception (e);
}
};
var uri = GetCoverArtPath (GetTrack ());
choose.Sensitive = uri != null;
if (uri == null || !Banshee.IO.File.Exists (uri)) {
delete.Sensitive = false;
}
menu.Append (choose);
menu.Append (delete);
menu.ShowAll ();
menu.Popup ();
}
};
Gtk.Drag.SourceSet (this, Gdk.ModifierType.Button1Mask, new TargetEntry [] { DragDropTarget.UriList }, Gdk.DragAction.Copy | Gdk.DragAction.Move);
DragDataGet += (o, a) => {
try {
var uri = GetCoverArtPath (GetTrack ());
if (uri != null) {
if (Banshee.IO.File.Exists (uri)) {
a.SelectionData.Set (
Gdk.Atom.Intern (DragDropTarget.UriList.Target, false), 8,
Encoding.UTF8.GetBytes (uri.AbsoluteUri)
);
}
}
} catch (Exception e) {
Log.Exception (e);
}
};
Gtk.Drag.DestSet (this, Gtk.DestDefaults.All, new TargetEntry [] { DragDropTarget.UriList }, Gdk.DragAction.Copy);
DragDataReceived += (o, a) => {
try {
SetCoverArt (GetTrack (), Encoding.UTF8.GetString (a.SelectionData.Data));
} catch (Exception e) {
Log.Exception (e);
}
};
}
private void SetCoverArt (TrackInfo track, string path)
{
if (track == null)
return;
var from_uri = new SafeUri (new System.Uri (path));
var to_uri = new SafeUri (CoverArtSpec.GetPathForNewFile (track.ArtworkId, from_uri.AbsoluteUri));
if (to_uri != null) {
// Make sure it's not the same file we already have
if (from_uri.Equals (to_uri)) {
return;
}
// Make sure the incoming file exists
if (!Banshee.IO.File.Exists (from_uri)) {
Hyena.Log.WarningFormat ("New cover art file not found: {0}", path);
return;
}
DeleteCoverArt (track);
Banshee.IO.File.Copy (from_uri, to_uri, true);
NotifyUpdated (track);
Hyena.Log.DebugFormat ("Got new cover art file for {0}: {1}", track.DisplayAlbumTitle, path);
}
}
private void NotifyUpdated (TrackInfo track)
{
var cur = ServiceManager.PlayerEngine.CurrentTrack;
if (cur != null && cur.TrackEqual (track)) {
ServiceManager.PlayerEngine.TrackInfoUpdated ();
}
OnUpdated ();
}
private void DeleteCoverArt (TrackInfo track)
{
if (track != null) {
var uri = new SafeUri (CoverArtSpec.GetPath (track.ArtworkId));
if (Banshee.IO.File.Exists (uri)) {
Banshee.IO.File.Delete (uri);
}
var artwork_id = track.ArtworkId;
if (artwork_id != null) {
ServiceManager.Get<ArtworkManager> ().ClearCacheFor (track.ArtworkId);
}
// Deleting it from this table means the cover art downloader extension will
// attempt to redownload it on its next run.
var db = ServiceManager.DbConnection;
var db_track = track as DatabaseTrackInfo;
if (db_track != null && db.TableExists ("CoverArtDownloads")) {
db.Execute ("DELETE FROM CoverArtDownloads WHERE AlbumID = ?", db_track.AlbumId);
}
}
}
private SafeUri GetCoverArtPath (TrackInfo track)
{
if (track != null) {
return new SafeUri (CoverArtSpec.GetPath (track.ArtworkId));
}
return null;
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace XenAPI
{
/// <summary>
/// The metrics associated with a virtual network device
/// First published in XenServer 4.0.
/// </summary>
public partial class VIF_metrics : XenObject<VIF_metrics>
{
public VIF_metrics()
{
}
public VIF_metrics(string uuid,
double io_read_kbs,
double io_write_kbs,
DateTime last_updated,
Dictionary<string, string> other_config)
{
this.uuid = uuid;
this.io_read_kbs = io_read_kbs;
this.io_write_kbs = io_write_kbs;
this.last_updated = last_updated;
this.other_config = other_config;
}
/// <summary>
/// Creates a new VIF_metrics from a Proxy_VIF_metrics.
/// </summary>
/// <param name="proxy"></param>
public VIF_metrics(Proxy_VIF_metrics proxy)
{
this.UpdateFromProxy(proxy);
}
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given VIF_metrics.
/// </summary>
public override void UpdateFrom(VIF_metrics update)
{
uuid = update.uuid;
io_read_kbs = update.io_read_kbs;
io_write_kbs = update.io_write_kbs;
last_updated = update.last_updated;
other_config = update.other_config;
}
internal void UpdateFromProxy(Proxy_VIF_metrics proxy)
{
uuid = proxy.uuid == null ? null : (string)proxy.uuid;
io_read_kbs = Convert.ToDouble(proxy.io_read_kbs);
io_write_kbs = Convert.ToDouble(proxy.io_write_kbs);
last_updated = proxy.last_updated;
other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config);
}
public Proxy_VIF_metrics ToProxy()
{
Proxy_VIF_metrics result_ = new Proxy_VIF_metrics();
result_.uuid = uuid ?? "";
result_.io_read_kbs = io_read_kbs;
result_.io_write_kbs = io_write_kbs;
result_.last_updated = last_updated;
result_.other_config = Maps.convert_to_proxy_string_string(other_config);
return result_;
}
/// <summary>
/// Creates a new VIF_metrics from a Hashtable.
/// Note that the fields not contained in the Hashtable
/// will be created with their default values.
/// </summary>
/// <param name="table"></param>
public VIF_metrics(Hashtable table) : this()
{
UpdateFrom(table);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this VIF_metrics
/// with the values listed in the Hashtable. Note that only the fields contained
/// in the Hashtable will be updated and the rest will remain the same.
/// </summary>
/// <param name="table"></param>
public void UpdateFrom(Hashtable table)
{
if (table.ContainsKey("uuid"))
uuid = Marshalling.ParseString(table, "uuid");
if (table.ContainsKey("io_read_kbs"))
io_read_kbs = Marshalling.ParseDouble(table, "io_read_kbs");
if (table.ContainsKey("io_write_kbs"))
io_write_kbs = Marshalling.ParseDouble(table, "io_write_kbs");
if (table.ContainsKey("last_updated"))
last_updated = Marshalling.ParseDateTime(table, "last_updated");
if (table.ContainsKey("other_config"))
other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config"));
}
public bool DeepEquals(VIF_metrics other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._uuid, other._uuid) &&
Helper.AreEqual2(this._io_read_kbs, other._io_read_kbs) &&
Helper.AreEqual2(this._io_write_kbs, other._io_write_kbs) &&
Helper.AreEqual2(this._last_updated, other._last_updated) &&
Helper.AreEqual2(this._other_config, other._other_config);
}
internal static List<VIF_metrics> ProxyArrayToObjectList(Proxy_VIF_metrics[] input)
{
var result = new List<VIF_metrics>();
foreach (var item in input)
result.Add(new VIF_metrics(item));
return result;
}
public override string SaveChanges(Session session, string opaqueRef, VIF_metrics server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
if (!Helper.AreEqual2(_other_config, server._other_config))
{
VIF_metrics.set_other_config(session, opaqueRef, _other_config);
}
return null;
}
}
/// <summary>
/// Get a record containing the current state of the given VIF_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
public static VIF_metrics get_record(Session session, string _vif_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_record(session.opaque_ref, _vif_metrics);
else
return new VIF_metrics((Proxy_VIF_metrics)session.proxy.vif_metrics_get_record(session.opaque_ref, _vif_metrics ?? "").parse());
}
/// <summary>
/// Get a reference to the VIF_metrics instance with the specified UUID.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_uuid">UUID of object to return</param>
public static XenRef<VIF_metrics> get_by_uuid(Session session, string _uuid)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_by_uuid(session.opaque_ref, _uuid);
else
return XenRef<VIF_metrics>.Create(session.proxy.vif_metrics_get_by_uuid(session.opaque_ref, _uuid ?? "").parse());
}
/// <summary>
/// Get the uuid field of the given VIF_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
public static string get_uuid(Session session, string _vif_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_uuid(session.opaque_ref, _vif_metrics);
else
return (string)session.proxy.vif_metrics_get_uuid(session.opaque_ref, _vif_metrics ?? "").parse();
}
/// <summary>
/// Get the io/read_kbs field of the given VIF_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
public static double get_io_read_kbs(Session session, string _vif_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_io_read_kbs(session.opaque_ref, _vif_metrics);
else
return Convert.ToDouble(session.proxy.vif_metrics_get_io_read_kbs(session.opaque_ref, _vif_metrics ?? "").parse());
}
/// <summary>
/// Get the io/write_kbs field of the given VIF_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
public static double get_io_write_kbs(Session session, string _vif_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_io_write_kbs(session.opaque_ref, _vif_metrics);
else
return Convert.ToDouble(session.proxy.vif_metrics_get_io_write_kbs(session.opaque_ref, _vif_metrics ?? "").parse());
}
/// <summary>
/// Get the last_updated field of the given VIF_metrics.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
public static DateTime get_last_updated(Session session, string _vif_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_last_updated(session.opaque_ref, _vif_metrics);
else
return session.proxy.vif_metrics_get_last_updated(session.opaque_ref, _vif_metrics ?? "").parse();
}
/// <summary>
/// Get the other_config field of the given VIF_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
public static Dictionary<string, string> get_other_config(Session session, string _vif_metrics)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_other_config(session.opaque_ref, _vif_metrics);
else
return Maps.convert_from_proxy_string_string(session.proxy.vif_metrics_get_other_config(session.opaque_ref, _vif_metrics ?? "").parse());
}
/// <summary>
/// Set the other_config field of the given VIF_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
/// <param name="_other_config">New value to set</param>
public static void set_other_config(Session session, string _vif_metrics, Dictionary<string, string> _other_config)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vif_metrics_set_other_config(session.opaque_ref, _vif_metrics, _other_config);
else
session.proxy.vif_metrics_set_other_config(session.opaque_ref, _vif_metrics ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse();
}
/// <summary>
/// Add the given key-value pair to the other_config field of the given VIF_metrics.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
/// <param name="_key">Key to add</param>
/// <param name="_value">Value to add</param>
public static void add_to_other_config(Session session, string _vif_metrics, string _key, string _value)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vif_metrics_add_to_other_config(session.opaque_ref, _vif_metrics, _key, _value);
else
session.proxy.vif_metrics_add_to_other_config(session.opaque_ref, _vif_metrics ?? "", _key ?? "", _value ?? "").parse();
}
/// <summary>
/// Remove the given key and its corresponding value from the other_config field of the given VIF_metrics. If the key is not in that Map, then do nothing.
/// First published in XenServer 5.0.
/// </summary>
/// <param name="session">The session</param>
/// <param name="_vif_metrics">The opaque_ref of the given vif_metrics</param>
/// <param name="_key">Key to remove</param>
public static void remove_from_other_config(Session session, string _vif_metrics, string _key)
{
if (session.JsonRpcClient != null)
session.JsonRpcClient.vif_metrics_remove_from_other_config(session.opaque_ref, _vif_metrics, _key);
else
session.proxy.vif_metrics_remove_from_other_config(session.opaque_ref, _vif_metrics ?? "", _key ?? "").parse();
}
/// <summary>
/// Return a list of all the VIF_metrics instances known to the system.
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static List<XenRef<VIF_metrics>> get_all(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_all(session.opaque_ref);
else
return XenRef<VIF_metrics>.Create(session.proxy.vif_metrics_get_all(session.opaque_ref).parse());
}
/// <summary>
/// Get all the VIF_metrics Records at once, in a single XML RPC call
/// First published in XenServer 4.0.
/// </summary>
/// <param name="session">The session</param>
public static Dictionary<XenRef<VIF_metrics>, VIF_metrics> get_all_records(Session session)
{
if (session.JsonRpcClient != null)
return session.JsonRpcClient.vif_metrics_get_all_records(session.opaque_ref);
else
return XenRef<VIF_metrics>.Create<Proxy_VIF_metrics>(session.proxy.vif_metrics_get_all_records(session.opaque_ref).parse());
}
/// <summary>
/// Unique identifier/object reference
/// </summary>
public virtual string uuid
{
get { return _uuid; }
set
{
if (!Helper.AreEqual(value, _uuid))
{
_uuid = value;
Changed = true;
NotifyPropertyChanged("uuid");
}
}
}
private string _uuid = "";
/// <summary>
/// Read bandwidth (KiB/s)
/// </summary>
public virtual double io_read_kbs
{
get { return _io_read_kbs; }
set
{
if (!Helper.AreEqual(value, _io_read_kbs))
{
_io_read_kbs = value;
Changed = true;
NotifyPropertyChanged("io_read_kbs");
}
}
}
private double _io_read_kbs;
/// <summary>
/// Write bandwidth (KiB/s)
/// </summary>
public virtual double io_write_kbs
{
get { return _io_write_kbs; }
set
{
if (!Helper.AreEqual(value, _io_write_kbs))
{
_io_write_kbs = value;
Changed = true;
NotifyPropertyChanged("io_write_kbs");
}
}
}
private double _io_write_kbs;
/// <summary>
/// Time at which this information was last updated
/// </summary>
[JsonConverter(typeof(XenDateTimeConverter))]
public virtual DateTime last_updated
{
get { return _last_updated; }
set
{
if (!Helper.AreEqual(value, _last_updated))
{
_last_updated = value;
Changed = true;
NotifyPropertyChanged("last_updated");
}
}
}
private DateTime _last_updated;
/// <summary>
/// additional configuration
/// First published in XenServer 5.0.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> other_config
{
get { return _other_config; }
set
{
if (!Helper.AreEqual(value, _other_config))
{
_other_config = value;
Changed = true;
NotifyPropertyChanged("other_config");
}
}
}
private Dictionary<string, string> _other_config = new Dictionary<string, string>() {};
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.PythonTools.Analysis;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Tagging;
using Microsoft.VisualStudioTools;
using SR = Microsoft.PythonTools.Project.SR;
namespace Microsoft.PythonTools.Intellisense {
class TaskProviderItem {
private readonly string _message;
private readonly ITrackingSpan _span;
private readonly SourceSpan _rawSpan;
private readonly VSTASKPRIORITY _priority;
private readonly VSTASKCATEGORY _category;
private readonly bool _squiggle;
private readonly ITextSnapshot _snapshot;
private readonly IServiceProvider _serviceProvider;
internal TaskProviderItem(
IServiceProvider serviceProvider,
string message,
SourceSpan rawSpan,
VSTASKPRIORITY priority,
VSTASKCATEGORY category,
bool squiggle,
ITextSnapshot snapshot
) {
_serviceProvider = serviceProvider;
_message = message;
_rawSpan = rawSpan;
_snapshot = snapshot;
_span = snapshot != null ? CreateSpan(snapshot, rawSpan) : null;
_rawSpan = rawSpan;
_priority = priority;
_category = category;
_squiggle = squiggle;
}
private string ErrorType {
get {
switch (_priority) {
case VSTASKPRIORITY.TP_HIGH:
return PredefinedErrorTypeNames.SyntaxError;
case VSTASKPRIORITY.TP_LOW:
return PredefinedErrorTypeNames.OtherError;
case VSTASKPRIORITY.TP_NORMAL:
return PredefinedErrorTypeNames.Warning;
default:
return string.Empty;
}
}
}
#region Conversion Functions
public bool IsValid {
get {
if (!_squiggle || _snapshot == null || _span == null || string.IsNullOrEmpty(ErrorType)) {
return false;
}
return true;
}
}
public void CreateSquiggleSpan(SimpleTagger<ErrorTag> tagger) {
tagger.CreateTagSpan(_span, new ErrorTag(ErrorType, _message));
}
public ITextSnapshot Snapshot {
get {
return _snapshot;
}
}
public ErrorTaskItem ToErrorTaskItem(EntryKey key) {
return new ErrorTaskItem(
_serviceProvider,
_rawSpan,
_message,
(key.Entry != null ? key.Entry.FilePath : null) ?? string.Empty
) {
Priority = _priority,
Category = _category
};
}
#endregion
private static ITrackingSpan CreateSpan(ITextSnapshot snapshot, SourceSpan span) {
Debug.Assert(span.Start.Index >= 0);
var res = new Span(
span.Start.Index,
Math.Min(span.End.Index - span.Start.Index, Math.Max(snapshot.Length - span.Start.Index, 0))
);
Debug.Assert(res.End <= snapshot.Length);
return snapshot.CreateTrackingSpan(res, SpanTrackingMode.EdgeNegative);
}
}
sealed class TaskProviderItemFactory {
private readonly ITextSnapshot _snapshot;
public TaskProviderItemFactory(
ITextSnapshot snapshot
) {
_snapshot = snapshot;
}
#region Factory Functions
public TaskProviderItem FromErrorResult(IServiceProvider serviceProvider, ErrorResult result, VSTASKPRIORITY priority, VSTASKCATEGORY category) {
return new TaskProviderItem(
serviceProvider,
result.Message,
result.Span,
priority,
category,
true,
_snapshot
);
}
internal TaskProviderItem FromUnresolvedImport(
IServiceProvider serviceProvider,
IPythonInterpreterFactoryWithDatabase factory,
string importName,
SourceSpan span
) {
string message;
if (factory != null && !factory.IsCurrent) {
message = SR.GetString(SR.UnresolvedModuleTooltipRefreshing, importName);
} else {
message = SR.GetString(SR.UnresolvedModuleTooltip, importName);
}
return new TaskProviderItem(
serviceProvider,
message,
span,
VSTASKPRIORITY.TP_NORMAL,
VSTASKCATEGORY.CAT_BUILDCOMPILE,
true,
_snapshot
);
}
#endregion
}
struct EntryKey : IEquatable<EntryKey> {
public IProjectEntry Entry;
public string Moniker;
public static readonly EntryKey Empty = new EntryKey(null, null);
public EntryKey(IProjectEntry entry, string moniker) {
Entry = entry;
Moniker = moniker;
}
public override bool Equals(object obj) {
return obj is EntryKey && Equals((EntryKey)obj);
}
public bool Equals(EntryKey other) {
return Entry == other.Entry && Moniker == other.Moniker;
}
public override int GetHashCode() {
return (Entry == null ? 0 : Entry.GetHashCode()) ^ (Moniker ?? string.Empty).GetHashCode();
}
}
abstract class WorkerMessage {
private readonly EntryKey _key;
private readonly List<TaskProviderItem> _items;
protected WorkerMessage() {
_key = EntryKey.Empty;
}
protected WorkerMessage(EntryKey key, List<TaskProviderItem> items) {
_key = key;
_items = items;
}
public abstract bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock);
// Factory methods
public static WorkerMessage Clear() {
return new ClearMessage(EntryKey.Empty);
}
public static WorkerMessage Clear(IProjectEntry entry, string moniker) {
return new ClearMessage(new EntryKey(entry, moniker));
}
public static WorkerMessage Replace(IProjectEntry entry, string moniker, List<TaskProviderItem> items) {
return new ReplaceMessage(new EntryKey(entry, moniker), items);
}
public static WorkerMessage Append(IProjectEntry entry, string moniker, List<TaskProviderItem> items) {
return new AppendMessage(new EntryKey(entry, moniker), items);
}
public static WorkerMessage Flush(TaskCompletionSource<TimeSpan> taskSource) {
return new FlushMessage(taskSource, DateTime.Now);
}
public static WorkerMessage Abort() {
return new AbortMessage();
}
// Message implementations
sealed class ReplaceMessage : WorkerMessage {
public ReplaceMessage(EntryKey key, List<TaskProviderItem> items)
: base(key, items) { }
public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) {
lock (itemsLock) {
items[_key] = _items;
return true;
}
}
}
sealed class AppendMessage : WorkerMessage {
public AppendMessage(EntryKey key, List<TaskProviderItem> items)
: base(key, items) { }
public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) {
lock (itemsLock) {
List<TaskProviderItem> itemList;
if (items.TryGetValue(_key, out itemList)) {
itemList.AddRange(_items);
} else {
items[_key] = _items;
}
return true;
}
}
}
sealed class ClearMessage : WorkerMessage {
public ClearMessage(EntryKey key)
: base(key, null) { }
public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) {
lock (itemsLock) {
if (_key.Entry != null) {
items.Remove(_key);
} else {
items.Clear();
}
// Always return true to ensure the refresh occurs
return true;
}
}
}
internal sealed class FlushMessage : WorkerMessage {
private readonly TaskCompletionSource<TimeSpan> _tcs;
private readonly DateTime _start;
public FlushMessage(TaskCompletionSource<TimeSpan> taskSource, DateTime start)
: base(EntryKey.Empty, null) {
_tcs = taskSource;
_start = start;
}
public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) {
_tcs.SetResult(DateTime.Now - _start);
return false;
}
}
internal sealed class AbortMessage : WorkerMessage {
public AbortMessage() : base() { }
public override bool Apply(Dictionary<EntryKey, List<TaskProviderItem>> items, object itemsLock) {
throw new OperationCanceledException();
}
}
}
abstract class TaskProvider : IVsTaskProvider, IDisposable {
private readonly Dictionary<EntryKey, List<TaskProviderItem>> _items;
private readonly Dictionary<EntryKey, HashSet<ITextBuffer>> _errorSources;
private readonly object _itemsLock = new object();
private uint _cookie;
private readonly IVsTaskList _taskList;
internal readonly IErrorProviderFactory _errorProvider;
protected readonly IServiceProvider _serviceProvider;
private Thread _worker;
private readonly Queue<WorkerMessage> _workerQueue = new Queue<WorkerMessage>();
private readonly ManualResetEventSlim _workerQueueChanged = new ManualResetEventSlim();
public TaskProvider(IServiceProvider serviceProvider, IVsTaskList taskList, IErrorProviderFactory errorProvider) {
_serviceProvider = serviceProvider;
_items = new Dictionary<EntryKey, List<TaskProviderItem>>();
_errorSources = new Dictionary<EntryKey, HashSet<ITextBuffer>>();
_taskList = taskList;
_errorProvider = errorProvider;
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
var worker = _worker;
if (worker != null) {
lock (_workerQueue) {
_workerQueue.Clear();
_workerQueue.Enqueue(WorkerMessage.Abort());
_workerQueueChanged.Set();
}
bool stopped = worker.Join(10000);
Debug.Assert(stopped, "Failed to terminate TaskProvider worker thread");
}
lock (_itemsLock) {
_items.Clear();
}
if (_taskList != null) {
_taskList.UnregisterTaskProvider(_cookie);
}
_workerQueueChanged.Dispose();
}
}
~TaskProvider() {
Dispose(false);
}
public uint Cookie {
get {
return _cookie;
}
}
/// <summary>
/// Replaces the items for the specified entry.
/// </summary>
public void ReplaceItems(IProjectEntry entry, string moniker, List<TaskProviderItem> items) {
SendMessage(WorkerMessage.Replace(entry, moniker, items));
}
/// <summary>
/// Adds items to the specified entry's existing items.
/// </summary>
public void AddItems(IProjectEntry entry, string moniker, List<TaskProviderItem> items) {
SendMessage(WorkerMessage.Append(entry, moniker, items));
}
/// <summary>
/// Removes all items from all entries.
/// </summary>
public void ClearAll() {
SendMessage(WorkerMessage.Clear());
}
/// <summary>
/// Removes all items for the specified entry.
/// </summary>
public void Clear(IProjectEntry entry, string moniker) {
SendMessage(WorkerMessage.Clear(entry, moniker));
}
/// <summary>
/// Waits for all messages to clear the queue. This typically takes at
/// least one second, since that is the timeout on the worker thread.
/// </summary>
/// <returns>
/// The time between when flush was called and the queue completed.
/// </returns>
public Task<TimeSpan> FlushAsync() {
var tcs = new TaskCompletionSource<TimeSpan>();
SendMessage(WorkerMessage.Flush(tcs));
return tcs.Task;
}
/// <summary>
/// Adds the buffer to be tracked for reporting squiggles and error list entries
/// for the given project entry and moniker for the error source.
/// </summary>
public void AddBufferForErrorSource(IProjectEntry entry, string moniker, ITextBuffer buffer) {
lock (_errorSources) {
var key = new EntryKey(entry, moniker);
HashSet<ITextBuffer> buffers;
if (!_errorSources.TryGetValue(key, out buffers)) {
_errorSources[new EntryKey(entry, moniker)] = buffers = new HashSet<ITextBuffer>();
}
buffers.Add(buffer);
}
}
/// <summary>
/// Removes the buffer from tracking for reporting squiggles and error list entries
/// for the given project entry and moniker for the error source.
/// </summary>
public void RemoveBufferForErrorSource(IProjectEntry entry, string moniker, ITextBuffer buffer) {
lock (_errorSources) {
var key = new EntryKey(entry, moniker);
HashSet<ITextBuffer> buffers;
if (_errorSources.TryGetValue(key, out buffers)) {
buffers.Remove(buffer);
}
}
}
/// <summary>
/// Clears all tracked buffers for the given project entry and moniker for
/// the error source.
/// </summary>
public void ClearErrorSource(IProjectEntry entry, string moniker) {
lock (_errorSources) {
_errorSources.Remove(new EntryKey(entry, moniker));
}
}
#region Internal Worker Thread
private void StartWorker() {
if (_worker != null) {
// Already running
Debug.Assert(_worker.IsAlive, "Worker has died without clearing itself");
return;
}
var t = new Thread(Worker);
t.IsBackground = true;
t.Name = GetType().Name + " Worker";
t.Start(t);
}
private void Worker(object param) {
var self = (Thread)param;
if (Interlocked.CompareExchange(ref _worker, self, null) != null) {
// Not us, so abort
return;
}
try {
WorkerWorker();
} catch (OperationCanceledException) {
} catch (ObjectDisposedException ex) {
Trace.TraceError(ex.ToString());
} catch (Exception ex) {
if (ex.IsCriticalException()) {
throw;
}
VsTaskExtensions.ReportUnhandledException(ex, SR.ProductName, GetType());
} finally {
var oldWorker = Interlocked.CompareExchange(ref _worker, null, self);
Debug.Assert(oldWorker == self, "Worker was changed while running");
}
}
private void WorkerWorker() {
var flushMessages = new Queue<WorkerMessage>();
bool changed = false;
var lastUpdateTime = DateTime.Now;
while (_workerQueueChanged.Wait(1000)) {
// Reset event and handle all messages in the queue
_workerQueueChanged.Reset();
while (true) {
WorkerMessage msg;
lock (_workerQueue) {
if (_workerQueue.Count == 0) {
break;
}
msg = _workerQueue.Dequeue();
}
if (msg is WorkerMessage.FlushMessage) {
// Keep flush messages until we've exited the loop
flushMessages.Enqueue(msg);
} else {
// Apply the message to our collection
changed |= msg.Apply(_items, _itemsLock);
}
// Every second, we want to force another update
if (changed) {
var currentTime = DateTime.Now;
if ((currentTime - lastUpdateTime).TotalMilliseconds > 1000) {
Refresh();
lastUpdateTime = currentTime;
changed = false;
}
}
}
}
// Handle any changes that weren't handled in the loop
if (changed) {
Refresh();
}
// Notify all the flush messages we received
while (flushMessages.Any()) {
var msg = flushMessages.Dequeue();
msg.Apply(_items, _itemsLock);
}
}
private void Refresh() {
if (_taskList != null || _errorProvider != null) {
_serviceProvider.GetUIThread().MustNotBeCalledFromUIThread();
RefreshAsync().WaitAndHandleAllExceptions(SR.ProductName, GetType());
}
}
private async Task RefreshAsync() {
var buffers = new HashSet<ITextBuffer>();
var bufferToErrorList = new Dictionary<ITextBuffer, List<TaskProviderItem>>();
if (_errorProvider != null) {
lock (_errorSources) {
foreach (var kv in _errorSources) {
List<TaskProviderItem> items;
buffers.UnionWith(kv.Value);
lock (_itemsLock) {
if (!_items.TryGetValue(kv.Key, out items)) {
continue;
}
foreach (var item in items) {
if (item.IsValid) {
List<TaskProviderItem> itemList;
if (!bufferToErrorList.TryGetValue(item.Snapshot.TextBuffer, out itemList)) {
bufferToErrorList[item.Snapshot.TextBuffer] = itemList = new List<TaskProviderItem>();
}
itemList.Add(item);
}
}
}
}
}
}
await _serviceProvider.GetUIThread().InvokeAsync(() => {
if (_taskList != null) {
if (_cookie == 0) {
ErrorHandler.ThrowOnFailure(_taskList.RegisterTaskProvider(this, out _cookie));
}
try {
_taskList.RefreshTasks(_cookie);
} catch (InvalidComObjectException) {
// DevDiv2 759317 - Watson bug, COM object can go away...
}
}
if (_errorProvider != null) {
foreach (var kv in bufferToErrorList) {
var tagger = _errorProvider.GetErrorTagger(kv.Key);
if (tagger == null) {
continue;
}
if (buffers.Remove(kv.Key)) {
tagger.RemoveTagSpans(span => span.Span.TextBuffer == kv.Key);
}
foreach (var taskProviderItem in kv.Value) {
taskProviderItem.CreateSquiggleSpan(tagger);
}
}
if (buffers.Any()) {
// Clear tags for any remaining buffers.
foreach (var buffer in buffers) {
var tagger = _errorProvider.GetErrorTagger(buffer);
tagger.RemoveTagSpans(span => span.Span.TextBuffer == buffer);
}
}
}
});
}
private void SendMessage(WorkerMessage message) {
lock (_workerQueue) {
_workerQueue.Enqueue(message);
_workerQueueChanged.Set();
}
StartWorker();
}
#endregion
#region IVsTaskProvider Members
public int EnumTaskItems(out IVsEnumTaskItems ppenum) {
lock (_itemsLock) {
ppenum = new TaskEnum(_items
.Where(x => x.Key.Entry.FilePath != null) // don't report REPL window errors in the error list, you can't naviagate to them
.SelectMany(kv => kv.Value.Select(i => i.ToErrorTaskItem(kv.Key)))
.ToArray()
);
}
return VSConstants.S_OK;
}
public int ImageList(out IntPtr phImageList) {
// not necessary if we report our category as build compile.
phImageList = IntPtr.Zero;
return VSConstants.E_NOTIMPL;
}
public int OnTaskListFinalRelease(IVsTaskList pTaskList) {
return VSConstants.S_OK;
}
public int ReRegistrationKey(out string pbstrKey) {
pbstrKey = null;
return VSConstants.E_NOTIMPL;
}
public int SubcategoryList(uint cbstr, string[] rgbstr, out uint pcActual) {
pcActual = 0;
return VSConstants.S_OK;
}
#endregion
}
class TaskEnum : IVsEnumTaskItems {
private readonly IEnumerable<ErrorTaskItem> _enumerable;
private IEnumerator<ErrorTaskItem> _enumerator;
public TaskEnum(IEnumerable<ErrorTaskItem> items) {
_enumerable = items;
_enumerator = _enumerable.GetEnumerator();
}
public int Clone(out IVsEnumTaskItems ppenum) {
ppenum = new TaskEnum(_enumerable);
return VSConstants.S_OK;
}
public int Next(uint celt, IVsTaskItem[] rgelt, uint[] pceltFetched = null) {
bool fetchedAny = false;
if (pceltFetched != null && pceltFetched.Length > 0) {
pceltFetched[0] = 0;
}
for (int i = 0; i < celt && _enumerator.MoveNext(); i++) {
if (pceltFetched != null && pceltFetched.Length > 0) {
pceltFetched[0] = (uint)i + 1;
}
rgelt[i] = _enumerator.Current;
fetchedAny = true;
}
return fetchedAny ? VSConstants.S_OK : VSConstants.S_FALSE;
}
public int Reset() {
_enumerator = _enumerable.GetEnumerator();
return VSConstants.S_OK;
}
public int Skip(uint celt) {
while (celt != 0 && _enumerator.MoveNext()) {
celt--;
}
return VSConstants.S_OK;
}
}
class ErrorTaskItem : IVsTaskItem {
private readonly IServiceProvider _serviceProvider;
public ErrorTaskItem(
IServiceProvider serviceProvider,
SourceSpan span,
string message,
string sourceFile
) {
_serviceProvider = serviceProvider;
Span = span;
Message = message;
SourceFile = sourceFile;
Category = VSTASKCATEGORY.CAT_BUILDCOMPILE;
Priority = VSTASKPRIORITY.TP_NORMAL;
MessageIsReadOnly = true;
IsCheckedIsReadOnly = true;
PriorityIsReadOnly = true;
}
public SourceSpan Span { get; private set; }
public string Message { get; set; }
public string SourceFile { get; set; }
public VSTASKCATEGORY Category { get; set; }
public VSTASKPRIORITY Priority { get; set; }
public bool CanDelete { get; set; }
public bool IsChecked { get; set; }
public bool MessageIsReadOnly { get; set; }
public bool IsCheckedIsReadOnly { get; set; }
public bool PriorityIsReadOnly { get; set; }
int IVsTaskItem.CanDelete(out int pfCanDelete) {
pfCanDelete = CanDelete ? 1 : 0;
return VSConstants.S_OK;
}
int IVsTaskItem.Category(VSTASKCATEGORY[] pCat) {
pCat[0] = Category;
return VSConstants.S_OK;
}
int IVsTaskItem.Column(out int piCol) {
if (Span.Start.Line == 1 && Span.Start.Column == 1 && Span.Start.Index != 0) {
// we don't have the column number calculated
piCol = 0;
return VSConstants.E_FAIL;
}
piCol = Span.Start.Column - 1;
return VSConstants.S_OK;
}
int IVsTaskItem.Document(out string pbstrMkDocument) {
pbstrMkDocument = SourceFile;
return VSConstants.S_OK;
}
int IVsTaskItem.HasHelp(out int pfHasHelp) {
pfHasHelp = 0;
return VSConstants.S_OK;
}
int IVsTaskItem.ImageListIndex(out int pIndex) {
pIndex = 0;
return VSConstants.E_NOTIMPL;
}
int IVsTaskItem.IsReadOnly(VSTASKFIELD field, out int pfReadOnly) {
switch (field) {
case VSTASKFIELD.FLD_CHECKED:
pfReadOnly = IsCheckedIsReadOnly ? 1 : 0;
break;
case VSTASKFIELD.FLD_DESCRIPTION:
pfReadOnly = MessageIsReadOnly ? 1 : 0;
break;
case VSTASKFIELD.FLD_PRIORITY:
pfReadOnly = PriorityIsReadOnly ? 1 : 0;
break;
case VSTASKFIELD.FLD_BITMAP:
case VSTASKFIELD.FLD_CATEGORY:
case VSTASKFIELD.FLD_COLUMN:
case VSTASKFIELD.FLD_CUSTOM:
case VSTASKFIELD.FLD_FILE:
case VSTASKFIELD.FLD_LINE:
case VSTASKFIELD.FLD_PROVIDERKNOWSORDER:
case VSTASKFIELD.FLD_SUBCATEGORY:
default:
pfReadOnly = 1;
break;
}
return VSConstants.S_OK;
}
int IVsTaskItem.Line(out int piLine) {
if (Span.Start.Line == 1 && Span.Start.Column == 1 && Span.Start.Index != 0) {
// we don't have the line number calculated
piLine = 0;
return VSConstants.E_FAIL;
}
piLine = Span.Start.Line - 1;
return VSConstants.S_OK;
}
int IVsTaskItem.NavigateTo() {
try {
if (Span.Start.Line == 1 && Span.Start.Column == 1 && Span.Start.Index != 0) {
// we have just an absolute index, use that to naviagte
PythonToolsPackage.NavigateTo(_serviceProvider, SourceFile, Guid.Empty, Span.Start.Index);
} else {
PythonToolsPackage.NavigateTo(_serviceProvider, SourceFile, Guid.Empty, Span.Start.Line - 1, Span.Start.Column - 1);
}
return VSConstants.S_OK;
} catch (DirectoryNotFoundException) {
// This may happen when the error was in a file that's located inside a .zip archive.
// Let's walk the path and see if it is indeed the case.
for (var path = SourceFile; CommonUtils.IsValidPath(path); path = Path.GetDirectoryName(path)) {
if (!File.Exists(path)) {
continue;
}
var ext = Path.GetExtension(path);
if (string.Equals(ext, ".zip", StringComparison.OrdinalIgnoreCase) ||
string.Equals(ext, ".egg", StringComparison.OrdinalIgnoreCase)) {
MessageBox.Show(
"Opening source files contained in .zip archives is not supported",
"Cannot open file",
MessageBoxButtons.OK,
MessageBoxIcon.Information
);
return VSConstants.S_FALSE;
}
}
// If it failed for some other reason, let caller handle it.
throw;
}
}
int IVsTaskItem.NavigateToHelp() {
return VSConstants.E_NOTIMPL;
}
int IVsTaskItem.OnDeleteTask() {
return VSConstants.E_NOTIMPL;
}
int IVsTaskItem.OnFilterTask(int fVisible) {
return VSConstants.E_NOTIMPL;
}
int IVsTaskItem.SubcategoryIndex(out int pIndex) {
pIndex = 0;
return VSConstants.E_NOTIMPL;
}
int IVsTaskItem.get_Checked(out int pfChecked) {
pfChecked = IsChecked ? 1 : 0;
return VSConstants.S_OK;
}
int IVsTaskItem.get_Priority(VSTASKPRIORITY[] ptpPriority) {
ptpPriority[0] = Priority;
return VSConstants.S_OK;
}
int IVsTaskItem.get_Text(out string pbstrName) {
pbstrName = Message;
return VSConstants.S_OK;
}
int IVsTaskItem.put_Checked(int fChecked) {
if (IsCheckedIsReadOnly) {
return VSConstants.E_NOTIMPL;
}
IsChecked = (fChecked != 0);
return VSConstants.S_OK;
}
int IVsTaskItem.put_Priority(VSTASKPRIORITY tpPriority) {
if (PriorityIsReadOnly) {
return VSConstants.E_NOTIMPL;
}
Priority = tpPriority;
return VSConstants.S_OK;
}
int IVsTaskItem.put_Text(string bstrName) {
if (MessageIsReadOnly) {
return VSConstants.E_NOTIMPL;
}
Message = bstrName;
return VSConstants.S_OK;
}
}
// Two distinct types are used to distinguish the two in the VS service registry.
sealed class ErrorTaskProvider : TaskProvider {
public ErrorTaskProvider(IServiceProvider serviceProvider, IVsTaskList taskList, IErrorProviderFactory errorProvider)
: base(serviceProvider, taskList, errorProvider) {
}
}
sealed class CommentTaskProvider : TaskProvider, IVsTaskListEvents {
private volatile Dictionary<string, VSTASKPRIORITY> _tokens;
public CommentTaskProvider(IServiceProvider serviceProvider, IVsTaskList taskList, IErrorProviderFactory errorProvider)
: base(serviceProvider, taskList, errorProvider) {
RefreshTokens();
}
public Dictionary<string, VSTASKPRIORITY> Tokens {
get { return _tokens; }
}
public event EventHandler TokensChanged;
public int OnCommentTaskInfoChanged() {
RefreshTokens();
return VSConstants.S_OK;
}
// Retrieves token settings as defined by user in Tools -> Options -> Environment -> Task List.
private void RefreshTokens() {
var taskInfo = (IVsCommentTaskInfo)_serviceProvider.GetService(typeof(SVsTaskList));
if (taskInfo == null) {
return;
}
IVsEnumCommentTaskTokens enumTokens;
ErrorHandler.ThrowOnFailure(taskInfo.EnumTokens(out enumTokens));
var newTokens = new Dictionary<string, VSTASKPRIORITY>();
var token = new IVsCommentTaskToken[1];
uint fetched;
string text;
var priority = new VSTASKPRIORITY[1];
// DevDiv bug 1135485: EnumCommentTaskTokens.Next returns E_FAIL instead of S_FALSE
while (enumTokens.Next(1, token, out fetched) == VSConstants.S_OK && fetched > 0) {
ErrorHandler.ThrowOnFailure(token[0].Text(out text));
ErrorHandler.ThrowOnFailure(token[0].Priority(priority));
newTokens[text] = priority[0];
}
_tokens = newTokens;
var tokensChanged = TokensChanged;
if (tokensChanged != null) {
tokensChanged(this, EventArgs.Empty);
}
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using Soomla;
namespace Soomla.Store.Example {
/// <summary>
/// This class contains functions that initialize the game and that display the different screens of the game.
/// </summary>
public class ExampleWindow : MonoBehaviour {
private static ExampleWindow instance = null;
private GUIState guiState = GUIState.WELCOME;
private Vector2 goodsScrollPosition = Vector2.zero;
private Vector2 productScrollPosition = Vector2.zero;
private bool isDragging = false;
private Vector2 startTouch = Vector2.zero;
private bool checkAffordable = false;
public string fontSuffix = "";
private enum GUIState{
WELCOME,
PRODUCTS,
GOODS
}
private static bool isVisible = false;
/// <summary>
/// Initializes the game state before the game starts.
/// </summary>
void Awake(){
if(instance == null){ //making sure we only initialize one instance.
instance = this;
GameObject.DontDestroyOnLoad(this.gameObject);
} else { //Destroying unused instances.
GameObject.Destroy(this);
}
//FONT
//using max to be certain we have the longest side of the screen, even if we are in portrait.
if(Mathf.Max(Screen.width, Screen.height) > 640){
fontSuffix = "_2X"; //a nice suffix to show the fonts are twice as big as the original
}
}
private Texture2D tImgDirect;
private Texture2D tLogoNew;
private Font fgoodDog;
private Font fgoodDogSmall;
private Font fTitle;
private Texture2D tWhitePixel;
private Texture2D tMuffins;
private Font fName;
private Font fDesc;
private Font fBuy;
private Texture2D tBack;
private Texture2D tGetMore;
private Font tTitle;
private Dictionary<string, Texture2D> itemsTextures;
private Dictionary<string, bool> itemsAffordability;
private Reward firstLaunchReward;
/// <summary>
/// Starts this instance.
/// Use this for initialization.
/// </summary>
void Start () {
StoreEvents.OnSoomlaStoreInitialized += onSoomlaStoreInitialized;
StoreEvents.OnCurrencyBalanceChanged += onCurrencyBalanceChanged;
StoreEvents.OnUnexpectedStoreError += onUnexpectedStoreError;
tImgDirect = (Texture2D)Resources.Load("SoomlaStore/images/img_direct");
fgoodDog = (Font)Resources.Load("SoomlaStore/GoodDog" + fontSuffix);
fgoodDogSmall = (Font)Resources.Load("SoomlaStore/GoodDog_small" + fontSuffix);
tLogoNew = (Texture2D)Resources.Load("SoomlaStore/images/soomla_logo_new");
tWhitePixel = (Texture2D)Resources.Load("SoomlaStore/images/white_pixel");
fTitle = (Font)Resources.Load("SoomlaStore/Title" + fontSuffix);
tMuffins = (Texture2D)Resources.Load("SoomlaStore/images/Muffins");
fName = (Font)Resources.Load("SoomlaStore/Name" + fontSuffix);
fDesc = (Font)Resources.Load("SoomlaStore/Description" + fontSuffix);
fBuy = (Font)Resources.Load("SoomlaStore/Buy" + fontSuffix);
tBack = (Texture2D)Resources.Load("SoomlaStore/images/back");
tGetMore = (Texture2D)Resources.Load("SoomlaStore/images/GetMore");
tTitle = (Font)Resources.Load("SoomlaStore/Title" + fontSuffix);
firstLaunchReward = new VirtualItemReward("first-launch", "Give Money at first launch", MuffinRushAssets.MUFFIN_CURRENCY_ITEM_ID, 4000);
SoomlaStore.Initialize(new MuffinRushAssets());
}
public void onUnexpectedStoreError(int errorCode) {
SoomlaUtils.LogError ("ExampleEventHandler", "error with code: " + errorCode);
}
public void onSoomlaStoreInitialized() {
// some usage examples for add/remove currency
// some examples
if (StoreInfo.Currencies.Count>0) {
try {
//First launch reward
if(!firstLaunchReward.Owned)
{
firstLaunchReward.Give();
}
//How to give currency
//StoreInventory.GiveItem(StoreInfo.Currencies[0].ItemId,4000);
SoomlaUtils.LogDebug("SOOMLA ExampleEventHandler", "Currency balance:" + StoreInventory.GetItemBalance(StoreInfo.Currencies[0].ItemId));
} catch (VirtualItemNotFoundException ex){
SoomlaUtils.LogError("SOOMLA ExampleWindow", ex.Message);
}
}
setupItemsTextures();
setupItemsAffordability ();
}
public void setupItemsTextures() {
itemsTextures = new Dictionary<string, Texture2D>();
foreach(VirtualGood vg in StoreInfo.Goods){
itemsTextures[vg.ItemId] = (Texture2D)Resources.Load("SoomlaStore/images/" + vg.Name);
}
foreach(VirtualCurrencyPack vcp in StoreInfo.CurrencyPacks){
itemsTextures[vcp.ItemId] = (Texture2D)Resources.Load("SoomlaStore/images/" + vcp.Name);
}
}
public void setupItemsAffordability() {
itemsAffordability = new Dictionary<string, bool> ();
foreach (VirtualGood vg in StoreInfo.Goods) {
itemsAffordability.Add(vg.ID, StoreInventory.CanAfford(vg.ID));
}
}
public void onCurrencyBalanceChanged(VirtualCurrency virtualCurrency, int balance, int amountAdded) {
if (itemsAffordability != null)
{
List<string> keys = new List<string> (itemsAffordability.Keys);
foreach(string key in keys)
itemsAffordability[key] = StoreInventory.CanAfford(key);
}
}
/// <summary>
/// Sets the window to open, and sets the GUI state to welcome.
/// </summary>
public static void OpenWindow(){
instance.guiState = GUIState.WELCOME;
isVisible = true;
}
/// <summary>
/// Sets the window to closed.
/// </summary>
public static void CloseWindow(){
isVisible = false;
}
/// <summary>
/// Implements the game behavior of MuffinRush.
/// Overrides the superclass function in order to provide functionality for our game.
/// </summary>
void Update () {
if(isVisible){
//code to be able to scroll without the scrollbars.
if(Input.GetMouseButtonDown(0)){
startTouch = Input.mousePosition;
}else if(Input.GetMouseButtonUp(0)){
isDragging = false;
}else if(Input.GetMouseButton(0)){
if(!isDragging){
if( Mathf.Abs(startTouch.y-Input.mousePosition.y) > 10f){
isDragging = true;
}
}else{
if(guiState == GUIState.GOODS){
goodsScrollPosition.y -= startTouch.y - Input.mousePosition.y;
startTouch = Input.mousePosition;
}else if(guiState == GUIState.PRODUCTS){
productScrollPosition.y -= startTouch.y - Input.mousePosition.y;
startTouch = Input.mousePosition;
}
}
}
}
if (Application.platform == RuntimePlatform.Android) {
if (Input.GetKeyUp(KeyCode.Escape)) {
//quit application on back button
Application.Quit();
return;
}
}
}
/// <summary>
/// Calls the relevant function to display the correct screen of the game.
/// </summary>
void OnGUI(){
if(!isVisible){
return;
}
//GUI.skin.verticalScrollbar.fixedWidth = 0;
//GUI.skin.verticalScrollbar.fixedHeight = 0;
//GUI.skin.horizontalScrollbar.fixedWidth = 0;
//GUI.skin.horizontalScrollbar.fixedHeight = 0;
GUI.skin.horizontalScrollbar = GUIStyle.none;
GUI.skin.verticalScrollbar = GUIStyle.none;
//disabling warnings because we use GUIStyle.none which result in warnings
if(guiState == GUIState.WELCOME){
welcomeScreen();
}else if(guiState == GUIState.GOODS){
goodsScreen();
}else if(guiState == GUIState.PRODUCTS){
currencyScreen();
}
}
/// <summary>
/// Displays the welcome screen of the game.
/// </summary>
void welcomeScreen()
{
//drawing background, just using a white pixel here
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tImgDirect);
//changing the font and alignment the label, and making a backup so we can put it back.
Font backupFont = GUI.skin.label.font;
TextAnchor backupAlignment = GUI.skin.label.alignment;
GUI.skin.label.font = fgoodDog;
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
//writing the text.
GUI.Label(new Rect(Screen.width/8,Screen.height/8f,Screen.width*6f/8f,Screen.height*0.3f),"Soomla Store\nExample");
//select the small font
GUI.skin.label.font = fgoodDogSmall;
GUI.Label(new Rect(Screen.width/8,Screen.height*7f/8f,Screen.width*6f/8f,Screen.height/8f),"Press the SOOMLA-bot to open store");
//set font back to original
GUI.skin.label.font = backupFont;
GUI.Label(new Rect(Screen.width*0.25f,Screen.height/2-50,Screen.width*0.5f,100),"[ Your game here ]");
//drawing button and testing if it has been clicked
if(GUI.Button(new Rect(Screen.width*2/6,Screen.height*5f/8f,Screen.width*2/6,Screen.width*2/6),tLogoNew)){
guiState = GUIState.GOODS;
#if UNITY_ANDROID && !UNITY_EDITOR
SoomlaStore.StartIabServiceInBg();
#endif
}
//set alignment to backup
GUI.skin.label.alignment = backupAlignment;
}
/// <summary>
/// Display the goods screen of the game's store.
/// </summary>
void goodsScreen()
{
//white background
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height), tWhitePixel);
Color backupColor = GUI.color;
TextAnchor backupAlignment = GUI.skin.label.alignment;
Font backupFont = GUI.skin.label.font;
GUI.color = Color.red;
GUI.skin.label.alignment = TextAnchor.UpperLeft;
GUI.Label(new Rect(10,10,Screen.width-10,Screen.height-10),"SOOMLA Example Store");
GUI.color = Color.black;
GUI.skin.label.alignment = TextAnchor.UpperRight;
string cItemId = StoreInfo.Currencies[0].ItemId;
GUI.Label(new Rect(10,10,Screen.width-40,20),""+ StoreInventory.GetItemBalance(cItemId));
checkAffordable = GUI.Toggle(new Rect(10,30,Screen.width-40,20), checkAffordable, "Check Affordability");
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.skin.label.font = fTitle;
GUI.Label(new Rect(0,Screen.height/8f,Screen.width,Screen.height/8f),"Virtual Goods");
GUI.color = backupColor;
GUI.DrawTexture(new Rect(Screen.width-30,10,30,30), tMuffins);
float productSize = Screen.width*0.30f;
float totalHeight = StoreInfo.Goods.Count*productSize;
//Here we start a scrollView, the first rectangle is the position of the scrollView on the screen,
//the second rectangle is the size of the panel inside the scrollView.
//All rectangles after this point are relative to the position of the scrollView.
goodsScrollPosition = GUI.BeginScrollView(new Rect(0,Screen.height*2f/8f,Screen.width,Screen.height*5f/8f),goodsScrollPosition,new Rect(0,0,Screen.width,totalHeight));
float y = 0;
foreach(VirtualGood vg in StoreInfo.Goods){
GUI.color = backupColor;
bool isAffordable = true;
if (checkAffordable){
bool affordable;
if (itemsAffordability.TryGetValue(vg.ID, out affordable))
isAffordable = affordable;
}
GUI.enabled = isAffordable;
if(GUI.Button(new Rect(0,y,Screen.width,productSize),"") && !isDragging){
Debug.Log("SOOMLA/UNITY wants to buy: " + vg.Name);
try {
StoreInventory.BuyItem(vg.ItemId);
} catch (Exception e) {
Debug.LogError ("SOOMLA/UNITY " + e.Message);
}
}
GUI.DrawTexture(new Rect(0,y,Screen.width,productSize),tWhitePixel);
//We draw a button so we can detect a touch and then draw an image on top of it.
//TODO
//Resources.Load(path) The path is the relative path starting from the Resources folder.
//Make sure the images used for UI, have the textureType GUI. You can change this in the Unity editor.
GUI.color = backupColor;
GUI.DrawTexture(new Rect(0+productSize/8f, y+productSize/8f,productSize*6f/8f,productSize*6f/8f), itemsTextures[vg.ItemId]);
GUI.color = Color.black;
GUI.skin.label.font = fName;
GUI.skin.label.alignment = TextAnchor.UpperLeft;
GUI.Label(new Rect(productSize,y,Screen.width,productSize/3f),vg.Name);
GUI.skin.label.font = fDesc;
GUI.Label(new Rect(productSize + 10f,y+productSize/3f,Screen.width-productSize-15f,productSize/3f),vg.Description);
//set price
if (vg.PurchaseType is PurchaseWithVirtualItem) {
GUI.Label(new Rect(Screen.width/2f,y+productSize*2/3f,Screen.width,productSize/3f),"price:" + ((PurchaseWithVirtualItem)vg.PurchaseType).Amount);
}
else {
string price = ((PurchaseWithMarket)vg.PurchaseType).MarketItem.MarketPriceAndCurrency;
if (string.IsNullOrEmpty(price)) {
price = ((PurchaseWithMarket)vg.PurchaseType).MarketItem.Price.ToString("0.00");
}
GUI.Label(new Rect(Screen.width/2f,y+productSize*2/3f,Screen.width,productSize/3f),"price: " + price);
}
GUI.Label(new Rect(Screen.width*3/4f,y+productSize*2/3f,Screen.width,productSize/3f), "Balance:" + StoreInventory.GetItemBalance(vg.ItemId));
GUI.skin.label.alignment = TextAnchor.UpperRight;
GUI.skin.label.font = fBuy;
if (GUI.enabled)
GUI.Label(new Rect(0,y,Screen.width-10,productSize),"Click to buy");
else
GUI.Label(new Rect(0,y,Screen.width-10,productSize),"Cannot afford");
GUI.color = Color.grey;
GUI.DrawTexture(new Rect(0,y+productSize-1,Screen.width,1),tWhitePixel);
y+= productSize;
GUI.enabled = true;
}
GUI.EndScrollView();
//We have just ended the scroll view this means that all the positions are relative top-left corner again.
GUI.skin.label.alignment = backupAlignment;
GUI.color = backupColor;
GUI.skin.label.font = backupFont;
float height = Screen.height/8f;
float borderSize = height/8f;
float buttonHeight = height-2*borderSize;
float width = buttonHeight*180/95;
if(GUI.Button(new Rect(Screen.width*2f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight), "back")){
guiState = GUIState.WELCOME;
#if UNITY_ANDROID && !UNITY_EDITOR
SoomlaStore.StopIabServiceInBg();
#endif
}
GUI.DrawTexture(new Rect(Screen.width*2f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight),tBack);
width = buttonHeight*227/94;
if(GUI.Button(new Rect(Screen.width*5f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight), "back")){
guiState = GUIState.PRODUCTS;
}
GUI.DrawTexture(new Rect(Screen.width*5f/7f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight),tGetMore);
}
/// <summary>
/// Displays the currencies screen of the game's store.
/// </summary>
void currencyScreen()
{
//white background
GUI.DrawTexture(new Rect(0,0,Screen.width,Screen.height),tWhitePixel);
Color backupColor = GUI.color;
TextAnchor backupAlignment = GUI.skin.label.alignment;
Font backupFont = GUI.skin.label.font;
GUI.color = Color.red;
GUI.skin.label.alignment = TextAnchor.UpperLeft;
GUI.Label(new Rect(10,10,Screen.width-10,Screen.height-10),"SOOMLA Example Store");
GUI.color = Color.black;
GUI.skin.label.alignment = TextAnchor.UpperRight;
string cItemId = StoreInfo.Currencies[0].ItemId;
GUI.Label(new Rect(10,10,Screen.width-40,Screen.height),""+ StoreInventory.GetItemBalance(cItemId));
GUI.skin.label.alignment = TextAnchor.MiddleCenter;
GUI.skin.label.font = tTitle;
GUI.Label(new Rect(0,Screen.height/8f,Screen.width,Screen.height/8f),"Virtual Currency Packs");
GUI.color = backupColor;
GUI.DrawTexture(new Rect(Screen.width-30,10,30,30),tMuffins);
float productSize = Screen.width*0.30f;
float totalHeight = StoreInfo.CurrencyPacks.Count*productSize;
//Here we start a scrollView, the first rectangle is the position of the scrollView on the screen,
//the second rectangle is the size of the panel inside the scrollView.
//All rectangles after this point are relative to the position of the scrollView.
productScrollPosition = GUI.BeginScrollView(new Rect(0,Screen.height*2f/8f,Screen.width,Screen.height*5f/8f),productScrollPosition,new Rect(0,0,Screen.width,totalHeight));
float y = 0;
foreach(VirtualCurrencyPack cp in StoreInfo.CurrencyPacks){
GUI.color = backupColor;
//We draw a button so we can detect a touch and then draw an image on top of it.
if(GUI.Button(new Rect(0,y,Screen.width,productSize),"") && !isDragging){
Debug.Log("SOOMLA/UNITY Wants to buy: " + cp.Name);
try {
StoreInventory.BuyItem(cp.ItemId);
} catch (Exception e) {
Debug.Log ("SOOMLA/UNITY " + e.Message);
}
}
GUI.DrawTexture(new Rect(0,y,Screen.width,productSize),tWhitePixel);
//Resources.Load(path) The path is the relative path starting from the Resources folder.
//Make sure the images used for UI, have the textureType GUI. You can change this in the Unity editor.
GUI.DrawTexture(new Rect(0+productSize/8f, y+productSize/8f,productSize*6f/8f,productSize*6f/8f),itemsTextures[cp.ItemId]);
GUI.color = Color.black;
GUI.skin.label.font = fName;
GUI.skin.label.alignment = TextAnchor.UpperLeft;
GUI.Label(new Rect(productSize,y,Screen.width,productSize/3f),cp.Name);
GUI.skin.label.font = fDesc;
GUI.Label(new Rect(productSize + 10f,y+productSize/3f,Screen.width-productSize-15f,productSize/3f),cp.Description);
string price = ((PurchaseWithMarket)cp.PurchaseType).MarketItem.MarketPriceAndCurrency;
if (string.IsNullOrEmpty(price)) {
price = ((PurchaseWithMarket)cp.PurchaseType).MarketItem.Price.ToString("0.00");
}
GUI.Label(new Rect(Screen.width*3/4f,y+productSize*2/3f,Screen.width,productSize/3f),"price:" + price);
GUI.skin.label.alignment = TextAnchor.UpperRight;
GUI.skin.label.font = fBuy;
GUI.Label(new Rect(0,y,Screen.width-10,productSize),"Click to buy");
GUI.color = Color.grey;
GUI.DrawTexture(new Rect(0,y+productSize-1,Screen.width,1),tWhitePixel);
y+= productSize;
}
GUI.EndScrollView();
//We have just ended the scroll view this means that all the positions are relative top-left corner again.
GUI.skin.label.alignment = backupAlignment;
GUI.color = backupColor;
GUI.skin.label.font = backupFont;
float height = Screen.height/8f;
float borderSize = height/8f;
float buttonHeight = height-2*borderSize;
float width = buttonHeight*180/95;
if(GUI.Button(new Rect(Screen.width/2f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight), "back")){
guiState = GUIState.GOODS;
}
GUI.DrawTexture(new Rect(Screen.width/2f-width/2f,Screen.height*7f/8f+borderSize,width,buttonHeight),tBack);
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Internal.Fakeables;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public sealed class LogManager
{
private static readonly LogFactory factory = new LogFactory();
private static IAppDomain currentAppDomain;
private static ICollection<Assembly> _hiddenAssemblies;
private static readonly object lockObject = new object();
/// <summary>
/// Delegate used to set/get the culture in use.
/// </summary>
[Obsolete]
public delegate CultureInfo GetCultureInfo();
#if !SILVERLIGHT && !MONO
/// <summary>
/// Initializes static members of the LogManager class.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline", Justification = "Significant logic in .cctor()")]
static LogManager()
{
SetupTerminationEvents();
}
#endif
/// <summary>
/// Prevents a default instance of the LogManager class from being created.
/// </summary>
private LogManager()
{
}
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add { factory.ConfigurationChanged += value; }
remove { factory.ConfigurationChanged -= value; }
}
#if !SILVERLIGHT
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add { factory.ConfigurationReloaded += value; }
remove { factory.ConfigurationReloaded -= value; }
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get { return factory.ThrowExceptions; }
set { factory.ThrowExceptions = value; }
}
internal static IAppDomain CurrentAppDomain
{
get { return currentAppDomain ?? (currentAppDomain = AppDomainWrapper.CurrentDomain); }
set
{
#if !SILVERLIGHT && !MONO
currentAppDomain.DomainUnload -= TurnOffLogging;
currentAppDomain.ProcessExit -= TurnOffLogging;
#endif
currentAppDomain = value;
}
}
/// <summary>
/// Gets or sets the current logging configuration.
/// <see cref="LogFactory.Configuration" />
/// </summary>
public static LoggingConfiguration Configuration
{
get { return factory.Configuration; }
set { factory.Configuration = value; }
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get { return factory.GlobalThreshold; }
set { factory.GlobalThreshold = value; }
}
/// <summary>
/// Gets or sets the default culture to use.
/// </summary>
[Obsolete("Use Configuration.DefaultCultureInfo property instead")]
public static GetCultureInfo DefaultCultureInfo
{
get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; }
set { throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo."); }
}
/// <summary>
/// Gets the logger with the name of the current class.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
return factory.GetLogger(GetClassFullName());
}
internal static bool IsHiddenAssembly(Assembly assembly)
{
return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly);
}
/// <summary>
/// Adds the given assembly which will be skipped
/// when NLog is trying to find the calling method on stack trace.
/// </summary>
/// <param name="assembly">The assembly to skip.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AddHiddenAssembly(Assembly assembly)
{
lock (lockObject)
{
if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly))
return;
_hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>())
{
assembly
};
}
}
/// <summary>
/// Gets a custom logger with the name of the current class. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
return factory.GetLogger(GetClassFullName(), loggerType);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
[CLSCompliant(false)]
public static Logger CreateNullLogger()
{
return factory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
[CLSCompliant(false)]
public static Logger GetLogger(string name)
{
return factory.GetLogger(name);
}
/// <summary>
/// Gets the specified named custom logger. Use <paramref name="loggerType"/> to pass the type of the needed Logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. The class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
/// <remarks>The generic way for this method is <see cref="LogFactory{loggerType}.GetLogger(string)"/></remarks>
[CLSCompliant(false)]
public static Logger GetLogger(string name, Type loggerType)
{
return factory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
factory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
public static void Flush()
{
factory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
factory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
factory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
factory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
factory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
factory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that implements IDisposable whose Dispose() method reenables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return factory.SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
factory.ResumeLogging();
}
/// <summary>
/// Checks if logging is currently enabled.
/// </summary>
/// <returns><see langword="true" /> if logging is currently enabled, <see langword="false"/>
/// otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return factory.IsLoggingEnabled();
}
/// <summary>
/// Dispose all targets, and shutdown logging.
/// </summary>
public static void Shutdown()
{
foreach (var target in Configuration.AllTargets)
{
target.Dispose();
}
}
#if !SILVERLIGHT && !MONO
private static void SetupTerminationEvents()
{
try
{
CurrentAppDomain.ProcessExit += TurnOffLogging;
CurrentAppDomain.DomainUnload += TurnOffLogging;
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Error setting up termination events: {0}", exception);
}
}
#endif
/// <summary>
/// Gets the fully qualified name of the class invoking the LogManager, including the
/// namespace but not the assembly.
/// </summary>
private static string GetClassFullName()
{
string className;
Type declaringType;
int framesToSkip = 2;
do
{
#if SILVERLIGHT
StackFrame frame = new StackTrace().GetFrame(framesToSkip);
#else
StackFrame frame = new StackFrame(framesToSkip, false);
#endif
MethodBase method = frame.GetMethod();
declaringType = method.DeclaringType;
if (declaringType == null)
{
className = method.Name;
break;
}
framesToSkip++;
className = declaringType.FullName;
} while (declaringType.Module.Name.Equals("mscorlib.dll", StringComparison.OrdinalIgnoreCase));
return className;
}
private static void TurnOffLogging(object sender, EventArgs args)
{
// Reset logging configuration to null; this causes old configuration (if any) to be
// closed.
InternalLogger.Info("Shutting down logging...");
Configuration = null;
InternalLogger.Info("Logger has been shut down.");
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// NOTE: A vast majority of this code was copied from BCL in
// ndp\clr\src\BCL\System\Security\AccessControl\RegistrySecurity.cs.
// Namespace: System.Security.AccessControl
//
/*============================================================
**
**
**
** Purpose: Managed ACL wrapper for registry keys.
**
**
===========================================================*/
using System;
using System.Security.Permissions;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.IO;
using System.Security.AccessControl;
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.PowerShell.Commands.Internal
{
/// <summary>
/// <para>Represents a set of access rights allowed or denied for a user or group. This class cannot be inherited.</para>
/// </summary>
// Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline.
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
public sealed class TransactedRegistryAccessRule : AccessRule
{
// Constructor for creating access rules for registry objects
/// <summary>
/// <para>Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to,
/// the access rights, and whether the specified access rights are allowed or denied.</para>
/// <param name="identity">The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as
/// NTAccount that can be converted to type SecurityIdentifier.</param>
/// <param name="registryRights">A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied.</param>
/// <param name="type">One of the AccessControlType values indicating whether the rights are allowed or denied.</param>
/// </summary>
internal TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type)
: this(identity, (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
/// <summary>
/// <para>Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to,
/// the access rights, and whether the specified access rights are allowed or denied.</para>
/// <param name="identity">The name of the user or group the rule applies to.</param>
/// <param name="registryRights">A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied.</param>
/// <param name="type">One of the AccessControlType values indicating whether the rights are allowed or denied.</param>
/// </summary>
internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, AccessControlType type)
: this(new NTAccount(identity), (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type)
{
}
/// <summary>
/// <para>Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to,
/// the access rights, and whether the specified access rights are allowed or denied.</para>
/// <param name="identity">The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as
/// NTAccount that can be converted to type SecurityIdentifier.</param>
/// <param name="registryRights">A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied.</param>
/// <param name="inheritanceFlags">A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects.</param>
/// <param name="propagationFlags">A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects.</param>
/// <param name="type">One of the AccessControlType values indicating whether the rights are allowed or denied.</param>
/// </summary>
public TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
: this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, type)
{
}
/// <summary>
/// <para>Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to,
/// the access rights, and whether the specified access rights are allowed or denied.</para>
/// <param name="identity">The name of the user or group the rule applies to.</param>
/// <param name="registryRights">A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied.</param>
/// <param name="inheritanceFlags">A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects.</param>
/// <param name="propagationFlags">A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects.</param>
/// <param name="type">One of the AccessControlType values indicating whether the rights are allowed or denied.</param>
/// </summary>
internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
: this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, type)
{
}
//
// Internal constructor to be called by public constructors
// and the access rule factory methods of {File|Folder}Security
//
internal TransactedRegistryAccessRule(
IdentityReference identity,
int accessMask,
bool isInherited,
InheritanceFlags inheritanceFlags,
PropagationFlags propagationFlags,
AccessControlType type)
: base(
identity,
accessMask,
isInherited,
inheritanceFlags,
propagationFlags,
type)
{
}
/// <summary>
/// <para>Gets the rights allowed or denied by the access rule.</para>
/// </summary>
public RegistryRights RegistryRights
{
get { return (RegistryRights)base.AccessMask; }
}
}
/// <summary>
/// <para>Represents a set of access rights to be audited for a user or group. This class cannot be inherited.</para>
/// </summary>
// Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline.
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
public sealed class TransactedRegistryAuditRule : AuditRule
{
/// <summary>
/// <para>Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to
/// audit, whether to take inheritance into account, and whether to audit success, failure, or both.</para>
/// <param name="identity">The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as
/// NTAccount that can be converted to type SecurityIdentifier.</param>
/// <param name="registryRights">A bitwise combination of RegistryRights values specifying the kinds of access to audit.</param>
/// <param name="inheritanceFlags">A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key.</param>
/// <param name="propagationFlags">A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key.</param>
/// <param name="flags">A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both.</param>
/// </summary>
internal TransactedRegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, flags)
{
}
/// <summary>
/// <para>Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to
/// audit, whether to take inheritance into account, and whether to audit success, failure, or both.</para>
/// <param name="identity">The name of the user or group the rule applies to.</param>
/// <param name="registryRights">A bitwise combination of RegistryRights values specifying the kinds of access to audit.</param>
/// <param name="inheritanceFlags">A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key.</param>
/// <param name="propagationFlags">A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key.</param>
/// <param name="flags">A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both.</param>
/// </summary>
internal TransactedRegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, flags)
{
}
internal TransactedRegistryAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
: base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags)
{
}
/// <summary>
/// <para>Gets the access rights affected by the audit rule.</para>
/// </summary>
public RegistryRights RegistryRights
{
get { return (RegistryRights)base.AccessMask; }
}
}
/// <summary>
/// <para>Represents the Windows access control security for a registry key. This class cannot be inherited.
/// This class is specifically to be used with TransactedRegistryKey.</para>
/// </summary>
// Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline.
[SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")]
public sealed class TransactedRegistrySecurity : NativeObjectSecurity
{
private const string resBaseName = "RegistryProviderStrings";
/// <summary>
/// <para>Initializes a new instance of the TransactedRegistrySecurity class with default values.</para>
/// </summary>
public TransactedRegistrySecurity()
: base(true, ResourceType.RegistryKey)
{
}
/*
// The name of registry key must start with a predefined string,
// like CLASSES_ROOT, CURRENT_USER, MACHINE, and USERS. See
// MSDN's help for SetNamedSecurityInfo for details.
internal TransactedRegistrySecurity(string name, AccessControlSections includeSections)
: base(true, ResourceType.RegistryKey, HKeyNameToWindowsName(name), includeSections)
{
new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand();
}
*/
// Suppressed because the passed name and hkey won't change.
[SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
internal TransactedRegistrySecurity(SafeRegistryHandle hKey, string name, AccessControlSections includeSections)
: base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null)
{
new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand();
}
private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context)
{
System.Exception exception = null;
switch (errorCode)
{
case Win32Native.ERROR_FILE_NOT_FOUND:
exception = new IOException(RegistryProviderStrings.Arg_RegKeyNotFound);
break;
case Win32Native.ERROR_INVALID_NAME:
exception = new ArgumentException(RegistryProviderStrings.Arg_RegInvalidKeyName);
break;
case Win32Native.ERROR_INVALID_HANDLE:
exception = new ArgumentException(RegistryProviderStrings.AccessControl_InvalidHandle);
break;
default:
break;
}
return exception;
}
/// <summary>
/// <para>Creates a new access control rule for the specified user, with the specified access rights, access control, and flags.</para>
/// <param name="identityReference">An IdentityReference that identifies the user or group the rule applies to.</param>
/// <param name="accessMask">A bitwise combination of RegistryRights values specifying the access rights to allow or deny, cast to an integer.</param>
/// <param name="isInherited">A Boolean value specifying whether the rule is inherited.</param>
/// <param name="inheritanceFlags">A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys.</param>
/// <param name="propagationFlags">A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None.</param>
/// <param name="type">One of the AccessControlType values specifying whether the rights are allowed or denied.</param>
/// <returns>A TransactedRegistryAccessRule object representing the specified rights for the specified user.</returns>
/// </summary>
public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type)
{
return new TransactedRegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type);
}
/// <summary>
/// <para>Creates a new audit rule, specifying the user the rule applies to, the access rights to audit, the inheritance and propagation of the
/// rule, and the outcome that triggers the rule.</para>
/// <param name="identityReference">An IdentityReference that identifies the user or group the rule applies to.</param>
/// <param name="accessMask">A bitwise combination of RegistryRights values specifying the access rights to audit, cast to an integer.</param>
/// <param name="isInherited">A Boolean value specifying whether the rule is inherited.</param>
/// <param name="inheritanceFlags">A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys.</param>
/// <param name="propagationFlags">A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None.</param>
/// <param name="flags">A bitwise combination of AuditFlags values specifying whether to audit successful access, failed access, or both.</param>
/// <returns>A TransactedRegistryAuditRule object representing the specified audit rule for the specified user, with the specified flags.
/// The return type of the method is the base class, AuditRule, but the return value can be cast safely to the derived class.</returns>
/// </summary>
public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags)
{
return new TransactedRegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags);
}
internal AccessControlSections GetAccessControlSectionsFromChanges()
{
AccessControlSections persistRules = AccessControlSections.None;
if (AccessRulesModified)
persistRules = AccessControlSections.Access;
if (AuditRulesModified)
persistRules |= AccessControlSections.Audit;
if (OwnerModified)
persistRules |= AccessControlSections.Owner;
if (GroupModified)
persistRules |= AccessControlSections.Group;
return persistRules;
}
// Suppressed because the passed keyName won't change.
[SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")]
internal void Persist(SafeRegistryHandle hKey, string keyName)
{
new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.Change, keyName).Demand();
WriteLock();
try
{
AccessControlSections persistRules = GetAccessControlSectionsFromChanges();
if (persistRules == AccessControlSections.None)
return; // Don't need to persist anything.
base.Persist(hKey, persistRules);
OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false;
}
finally
{
WriteUnlock();
}
}
/// <summary>
/// <para>Searches for a matching access control with which the new rule can be merged. If none are found, adds the new rule.</para>
/// <param name="rule">The access control rule to add.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void AddAccessRule(TransactedRegistryAccessRule rule)
{
base.AddAccessRule(rule);
}
/// <summary>
/// <para>Removes all access control rules with the same user and AccessControlType (allow or deny) as the specified rule, and then adds the specified rule.</para>
/// <param name="rule">The TransactedRegistryAccessRule to add. The user and AccessControlType of this rule determine the rules to remove before this rule is added.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void SetAccessRule(TransactedRegistryAccessRule rule)
{
base.SetAccessRule(rule);
}
/// <summary>
/// <para>Removes all access control rules with the same user as the specified rule, regardless of AccessControlType, and then adds the specified rule.</para>
/// <param name="rule">The TransactedRegistryAccessRule to add. The user specified by this rule determines the rules to remove before this rule is added.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void ResetAccessRule(TransactedRegistryAccessRule rule)
{
base.ResetAccessRule(rule);
}
/// <summary>
/// <para>Searches for an access control rule with the same user and AccessControlType (allow or deny) as the specified access rule, and with compatible
/// inheritance and propagation flags; if such a rule is found, the rights contained in the specified access rule are removed from it.</para>
/// <param name="rule">A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for, and a set of inheritance
/// and propagation flags that a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public bool RemoveAccessRule(TransactedRegistryAccessRule rule)
{
return base.RemoveAccessRule(rule);
}
/// <summary>
/// <para>Searches for all access control rules with the same user and AccessControlType (allow or deny) as the specified rule and, if found, removes them.</para>
/// <param name="rule">A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for. Any rights, inheritance flags, or
/// propagation flags specified by this rule are ignored.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void RemoveAccessRuleAll(TransactedRegistryAccessRule rule)
{
base.RemoveAccessRuleAll(rule);
}
/// <summary>
/// <para>Searches for an access control rule that exactly matches the specified rule and, if found, removes it.</para>
/// <param name="rule">The TransactedRegistryAccessRule to remove.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void RemoveAccessRuleSpecific(TransactedRegistryAccessRule rule)
{
base.RemoveAccessRuleSpecific(rule);
}
/// <summary>
/// <para>Searches for an audit rule with which the new rule can be merged. If none are found, adds the new rule.</para>
/// <param name="rule">The audit rule to add. The user specified by this rule determines the search.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void AddAuditRule(TransactedRegistryAuditRule rule)
{
base.AddAuditRule(rule);
}
/// <summary>
/// <para>Removes all audit rules with the same user as the specified rule, regardless of the AuditFlags value, and then adds the specified rule.</para>
/// <param name="rule">The TransactedRegistryAuditRule to add. The user specified by this rule determines the rules to remove before this rule is added.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void SetAuditRule(TransactedRegistryAuditRule rule)
{
base.SetAuditRule(rule);
}
/// <summary>
/// <para>Searches for an audit control rule with the same user as the specified rule, and with compatible inheritance and propagation flags;
/// if a compatible rule is found, the rights contained in the specified rule are removed from it.</para>
/// <param name="rule">A TransactedRegistryAuditRule that specifies the user to search for, and a set of inheritance and propagation flags that
/// a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public bool RemoveAuditRule(TransactedRegistryAuditRule rule)
{
return base.RemoveAuditRule(rule);
}
/// <summary>
/// <para>Searches for all audit rules with the same user as the specified rule and, if found, removes them.</para>
/// <param name="rule">A TransactedRegistryAuditRule that specifies the user to search for. Any rights, inheritance
/// flags, or propagation flags specified by this rule are ignored.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void RemoveAuditRuleAll(TransactedRegistryAuditRule rule)
{
base.RemoveAuditRuleAll(rule);
}
/// <summary>
/// <para>Searches for an audit rule that exactly matches the specified rule and, if found, removes it.</para>
/// <param name="rule">The TransactedRegistryAuditRule to be removed.</param>
/// </summary>
// Suppressed because we want to ensure TransactedRegistry* objects.
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")]
public void RemoveAuditRuleSpecific(TransactedRegistryAuditRule rule)
{
base.RemoveAuditRuleSpecific(rule);
}
/// <summary>
/// <para>Gets the enumeration type that the TransactedRegistrySecurity class uses to represent access rights.</para>
/// <returns>A Type object representing the RegistryRights enumeration.</returns>
/// </summary>
public override Type AccessRightType
{
get { return typeof(RegistryRights); }
}
/// <summary>
/// <para>Gets the type that the TransactedRegistrySecurity class uses to represent access rules.</para>
/// <returns>A Type object representing the TransactedRegistryAccessRule class.</returns>
/// </summary>
public override Type AccessRuleType
{
get { return typeof(TransactedRegistryAccessRule); }
}
/// <summary>
/// <para>Gets the type that the TransactedRegistrySecurity class uses to represent audit rules.</para>
/// <returns>A Type object representing the TransactedRegistryAuditRule class.</returns>
/// </summary>
public override Type AuditRuleType
{
get { return typeof(TransactedRegistryAuditRule); }
}
}
}
| |
///////////////////////////////////////////////////////////////////////////////////////////////
//
// This File is Part of the CallButler Open Source PBX (http://www.codeplex.com/callbutler
//
// Copyright (c) 2005-2008, Jim Heising
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// * Neither the name of Jim Heising nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
///////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Xml;
namespace WOSI.Utilities
{
public class StringUtils
{
public static string GetProperSortText(SortOrder order)
{
string text = String.Empty;
switch (order)
{
case (SortOrder.Ascending):
text += " ASC";
break;
case (SortOrder.Descending):
text += " DESC";
break;
case (SortOrder.None):
text = "";
break;
}
return text;
}
public static bool IsWellFormedXml(string inputString)
{
XmlTextReader xmlReader = new XmlTextReader(new System.IO.StringReader(inputString));
try
{
while(xmlReader.Read())
{
}
xmlReader.Close();
return true;
}
catch
{
}
xmlReader.Close();
return false;
}
public static string XmlEncodeString(string inputString)
{
XmlDocument xmlDoc = new XmlDocument();
XmlElement xmlElement = xmlDoc.CreateElement("Str");
xmlElement.InnerText = inputString;
return xmlElement.InnerXml;
}
public static string[] SplitQuotedString(string stringToSplit, char token)
{
List<string> valueList = new List<string>();
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
char quoteChar = '\0';
foreach (Char character in stringToSplit)
{
if (character == '"' || character == '<')
{
inQuotes = !inQuotes;
quoteChar = character;
}
else if (inQuotes && character == '>' && quoteChar == '<')
{
inQuotes = false;
}
if (!inQuotes && character == token)
{
valueList.Add(sb.ToString());
sb = new StringBuilder();
}
else
sb.Append(character);
}
if (sb.Length > 0)
valueList.Add(sb.ToString());
return valueList.ToArray();
}
public static string[] SplitQuotedString(string stringToSplit, char startQuote, char endQuote, char token)
{
List<string> valueList = new List<string>();
StringBuilder sb = new StringBuilder();
bool inQuotes = false;
char quoteChar = '\0';
foreach (Char character in stringToSplit)
{
if (character == startQuote)
{
inQuotes = !inQuotes;
quoteChar = character;
}
else if (inQuotes && character == endQuote && quoteChar == startQuote)
{
inQuotes = false;
}
if (!inQuotes && character == token)
{
valueList.Add(sb.ToString());
sb = new StringBuilder();
}
else
sb.Append(character);
}
if (sb.Length > 0)
valueList.Add(sb.ToString());
return valueList.ToArray();
}
public static string GetAreaCode(string inputString)
{
//string outputNumber = "";
string numberString = "";
// Get number count
int numberCount = 0;
foreach (Char numberChar in inputString)
{
if (Char.IsNumber(numberChar))
{
numberCount++;
numberString += numberChar.ToString();
}
}
if (Regex.IsMatch(inputString, @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)"))
{
return "";
}
else if (numberCount == 7)
{
return "";
}
else if (numberCount == 10)
{
return numberString.Substring(0, 3);
}
else if (numberCount == 11)
{
return numberString.Substring(1, 3);
}
return "";
}
public static string FormatPhoneNumber(string inputString)
{
string outputNumber = "";
string numberString = "";
// Remove any spaces
//inputString = inputString.Replace(" ", "");
// Get number count
int numberCount = 0;
foreach (Char numberChar in inputString)
{
if (Char.IsNumber(numberChar))
{
numberCount++;
numberString += numberChar.ToString();
}
}
if (Regex.IsMatch(inputString, @"(?<First>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Second>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Third>2[0-4]\d|25[0-5]|[01]?\d\d?)\.(?<Fourth>2[0-4]\d|25[0-5]|[01]?\d\d?)"))
{
outputNumber = inputString;
}
else if (numberCount == 7)
{
outputNumber = numberString.Substring(0, 3) + "-" + numberString.Substring(3, 4);
}
else if (numberCount == 10)
{
outputNumber = "(" + numberString.Substring(0, 3) + ") " + numberString.Substring(3, 3) + "-" + numberString.Substring(6, 4);
}
else if (numberCount == 11)
{
outputNumber = numberString.Substring(0, 1) + " (" + numberString.Substring(1, 3) + ") " + numberString.Substring(4, 3) + "-" + numberString.Substring(7, 4);
}
else
outputNumber = inputString;
return outputNumber;
}
public static string CleanTelephoneNumber(string inputString)
{
return Regex.Replace(inputString, @"[\(\)\-\.\s]", "");
}
public static string ConvertStringToPhoneNumberString(string inputString)
{
string outputStr = "";
foreach (char strChar in inputString.ToUpper())
{
switch (strChar)
{
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
outputStr += strChar.ToString();
break;
case 'A':
case 'B':
case 'C':
outputStr += '2';
break;
case 'D':
case 'E':
case 'F':
outputStr += '3';
break;
case 'G':
case 'H':
case 'I':
outputStr += '4';
break;
case 'J':
case 'K':
case 'L':
outputStr += '5';
break;
case 'M':
case 'N':
case 'O':
outputStr += '6';
break;
case 'P':
case 'Q':
case 'R':
case 'S':
outputStr += '7';
break;
case 'T':
case 'U':
case 'V':
outputStr += '8';
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
outputStr += '9';
break;
case '0':
outputStr += '0';
break;
case '*':
outputStr += '*';
break;
case '#':
outputStr += '#';
break;
case '+':
outputStr += '+';
break;
}
}
return outputStr;
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Cont
{
using System;
using NPOI.HSSF.Record;
using NPOI.Util;
/**
* An augmented {@link LittleEndianOutput} used for serialization of {@link ContinuableRecord}s.
* This class keeps track of how much remaining space is available in the current BIFF record and
* can start new {@link ContinueRecord}s as required.
*
* @author Josh Micich
*/
public class ContinuableRecordOutput : ILittleEndianOutput
{
private ILittleEndianOutput _out;
private UnknownLengthRecordOutput _ulrOutput;
private int _totalPreviousRecordsSize;
internal ContinuableRecordOutput(ILittleEndianOutput out1, int sid)
{
_ulrOutput = new UnknownLengthRecordOutput(out1, sid);
_out = out1;
_totalPreviousRecordsSize = 0;
}
public static ContinuableRecordOutput CreateForCountingOnly()
{
return new ContinuableRecordOutput(NOPOutput, -777); // fake sid
}
/**
* @return total number of bytes written so far (including all BIFF headers)
*/
public int TotalSize
{
get
{
return _totalPreviousRecordsSize + _ulrOutput.TotalSize;
}
}
/**
* Terminates the last record (also updates its 'ushort size' field)
*/
public void Terminate()
{
_ulrOutput.Terminate();
}
/**
* @return number of remaining bytes of space in current record
*/
public int AvailableSpace
{
get
{
return _ulrOutput.AvailableSpace;
}
}
/**
* Terminates the current record and starts a new {@link ContinueRecord} (regardless
* of how much space is still available in the current record).
*/
public void WriteContinue()
{
_ulrOutput.Terminate();
_totalPreviousRecordsSize += _ulrOutput.TotalSize;
_ulrOutput = new UnknownLengthRecordOutput(_out, ContinueRecord.sid);
}
public void WriteContinueIfRequired(int requiredContinuousSize)
{
if (_ulrOutput.AvailableSpace < requiredContinuousSize)
{
WriteContinue();
}
}
/**
* Writes the 'optionFlags' byte and encoded character data of a unicode string. This includes:
* <ul>
* <li>byte optionFlags</li>
* <li>encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)</li>
* </ul>
*
* Notes:
* <ul>
* <li>The value of the 'is16bitEncoded' flag is determined by the actual character data
* of <c>text</c></li>
* <li>The string options flag is never separated (by a {@link ContinueRecord}) from the
* first chunk of character data it refers to.</li>
* <li>The 'ushort Length' field is assumed to have been explicitly written earlier. Hence,
* there may be an intervening {@link ContinueRecord}</li>
* </ul>
*/
public void WriteStringData(String text)
{
bool is16bitEncoded = StringUtil.HasMultibyte(text);
// calculate total size of the header and first encoded char
int keepTogetherSize = 1 + 1; // ushort len, at least one character byte
int optionFlags = 0x00;
if (is16bitEncoded)
{
optionFlags |= 0x01;
keepTogetherSize += 1; // one extra byte for first char
}
WriteContinueIfRequired(keepTogetherSize);
WriteByte(optionFlags);
WriteCharacterData(text, is16bitEncoded);
}
/**
* Writes a unicode string complete with header and character data. This includes:
* <ul>
* <li>ushort Length</li>
* <li>byte optionFlags</li>
* <li>ushort numberOfRichTextRuns (optional)</li>
* <li>ushort extendedDataSize (optional)</li>
* <li>encoded character data (in "ISO-8859-1" or "UTF-16LE" encoding)</li>
* </ul>
*
* The following bits of the 'optionFlags' byte will be set as appropriate:
* <table border='1'>
* <tr><th>Mask</th><th>Description</th></tr>
* <tr><td>0x01</td><td>is16bitEncoded</td></tr>
* <tr><td>0x04</td><td>hasExtendedData</td></tr>
* <tr><td>0x08</td><td>isRichText</td></tr>
* </table>
* Notes:
* <ul>
* <li>The value of the 'is16bitEncoded' flag is determined by the actual character data
* of <c>text</c></li>
* <li>The string header fields are never separated (by a {@link ContinueRecord}) from the
* first chunk of character data (i.e. the first character is always encoded in the same
* record as the string header).</li>
* </ul>
*/
public void WriteString(String text, int numberOfRichTextRuns, int extendedDataSize)
{
bool is16bitEncoded = StringUtil.HasMultibyte(text);
// calculate total size of the header and first encoded char
int keepTogetherSize = 2 + 1 + 1; // ushort len, byte optionFlags, at least one character byte
int optionFlags = 0x00;
if (is16bitEncoded)
{
optionFlags |= 0x01;
keepTogetherSize += 1; // one extra byte for first char
}
if (numberOfRichTextRuns > 0)
{
optionFlags |= 0x08;
keepTogetherSize += 2;
}
if (extendedDataSize > 0)
{
optionFlags |= 0x04;
keepTogetherSize += 4;
}
WriteContinueIfRequired(keepTogetherSize);
WriteShort(text.Length);
WriteByte(optionFlags);
if (numberOfRichTextRuns > 0)
{
WriteShort(numberOfRichTextRuns);
}
if (extendedDataSize > 0)
{
WriteInt(extendedDataSize);
}
WriteCharacterData(text, is16bitEncoded);
}
private void WriteCharacterData(String text, bool is16bitEncoded)
{
int nChars = text.Length;
int i = 0;
if (is16bitEncoded)
{
while (true)
{
int nWritableChars = Math.Min(nChars - i, _ulrOutput.AvailableSpace / 2);
for (; nWritableChars > 0; nWritableChars--)
{
_ulrOutput.WriteShort(text[i++]);
}
if (i >= nChars)
{
break;
}
WriteContinue();
WriteByte(0x01);
}
}
else
{
while (true)
{
int nWritableChars = Math.Min(nChars - i, _ulrOutput.AvailableSpace / 1);
for (; nWritableChars > 0; nWritableChars--)
{
_ulrOutput.WriteByte(text[i++]);
}
if (i >= nChars)
{
break;
}
WriteContinue();
WriteByte(0x00);
}
}
}
public void Write(byte[] b)
{
WriteContinueIfRequired(b.Length);
_ulrOutput.Write(b);
}
public void Write(byte[] b, int offset, int len)
{
//WriteContinueIfRequired(len);
//_ulrOutput.Write(b, offset, len);
int i = 0;
while (true)
{
int nWritableChars = Math.Min(len - i, _ulrOutput.AvailableSpace / 1);
for (; nWritableChars > 0; nWritableChars--)
{
_ulrOutput.WriteByte(b[offset + i++]);
}
if (i >= len)
{
break;
}
WriteContinue();
}
}
public void WriteByte(int v)
{
WriteContinueIfRequired(1);
_ulrOutput.WriteByte(v);
}
public void WriteDouble(double v)
{
WriteContinueIfRequired(8);
_ulrOutput.WriteDouble(v);
}
public void WriteInt(int v)
{
WriteContinueIfRequired(4);
_ulrOutput.WriteInt(v);
}
public void WriteLong(long v)
{
WriteContinueIfRequired(8);
_ulrOutput.WriteLong(v);
}
public void WriteShort(int v)
{
WriteContinueIfRequired(2);
_ulrOutput.WriteShort(v);
}
///**
// * Allows optimised usage of {@link ContinuableRecordOutput} for sizing purposes only.
// */
private static ILittleEndianOutput NOPOutput = new DelayableLittleEndianOutput1();
class DelayableLittleEndianOutput1 : IDelayableLittleEndianOutput
{
public ILittleEndianOutput CreateDelayedOutput(int size)
{
return this;
}
public void Write(byte[] b)
{
// does nothing
}
public void Write(byte[] b, int offset, int len)
{
// does nothing
}
public void WriteByte(int v)
{
// does nothing
}
public void WriteDouble(double v)
{
// does nothing
}
public void WriteInt(int v)
{
// does nothing
}
public void WriteLong(long v)
{
// does nothing
}
public void WriteShort(int v)
{
// does nothing
}
}
}
}
| |
// 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.Globalization;
using System.Runtime.InteropServices;
#if !FEATURE_SLJ_PROJECTION_COMPAT
#pragma warning disable 436 // Redefining types from Windows.Foundation
#endif // !FEATURE_SLJ_PROJECTION_COMPAT
#if FEATURE_SLJ_PROJECTION_COMPAT
namespace System.Windows
#else // !FEATURE_SLJ_PROJECTION_COMPAT
namespace Windows.Foundation
#endif // FEATURE_SLJ_PROJECTION_COMPAT
{
//
// Rect is the managed projection of Windows.Foundation.Rect. Any changes to the layout
// of this type must be exactly mirrored on the native WinRT side as well.
//
// Note that this type is owned by the Jupiter team. Please contact them before making any
// changes here.
//
[StructLayout(LayoutKind.Sequential)]
public struct Rect : IFormattable
{
private float _x;
private float _y;
private float _width;
private float _height;
private const double EmptyX = Double.PositiveInfinity;
private const double EmptyY = Double.PositiveInfinity;
private const double EmptyWidth = Double.NegativeInfinity;
private const double EmptyHeight = Double.NegativeInfinity;
private readonly static Rect s_empty = CreateEmptyRect();
public Rect(double x,
double y,
double width,
double height)
{
if (width < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(width));
if (height < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(height));
_x = (float)x;
_y = (float)y;
_width = (float)width;
_height = (float)height;
}
public Rect(Point point1,
Point point2)
{
_x = (float)Math.Min(point1.X, point2.X);
_y = (float)Math.Min(point1.Y, point2.Y);
_width = (float)Math.Max(Math.Max(point1.X, point2.X) - _x, 0);
_height = (float)Math.Max(Math.Max(point1.Y, point2.Y) - _y, 0);
}
public Rect(Point location, Size size)
{
if (size.IsEmpty)
{
this = s_empty;
}
else
{
_x = (float)location.X;
_y = (float)location.Y;
_width = (float)size.Width;
_height = (float)size.Height;
}
}
internal static Rect Create(double x,
double y,
double width,
double height)
{
if (x == EmptyX && y == EmptyY && width == EmptyWidth && height == EmptyHeight)
{
return Rect.Empty;
}
else
{
return new Rect(x, y, width, height);
}
}
public double X
{
get { return _x; }
set { _x = (float)value; }
}
public double Y
{
get { return _y; }
set { _y = (float)value; }
}
public double Width
{
get { return _width; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(Width));
_width = (float)value;
}
}
public double Height
{
get { return _height; }
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(SR.ArgumentOutOfRange_NeedNonNegNum, nameof(Height));
_height = (float)value;
}
}
public double Left
{
get { return _x; }
}
public double Top
{
get { return _y; }
}
public double Right
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _x + _width;
}
}
public double Bottom
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _y + _height;
}
}
public static Rect Empty
{
get { return s_empty; }
}
public bool IsEmpty
{
get { return _width < 0; }
}
public bool Contains(Point point)
{
return ContainsInternal(point.X, point.Y);
}
public void Intersect(Rect rect)
{
if (!this.IntersectsWith(rect))
{
this = s_empty;
}
else
{
double left = Math.Max(X, rect.X);
double top = Math.Max(Y, rect.Y);
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
Width = Math.Max(Math.Min(X + Width, rect.X + rect.Width) - left, 0);
Height = Math.Max(Math.Min(Y + Height, rect.Y + rect.Height) - top, 0);
X = left;
Y = top;
}
}
public void Union(Rect rect)
{
if (IsEmpty)
{
this = rect;
}
else if (!rect.IsEmpty)
{
double left = Math.Min(Left, rect.Left);
double top = Math.Min(Top, rect.Top);
// We need this check so that the math does not result in NaN
if ((rect.Width == Double.PositiveInfinity) || (Width == Double.PositiveInfinity))
{
Width = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxRight = Math.Max(Right, rect.Right);
Width = Math.Max(maxRight - left, 0);
}
// We need this check so that the math does not result in NaN
if ((rect.Height == Double.PositiveInfinity) || (Height == Double.PositiveInfinity))
{
Height = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxBottom = Math.Max(Bottom, rect.Bottom);
Height = Math.Max(maxBottom - top, 0);
}
X = left;
Y = top;
}
}
public void Union(Point point)
{
Union(new Rect(point, point));
}
private bool ContainsInternal(double x, double y)
{
return ((x >= X) && (x - Width <= X) &&
(y >= Y) && (y - Height <= Y));
}
internal bool IntersectsWith(Rect rect)
{
if (Width < 0 || rect.Width < 0)
{
return false;
}
return (rect.X <= X + Width) &&
(rect.X + rect.Width >= X) &&
(rect.Y <= Y + Height) &&
(rect.Y + rect.Height >= Y);
}
private static Rect CreateEmptyRect()
{
Rect rect = new Rect();
// TODO: for consistency with width/height we should change these
// to assign directly to the backing fields.
rect.X = EmptyX;
rect.Y = EmptyY;
// the width and height properties prevent assignment of
// negative numbers so assign directly to the backing fields.
rect._width = (float)EmptyWidth;
rect._height = (float)EmptyHeight;
return rect;
}
public override string ToString()
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, null /* format provider */);
}
public string ToString(IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(null /* format string */, provider);
}
string IFormattable.ToString(string format, IFormatProvider provider)
{
// Delegate to the internal method which implements all ToString calls.
return ConvertToString(format, provider);
}
internal string ConvertToString(string format, IFormatProvider provider)
{
if (IsEmpty)
{
return SR.DirectUI_Empty;
}
// Helper to get the numeric list separator for a given culture.
char separator = TokenizerHelper.GetNumericListSeparator(provider);
return String.Format(provider,
"{1:" + format + "}{0}{2:" + format + "}{0}{3:" + format + "}{0}{4:" + format + "}",
separator,
_x,
_y,
_width,
_height);
}
public bool Equals(Rect value)
{
return (this == value);
}
public static bool operator ==(Rect rect1, Rect rect2)
{
return rect1.X == rect2.X &&
rect1.Y == rect2.Y &&
rect1.Width == rect2.Width &&
rect1.Height == rect2.Height;
}
public static bool operator !=(Rect rect1, Rect rect2)
{
return !(rect1 == rect2);
}
public override bool Equals(object o)
{
return o is Rect && this == (Rect)o;
}
public override int GetHashCode()
{
// Perform field-by-field XOR of HashCodes
return X.GetHashCode() ^
Y.GetHashCode() ^
Width.GetHashCode() ^
Height.GetHashCode();
}
}
}
#if !FEATURE_SLJ_PROJECTION_COMPAT
#pragma warning restore 436
#endif // !FEATURE_SLJ_PROJECTION_COMPAT
| |
// ***********************************************************************
// Copyright (c) 2007-2013 Charlie Poole, Rob Prouse
//
// 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.Globalization;
using NUnit.Framework.Internal;
using NUnit.TestUtilities.Comparers;
namespace NUnit.Framework.Constraints
{
[TestFixture]
public class EqualConstraintTests : ConstraintTestBase
{
[SetUp]
public void SetUp()
{
TheConstraint = new EqualConstraint(4);
ExpectedDescription = "4";
StringRepresentation = "<equal 4>";
}
static object[] SuccessData = new object[] {4, 4.0f, 4.0d, 4.0000m};
static object[] FailureData = new object[]
{
new TestCaseData(5, "5"),
new TestCaseData(null, "null"),
new TestCaseData("Hello", "\"Hello\""),
new TestCaseData(double.NaN, double.NaN.ToString()),
new TestCaseData(double.PositiveInfinity, double.PositiveInfinity.ToString())
};
#region DateTimeEquality
public class DateTimeEquality
{
[Test]
public void CanMatchDates()
{
DateTime expected = new DateTime(2007, 4, 1);
DateTime actual = new DateTime(2007, 4, 1);
Assert.That(actual, new EqualConstraint(expected));
}
[Test]
public void CanMatchDatesWithinTimeSpan()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
TimeSpan tolerance = TimeSpan.FromMinutes(5.0);
Assert.That(actual, new EqualConstraint(expected).Within(tolerance));
}
[Test]
public void CanMatchDatesWithinDays()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 4, 13, 0, 0);
Assert.That(actual, new EqualConstraint(expected).Within(5).Days);
}
[Test]
public void CanMatchDatesWithinHours()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 16, 0, 0);
Assert.That(actual, new EqualConstraint(expected).Within(5).Hours);
}
[Test]
public void CanMatchUsingIsEqualToWithinTimeSpan()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, Is.EqualTo(expected).Within(TimeSpan.FromMinutes(2)));
}
[Test]
public void CanMatchDatesWithinMinutes()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
}
[Test]
public void CanMatchTimeSpanWithinMinutes()
{
TimeSpan expected = new TimeSpan(10, 0, 0);
TimeSpan actual = new TimeSpan(10, 2, 30);
Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
}
[Test]
public void CanMatchDatesWithinSeconds()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds);
}
[Test]
public void CanMatchDatesWithinMilliseconds()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds);
}
[Test]
public void CanMatchDatesWithinTicks()
{
DateTime expected = new DateTime(2007, 4, 1, 13, 0, 0);
DateTime actual = new DateTime(2007, 4, 1, 13, 1, 0);
Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute*5).Ticks);
}
[Test]
public void ErrorIfDaysPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Days.Within(5)));
}
[Test]
public void ErrorIfHoursPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Hours.Within(5)));
}
[Test]
public void ErrorIfMinutesPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Minutes.Within(5)));
}
[Test]
public void ErrorIfSecondsPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Seconds.Within(5)));
}
[Test]
public void ErrorIfMillisecondsPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Milliseconds.Within(5)));
}
[Test]
public void ErrorIfTicksPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now).Ticks.Within(5)));
}
}
#endregion
#region DateTimeOffsetEquality
public class DateTimeOffsetShouldBeSame
{
[Datapoints]
public static readonly DateTimeOffset[] SameDateTimeOffsets =
{
new DateTimeOffset(new DateTime(2014, 1, 30, 12, 34, 56), new TimeSpan(6, 15, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 56), new TimeSpan(3, 0, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 56), new TimeSpan(3, 1, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 55), new TimeSpan(3, 0, 0)),
new DateTimeOffset(new DateTime(2014, 1, 30, 9, 19, 55), new TimeSpan(3, 50, 0))
};
[Theory]
public void PositiveEqualityTest(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That(value1 == value2);
Assert.That(value1, Is.EqualTo(value2));
}
[Theory]
public void NegativeEqualityTest(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That(value1 != value2);
Assert.That(value1, Is.Not.EqualTo(value2));
}
[Theory]
public void PositiveEqualityTestWithTolerance(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
Assert.That(value1, Is.EqualTo(value2).Within(1).Minutes);
}
[Theory]
public void NegativeEqualityTestWithTolerance(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() > new TimeSpan(0, 1, 0));
Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes);
}
[Theory]
public void NegativeEqualityTestWithToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() > new TimeSpan(0, 1, 0));
Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes.WithSameOffset);
}
[Theory]
public void PositiveEqualityTestWithToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
Assume.That(value1.Offset == value2.Offset);
Assert.That(value1, Is.EqualTo(value2).Within(1).Minutes.WithSameOffset);
}
[Theory]
public void NegativeEqualityTestWithinToleranceAndWithSameOffset(DateTimeOffset value1, DateTimeOffset value2)
{
Assume.That((value1 - value2).Duration() <= new TimeSpan(0, 1, 0));
Assume.That(value1.Offset != value2.Offset);
Assert.That(value1, Is.Not.EqualTo(value2).Within(1).Minutes.WithSameOffset);
}
}
public class DateTimeOffSetEquality
{
[Test]
public void CanMatchDates()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1));
Assert.That(actual, new EqualConstraint(expected));
}
[Test]
public void CanMatchDatesWithinTimeSpan()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
var tolerance = TimeSpan.FromMinutes(5.0);
Assert.That(actual, new EqualConstraint(expected).Within(tolerance));
}
[Test]
public void CanMatchDatesWithinDays()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 4, 13, 0, 0));
Assert.That(actual, new EqualConstraint(expected).Within(5).Days);
}
[Test]
public void CanMatchUsingIsEqualToWithinTimeSpan()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, Is.EqualTo(expected).Within(TimeSpan.FromMinutes(2)));
}
[Test]
public void CanMatchDatesWithinMinutes()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(5).Minutes);
}
[Test]
public void CanMatchDatesWithinSeconds()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(300).Seconds);
}
[Test]
public void CanMatchDatesWithinMilliseconds()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(300000).Milliseconds);
}
[Test]
public void CanMatchDatesWithinTicks()
{
var expected = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 0, 0));
var actual = new DateTimeOffset(new DateTime(2007, 4, 1, 13, 1, 0));
Assert.That(actual, new EqualConstraint(expected).Within(TimeSpan.TicksPerMinute*5).Ticks);
}
[Test]
public void DTimeOffsetCanMatchDatesWithinHours()
{
var a = DateTimeOffset.Parse("2012-01-01T12:00Z");
var b = DateTimeOffset.Parse("2012-01-01T12:01Z");
Assert.That(a, Is.EqualTo(b).Within(TimeSpan.FromMinutes(2)));
}
}
#endregion
#region DictionaryEquality
public class DictionaryEquality
{
[Test]
public void CanMatchDictionaries_SameOrder()
{
Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}});
}
[Test]
public void CanMatchDictionaries_Failure()
{
Assert.Throws<AssertionException>(
() => Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {1, 5}, {2, 2}}));
}
[Test]
public void CanMatchDictionaries_DifferentOrder()
{
Assert.AreEqual(new Dictionary<int, int> {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {2, 2}, {1, 1}});
}
#if !NETCOREAPP1_1
[Test]
public void CanMatchHashtables_SameOrder()
{
Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Hashtable {{0, 0}, {1, 1}, {2, 2}});
}
[Test]
public void CanMatchHashtables_Failure()
{
Assert.Throws<AssertionException>(
() => Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Hashtable {{0, 0}, {1, 5}, {2, 2}}));
}
[Test]
public void CanMatchHashtables_DifferentOrder()
{
Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Hashtable {{0, 0}, {2, 2}, {1, 1}});
}
[Test]
public void CanMatchHashtableWithDictionary()
{
Assert.AreEqual(new Hashtable {{0, 0}, {1, 1}, {2, 2}},
new Dictionary<int, int> {{0, 0}, {2, 2}, {1, 1}});
}
#endif
}
#endregion
#region FloatingPointEquality
public class FloatingPointEquality
{
[TestCase(double.NaN)]
[TestCase(double.PositiveInfinity)]
[TestCase(double.NegativeInfinity)]
[TestCase(float.NaN)]
[TestCase(float.PositiveInfinity)]
[TestCase(float.NegativeInfinity)]
public void CanMatchSpecialFloatingPointValues(object value)
{
Assert.That(value, new EqualConstraint(value));
}
[TestCase(20000000000000004.0)]
[TestCase(19999999999999996.0)]
public void CanMatchDoublesWithUlpTolerance(object value)
{
Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps);
}
[TestCase(20000000000000008.0)]
[TestCase(19999999999999992.0)]
public void FailsOnDoublesOutsideOfUlpTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(20000000000000000.0).Within(1).Ulps));
Assert.That(ex.Message, Does.Contain("+/- 1 Ulps"));
}
[TestCase(19999998.0f)]
[TestCase(20000002.0f)]
public void CanMatchSinglesWithUlpTolerance(object value)
{
Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps);
}
[TestCase(19999996.0f)]
[TestCase(20000004.0f)]
public void FailsOnSinglesOutsideOfUlpTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(20000000.0f).Within(1).Ulps));
Assert.That(ex.Message, Does.Contain("+/- 1 Ulps"));
}
[TestCase(9500.0)]
[TestCase(10000.0)]
[TestCase(10500.0)]
public void CanMatchDoublesWithRelativeTolerance(object value)
{
Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent);
}
[TestCase(8500.0)]
[TestCase(11500.0)]
public void FailsOnDoublesOutsideOfRelativeTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(10000.0).Within(10.0).Percent));
Assert.That(ex.Message, Does.Contain("+/- 10.0d Percent"));
}
[TestCase(9500.0f)]
[TestCase(10000.0f)]
[TestCase(10500.0f)]
public void CanMatchSinglesWithRelativeTolerance(object value)
{
Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent);
}
[TestCase(8500.0f)]
[TestCase(11500.0f)]
public void FailsOnSinglesOutsideOfRelativeTolerance(object value)
{
var ex = Assert.Throws<AssertionException>(() => Assert.That(value, new EqualConstraint(10000.0f).Within(10.0f).Percent));
Assert.That(ex.Message, Does.Contain("+/- 10.0f Percent"));
}
/// <summary>Applies both the Percent and Ulps modifiers to cause an exception</summary>
[Test]
public void ErrorWithPercentAndUlpsToleranceModes()
{
Assert.Throws<InvalidOperationException>(() =>
{
var shouldFail = new EqualConstraint(100.0f).Within(10.0f).Percent.Ulps;
});
}
/// <summary>Applies both the Ulps and Percent modifiers to cause an exception</summary>
[Test]
public void ErrorWithUlpsAndPercentToleranceModes()
{
Assert.Throws<InvalidOperationException>(() =>
{
EqualConstraint shouldFail = new EqualConstraint(100.0f).Within(10.0f).Ulps.Percent;
});
}
[Test]
public void ErrorIfPercentPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(1010, Is.EqualTo(1000).Percent.Within(5)));
}
[Test]
public void ErrorIfUlpsPrecedesWithin()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(1010.0, Is.EqualTo(1000.0).Ulps.Within(5)));
}
[TestCase(1000, 1010)]
[TestCase(1000U, 1010U)]
[TestCase(1000L, 1010L)]
[TestCase(1000UL, 1010UL)]
public void ErrorIfUlpsIsUsedOnIntegralType(object x, object y)
{
Assert.Throws<InvalidOperationException>(() => Assert.That(y, Is.EqualTo(x).Within(2).Ulps));
}
[Test]
public void ErrorIfUlpsIsUsedOnDecimal()
{
Assert.Throws<InvalidOperationException>(() => Assert.That(100m, Is.EqualTo(100m).Within(2).Ulps));
}
}
#endregion
#region UsingModifier
public class UsingModifier
{
[Test]
public void UsesProvidedIComparer()
{
var comparer = new ObjectComparer();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void CanCompareUncomparableTypes()
{
Assert.That(2 + 2, Is.Not.EqualTo("4"));
var comparer = new ConvertibleComparer();
Assert.That(2 + 2, Is.EqualTo("4").Using(comparer));
}
[Test]
public void UsesProvidedEqualityComparer()
{
var comparer = new ObjectEqualityComparer();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.Called, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericEqualityComparer()
{
var comparer = new GenericEqualityComparer<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericComparer()
{
var comparer = new GenericComparer<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericComparison()
{
var comparer = new GenericComparison<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using(comparer.Delegate));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesProvidedGenericEqualityComparison()
{
var comparer = new GenericEqualityComparison<int>();
Assert.That(2 + 2, Is.EqualTo(4).Using<int>(comparer.Delegate));
Assert.That(comparer.WasCalled, "Comparer was not called");
}
[Test]
public void UsesBooleanReturningDelegate()
{
Assert.That(2 + 2, Is.EqualTo(4).Using<int>((x, y) => x.Equals(y)));
}
[Test]
public void UsesProvidedLambda_IntArgs()
{
Assert.That(2 + 2, Is.EqualTo(4).Using<int>((x, y) => x.CompareTo(y)));
}
[Test]
public void UsesProvidedLambda_StringArgs()
{
Assert.That("hello", Is.EqualTo("HELLO").Using<string>((x, y) => StringUtil.Compare(x, y, true)));
}
[Test]
public void UsesProvidedListComparer()
{
var list1 = new List<int>() {2, 3};
var list2 = new List<int>() {3, 4};
var list11 = new List<List<int>>() {list1};
var list22 = new List<List<int>>() {list2};
var comparer = new IntListEqualComparer();
Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer));
}
public class IntListEqualComparer : IEqualityComparer<List<int>>
{
public bool Equals(List<int> x, List<int> y)
{
return x.Count == y.Count;
}
public int GetHashCode(List<int> obj)
{
return obj.Count.GetHashCode();
}
}
[Test]
public void UsesProvidedArrayComparer()
{
var array1 = new int[] {2, 3};
var array2 = new int[] {3, 4};
var list11 = new List<int[]>() {array1};
var list22 = new List<int[]>() {array2};
var comparer = new IntArrayEqualComparer();
Assert.That(list11, new CollectionEquivalentConstraint(list22).Using(comparer));
}
public class IntArrayEqualComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
return x.Length == y.Length;
}
public int GetHashCode(int[] obj)
{
return obj.Length.GetHashCode();
}
}
[Test]
public void HasMemberHonorsUsingWhenCollectionsAreOfDifferentTypes()
{
ICollection strings = new List<string> { "1", "2", "3" };
Assert.That(strings, Has.Member(2).Using<string, int>((s, i) => i.ToString() == s));
}
}
#endregion
#region TypeEqualityMessages
private readonly string NL = Environment.NewLine;
private static IEnumerable DifferentTypeSameValueTestData
{
get
{
var ptr = new System.IntPtr(0);
var ExampleTestA = new ExampleTest.ClassA(0);
var ExampleTestB = new ExampleTest.ClassB(0);
var clipTestA = new ExampleTest.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere();
var clipTestB = new ExampleTest.Clip.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip.ReallyLongClassNameShouldBeHere();
yield return new object[] { 0, ptr };
yield return new object[] { ExampleTestA, ExampleTestB };
yield return new object[] { clipTestA, clipTestB };
}
}
[Test]
public void SameValueDifferentTypeExactMessageMatch()
{
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(0, new System.IntPtr(0)));
Assert.AreEqual(ex.Message, " Expected: 0 (Int32)"+ NL + " But was: 0 (IntPtr)"+ NL);
}
class Dummy
{
internal readonly int value;
public Dummy(int value)
{
this.value = value;
}
public override string ToString()
{
return "Dummy " + value;
}
}
class Dummy1
{
internal readonly int value;
public Dummy1(int value)
{
this.value = value;
}
public override string ToString()
{
return "Dummy " + value;
}
}
class DummyGenericClass<T>
{
private readonly object _obj;
public DummyGenericClass(object obj)
{
_obj = obj;
}
public override string ToString()
{
return _obj.ToString();
}
}
[Test]
public void TestSameValueDifferentTypeUsingGenericTypes()
{
var d1 = new Dummy(12);
var d2 = new Dummy1(12);
var dc1 = new DummyGenericClass<Dummy>(d1);
var dc2 = new DummyGenericClass<Dummy1>(d2);
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(dc1, dc2));
var expectedMsg =
" Expected: <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy])" + Environment.NewLine +
" But was: <Dummy 12> (EqualConstraintTests+DummyGenericClass`1[EqualConstraintTests+Dummy1])" + Environment.NewLine;
Assert.AreEqual(expectedMsg, ex.Message);
}
[Test]
public void SameValueAndTypeButDifferentReferenceShowNotShowTypeDifference()
{
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(Is.Zero, Is.Zero));
Assert.AreEqual(ex.Message, " Expected: <<equal 0>>"+ NL + " But was: <<equal 0>>"+ NL);
}
[Test, TestCaseSource(nameof(DifferentTypeSameValueTestData))]
public void SameValueDifferentTypeRegexMatch(object expected, object actual)
{
var ex = Assert.Throws<AssertionException>(() => Assert.AreEqual(expected, actual));
Assert.That(ex.Message, Does.Match(@"\s*Expected\s*:\s*.*\s*\(.+\)\r?\n\s*But\s*was\s*:\s*.*\s*\(.+\)"));
}
}
namespace ExampleTest.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip {
class ReallyLongClassNameShouldBeHere {
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return obj.ToString() == this.ToString();
}
public override int GetHashCode()
{
return "a".GetHashCode();
}
public override string ToString()
{
return "a";
}
}
}
namespace ExampleTest.Clip.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Outer.Middle.Inner.Clip
{
class ReallyLongClassNameShouldBeHere {
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return obj.ToString()==this.ToString();
}
public override int GetHashCode()
{
return "a".GetHashCode();
}
public override string ToString()
{
return "a";
}
}
}
namespace ExampleTest {
class BaseTest {
readonly int _value;
public BaseTest()
{
_value = 0;
}
public BaseTest(int value) {
_value = value;
}
public override bool Equals(object obj)
{
if (obj == null || GetType() != obj.GetType())
{
return false;
}
return _value.Equals(((BaseTest)obj)._value);
}
public override string ToString()
{
return _value.ToString();
}
public override int GetHashCode()
{
return _value.GetHashCode();
}
}
class ClassA : BaseTest {
public ClassA(int x) : base(x) { }
}
class ClassB : BaseTest
{
public ClassB(int x) : base(x) { }
}
}
#endregion
/// <summary>
/// ConvertibleComparer is used in testing to ensure that objects
/// of different types can be compared when appropriate.
/// </summary>
/// <remark>Introduced when testing issue 1897.
/// https://github.com/nunit/nunit/issues/1897
/// </remark>
public class ConvertibleComparer : IComparer<IConvertible>
{
public int Compare(IConvertible x, IConvertible y)
{
var str1 = Convert.ToString(x, CultureInfo.InvariantCulture);
var str2 = Convert.ToString(y, CultureInfo.InvariantCulture);
return string.Compare(str1, str2, StringComparison.Ordinal);
}
}
}
| |
// -------------------------------------------
// Control Freak 2
// Copyright (C) 2013-2016 Dan's Game Tools
// http://DansGameTools.com
// -------------------------------------------
using UnityEngine;
using UnityEngine.EventSystems;
using ControlFreak2.Internal;
namespace ControlFreak2 //.Internal
{
// -------------------------------
//! Base class for dynamic touch controls.
// -------------------------------
public abstract class DynamicTouchControl : TouchControl
{
//! \cond
public bool fadeOutWhenReleased = true;
public bool startFadedOut = false;
public float fadeOutTargetAlpha = 0;
public float fadeInDuration = 0.2f;
public float fadeOutDelay = 0.5f;
public float fadeOutDuration = 0.5f;
public bool centerOnDirectTouch = true;
public bool centerOnIndirectTouch = true;
public bool centerWhenFollowing = false;
public bool stickyMode;
public bool clampInsideRegion = true;
public bool clampInsideCanvas = true;
public bool returnToStartingPosition = false;
public Vector2
directInitialVector,
indirectInitialVector;
public float touchSmoothing;
[Tooltip("Stick's origin smoothing - the higher the value, the slower the movement."), Range(0, 1.0f)]
public float originSmoothTime = 0.5f;
const float ORIGIN_ANIM_MAX_TIME = 0.2f;
public DynamicRegion targetDynamicRegion;
protected bool linkedToDynamicRegion;
protected bool touchStartedByRegion;
protected TouchStartType touchStartType;
protected TouchGestureBasicState
touchStateOriented,
touchStateScreen,
touchStateWorld;
protected TouchObject touchObj;
private RectTransform initialRectCopy;
private Vector3
originPos,
originStartPos;
private bool originAnimOn;
private float originAnimElapsed;
// -----------------
public DynamicTouchControl() : base()
{
this.touchStateScreen = new TouchGestureBasicState();
this.touchStateWorld = new TouchGestureBasicState();
this.touchStateOriented = new TouchGestureBasicState();
this.directInitialVector = Vector2.zero;
this.indirectInitialVector = Vector2.zero;
this.startFadedOut = true;
this.fadeOutWhenReleased = true;
this.touchSmoothing = 0.1f;
}
// ------------------
override protected void OnInitControl()
{
this.SetTargetDynamicRegion(this.targetDynamicRegion);
this.SetTouchSmoothing(this.touchSmoothing);
// Create a copy of this rectTransform...
this.StoreDefaultPos();
}
// ------------------
public override void ResetControl ()
{
if (this.CanFadeOut() && this.startFadedOut && !CFUtils.editorStopped)
this.DynamicFadeOut(false);
else
this.DynamicWakeUp(false);
}
// --------------
override public void InvalidateHierarchy()
{
base.InvalidateHierarchy();
this.StoreDefaultPos();
}
//! \endcond
// ----------------
public bool Pressed() { return this.touchStateWorld.PressedRaw(); }
public bool JustPressed() { return this.touchStateWorld.JustPressedRaw(); }
public bool JustReleased() { return this.touchStateWorld.JustReleasedRaw(); }
//// ----------------
//private bool IsPhysicallyTouched() { return (this.touchStateWorld.IsPressureSensitive().PressedRaw() && (this.touchObj != null)); }
// -----------------
public bool IsTouchPressureSensitive() { return (this.touchStateWorld.PressedRaw() && this.touchStateWorld.IsPressureSensitive()); }
public float GetTouchPressure() { return (this.touchStateWorld.PressedRaw() ? this.touchStateWorld.GetPressure() : 0); }
//public float GetAbsTouchPressure() { return (this.IsPhysicallyTouched() ? this.touchObj.GetAbsPressure() : 0); }
//public float GetMaxTouchPressure() { return (this.IsPhysicallyTouched() ? this.touchObj.GetMaxPressure() : 0); }
// ------------------
//! Set this control's touch smoothing time as a fraction of max touch smoothing time.
// ------------------
public void SetTouchSmoothing(float smTime)
{
this.touchSmoothing = Mathf.Clamp01(smTime);
this.touchStateWorld .SetSmoothingTime(this.touchSmoothing * InputRig.TOUCH_SMOOTHING_MAX_TIME);
this.touchStateOriented .SetSmoothingTime(this.touchSmoothing * InputRig.TOUCH_SMOOTHING_MAX_TIME);
this.touchStateScreen .SetSmoothingTime(this.touchSmoothing * InputRig.TOUCH_SMOOTHING_MAX_TIME);
}
// -------------------
//! Set this control's dynamic region.
// ----------------
public void SetTargetDynamicRegion(DynamicRegion targetDynamicRegion)
{
this.targetDynamicRegion = targetDynamicRegion;
if ((targetDynamicRegion != null) && targetDynamicRegion.CanBeUsed())
{
targetDynamicRegion.SetTargetControl(this);
}
}
//! \cond
// ---------------
public void OnLinkToDynamicRegion(DynamicRegion dynRegion)
{
this.linkedToDynamicRegion = ((dynRegion != null) && (dynRegion == this.targetDynamicRegion));
}
//! \endcond
// --------------
//! Get this control's dynamic region.
// --------------
public DynamicRegion GetDynamicRegion()
{
return (this.linkedToDynamicRegion ? this.targetDynamicRegion : null);
//return this.dynamicRegion;
}
// ----------------
//! Is this control in dynamic mode?
// ----------------
public bool IsInDynamicMode()
{
return (this.GetDynamicRegion() != null);
}
// ----------------
//! Get dynamic alpha (not multiplied by base alpha).
// ------------------
public float GetDynamicAlpha()
{
#if UNITY_EDITOR
if (CFUtils.editorStopped)
return 1.0f;
#endif
return this.dynamicAlphaCur;
}
//! \cond
// -----------------
override public float GetAlpha()
{
return this.GetDynamicAlpha() * base.GetAlpha();
}
private bool
dynamicIsFadingOut,
dynamicAlphaAnimOn,
dynamicWaitingToFadeOut;
private float
dynamicAlphaAnimDur,
dynamicAlphaAnimElapsed,
dynamicFadeOutDelayElapsed,
dynamicAlphaCur,
dynamicAlphaStart,
dynamicAlphaTarget;
// --------------------
private void SetDynamicAlpha(float alpha, float animDur)
{
if (animDur > 0.001f)
{
this.dynamicAlphaAnimDur = animDur;
this.dynamicAlphaStart = this.dynamicAlphaCur;
this.dynamicAlphaTarget = alpha;
this.dynamicAlphaAnimElapsed = 0;
this.dynamicAlphaAnimOn = true;
}
else
{
this.dynamicAlphaAnimOn = false;
this.dynamicAlphaAnimElapsed = 0;
this.dynamicAlphaCur = this.dynamicAlphaTarget = this.dynamicAlphaStart = alpha;
}
}
// --------------------
private void DynamicWakeUp(bool animate)
{
this.dynamicIsFadingOut = false;
this.dynamicWaitingToFadeOut = false;
this.SetDynamicAlpha(1.0f, (animate ? this.fadeInDuration : 0));
}
// --------------------
private void DynamicFadeOut(bool animate)
{
if (!animate)
{
this.dynamicIsFadingOut = true;
this.dynamicWaitingToFadeOut = false;
this.dynamicFadeOutDelayElapsed = 0;
this.SetDynamicAlpha(this.fadeOutTargetAlpha, 0);
}
else
{
if (this.dynamicIsFadingOut)
return;
this.dynamicIsFadingOut = true;
this.dynamicWaitingToFadeOut = true;
this.dynamicFadeOutDelayElapsed = 0;
}
}
// ----------------------
private bool CanFadeOut()
{
return (this.fadeOutWhenReleased && this.IsInDynamicMode());
}
// --------------------
private void UpdateDynamicAlpha()
{
// Update anim...
if (this.dynamicAlphaAnimOn)
{
this.dynamicAlphaAnimElapsed += Time.unscaledDeltaTime;
if (this.dynamicAlphaAnimElapsed > this.dynamicAlphaAnimDur)
{
this.dynamicAlphaAnimOn = false;
this.dynamicAlphaCur = this.dynamicAlphaTarget;
}
else
{
this.dynamicAlphaCur = Mathf.Lerp(this.dynamicAlphaStart, this.dynamicAlphaTarget, (this.dynamicAlphaAnimElapsed / this.dynamicAlphaAnimDur));
}
}
// Control fadeout...
if (this.dynamicIsFadingOut)
{
if (this.dynamicWaitingToFadeOut)
{
this.dynamicFadeOutDelayElapsed += Time.unscaledDeltaTime;
if (this.dynamicFadeOutDelayElapsed >= this.fadeOutDelay)
{
this.dynamicWaitingToFadeOut = false;
this.SetDynamicAlpha(this.fadeOutTargetAlpha, this.fadeOutDuration);
}
}
}
else
{
}
}
// -----------------
public override void SetWorldPos(Vector2 pos2D)
{
this.SetOriginPos(pos2D, false);
this.StoreDefaultPos();
}
// -----------------
protected void SetOriginPos(Vector3 pos, bool animate)
{
this.originPos = pos;
if (animate)
{
this.originStartPos = this.GetWorldPos();
this.originAnimOn = true;
this.originAnimElapsed = 0;
}
else
{
this.SetWorldPosRaw(this.originPos); //this.transform.position = this.originPos;
this.originStartPos = this.originPos;
this.originAnimOn = false;
}
}
protected void SetOriginPos(Vector3 pos) { SetOriginPos(pos, true); }
// ---------------------
protected Vector2 GetOriginOffset()
{
return (this.transform.position - this.originPos);
}
// -------------------
protected void UpdateOriginAnimation()
{
if (this.originAnimOn)
{
this.originAnimElapsed += CFUtils.realDeltaTime;
if (this.originAnimElapsed >= (this.originSmoothTime * ORIGIN_ANIM_MAX_TIME))
{
this.originAnimOn = false;
this.SetWorldPosRaw(this.originPos);
}
else
{
this.SetWorldPosRaw(Vector3.Lerp(this.originStartPos, this.originPos,
(this.originAnimElapsed / (this.originSmoothTime * ORIGIN_ANIM_MAX_TIME))));
}
}
}
// ----------------------
//! Store this dynamic control's default position.
// ------------------
protected void StoreDefaultPos()
{
if (CFUtils.editorStopped)
return;
if (this.initialRectCopy == null)
{
GameObject go = new GameObject(this.name + "_INITIAL_POS", typeof(RectTransform));
this.initialRectCopy = go.GetComponent<RectTransform>();
}
RectTransform rectTr = this.GetComponent<RectTransform>();
this.initialRectCopy.hideFlags = HideFlags.DontSave; //.HideAndDontSave;
this.initialRectCopy.SetParent(rectTr.parent, false);
this.initialRectCopy.anchoredPosition3D = rectTr.anchoredPosition3D;
this.initialRectCopy.anchorMax = rectTr.anchorMax;
this.initialRectCopy.anchorMin = rectTr.anchorMin;
this.initialRectCopy.offsetMin = rectTr.offsetMin;
this.initialRectCopy.offsetMax = rectTr.offsetMax;
this.initialRectCopy.pivot = rectTr.pivot;
}
//
// -------------------
protected Vector3 GetDefaultPos()
{
return ((this.initialRectCopy == null) ? this.transform.position : this.initialRectCopy.position);
}
// -------------------
override protected void OnDestroyControl()
{
this.ResetControl();
// Destroy initial rect copy...
if (this.initialRectCopy != null)
GameObject.Destroy(this.initialRectCopy);
}
// ----------------------
override protected void OnUpdateControl()
{
#if UNITY_EDITOR
if (CFUtils.editorStopped)
return;
#endif
if ((this.touchObj != null) && (this.rig != null))
this.rig.WakeTouchControlsUp();
this.UpdateDynamicAlpha();
this.touchStateWorld.Update();
this.touchStateScreen.Update();
this.touchStateOriented.Update();
if (this.touchStateScreen.JustPressedRaw())
{
this.DynamicWakeUp(true);
// Static mode...
if (!this.IsInDynamicMode())
{
this.SetOriginPos(this.GetWorldPos(), false);
}
// Dynamic mode...
else
{
bool isFadedOut = (this.GetDynamicAlpha() < 0.001f);
if (!this.centerOnDirectTouch && !this.touchStartedByRegion)
{
this.SetOriginPos(this.GetWorldPos(), false);
}
else
{
Vector2 originPos = this.touchStateWorld.GetStartPos();
// Add indirect initial offset...
if (this.touchStartedByRegion)
{
if (this.indirectInitialVector != Vector2.zero)
originPos -= this.NormalizedToWorldOffset(this.indirectInitialVector);
}
else
{
if (this.directInitialVector != Vector2.zero)
originPos -= this.NormalizedToWorldOffset(this.directInitialVector);
}
if (!isFadedOut && !this.centerOnIndirectTouch)
{
originPos = this.GetFollowPos(originPos, Vector2.zero);
}
if (this.clampInsideRegion && (this.GetDynamicRegion() != null))
originPos = this.ClampInsideOther(originPos, this.GetDynamicRegion());
if (this.clampInsideCanvas && (this.canvas != null))
originPos = this.ClampInsideCanvas(originPos, this.canvas);
this.SetOriginPos(originPos, !isFadedOut);
}
}
}
if (this.touchStateWorld.JustReleasedRaw())
{
// Return to initial pos in dynamic mode...
if (!this.IsInDynamicMode() || this.returnToStartingPosition)
{
this.SetOriginPos(this.GetDefaultPos(), true);
}
}
// Fade-out in dynamic mode...
if (this.IsInDynamicMode() && this.fadeOutWhenReleased && !this.touchStateWorld.PressedRaw())
this.DynamicFadeOut(true);
// Reset 'started by region' flag...
this.touchStartedByRegion = false;
// Update following...
if (this.touchStateWorld.PressedRaw())
{
if (this.stickyMode && ((this.swipeOffMode == TouchControl.SwipeOffMode.Disabled) ||
(this.swipeOffMode == TouchControl.SwipeOffMode.OnlyIfSwipedOver) && (this.touchStartType != TouchStartType.SwipeOver))) // && this.IsInDynamicMode())
{
bool pressWasOutside = true;
Vector3 followPos = this.touchStateWorld.GetCurPosSmooth();
if (!this.centerWhenFollowing)
{
pressWasOutside = false;
followPos = this.GetFollowPos(followPos, this.GetOriginOffset(), out pressWasOutside);
}
if (pressWasOutside)
{
if (this.clampInsideRegion && (this.GetDynamicRegion() != null))
followPos = this.ClampInsideOther(followPos, this.GetDynamicRegion()); //this.joyRegion);
if (this.clampInsideCanvas && (this.canvas != null))
followPos = this.ClampInsideCanvas(followPos, this.canvas);
this.SetOriginPos(followPos);
}
}
}
this.UpdateOriginAnimation();
}
// -------------------
override public bool OnTouchStart(TouchObject touch, TouchControl sender, TouchStartType touchStartType)
{
if (this.touchObj != null)
return false;
this.touchObj = touch;
this.touchObj.AddControl(this);
Vector3
startPosScreen = ((touchStartType == TouchStartType.DirectPress) ? touch.screenPosStart : touch.screenPosCur),
curPosScreen = touch.screenPosCur,
startPosOriented = this.ScreenToOrientedPos(startPosScreen, touch.cam),
curPosOriented = this.ScreenToOrientedPos(curPosScreen, touch.cam),
startPosWorld = this.ScreenToWorldPos(startPosScreen, touch.cam),
curPosWorld = this.ScreenToWorldPos(curPosScreen, touch.cam);
this.touchStateWorld.OnTouchStart (startPosWorld, curPosWorld, 0, this.touchObj);
this.touchStateScreen.OnTouchStart (startPosScreen, curPosScreen, 0, this.touchObj);
this.touchStateOriented.OnTouchStart(startPosOriented, curPosOriented, 0, this.touchObj);
this.touchStartedByRegion = ((sender != null) && (sender != this)); //== this.GetDynamicRegion()));
this.touchStartType = touchStartType;
return true;
}
// -------------------
override public bool OnTouchEnd(TouchObject touch, TouchEndType touchEndType)
{
if ((touch != this.touchObj) || (this.touchObj == null))
return false;
this.touchObj = null;
this.touchStateWorld.OnTouchEnd(touchEndType != TouchEndType.Release); //cancel);
this.touchStateScreen.OnTouchEnd(touchEndType != TouchEndType.Release); //cancel);
this.touchStateOriented.OnTouchEnd(touchEndType != TouchEndType.Release); //cancel);
return true;
}
// -------------------
override public bool OnTouchMove(TouchObject touch) //, TouchControl sender)
{
if ((touch != this.touchObj) || (this.touchObj == null))
return false;
Vector3
posScreen = touch.screenPosCur,
posWorld = this.ScreenToWorldPos(touch.screenPosCur, touch.cam),
posOriented = this.ScreenToOrientedPos(touch.screenPosCur, touch.cam);
this.touchStateWorld.OnTouchMove(posWorld);
this.touchStateScreen.OnTouchMove(posScreen);
this.touchStateOriented.OnTouchMove(posOriented);
this.CheckSwipeOff(touch, this.touchStartType);
return true;
}
// -------------------
override public bool OnTouchPressureChange(TouchObject touch)
{
if ((touch != this.touchObj) || (this.touchObj == null))
return false;
this.touchStateWorld.OnTouchPressureChange(touch.GetPressure());
this.touchStateScreen.OnTouchPressureChange(touch.GetPressure());
this.touchStateOriented.OnTouchPressureChange(touch.GetPressure());
return true;
}
// ----------------------
override public void ReleaseAllTouches()
{
if (this.touchObj != null)
{
this.touchObj.ReleaseControl(this, TouchEndType.Cancel);
this.touchObj = null;
}
this.touchStateWorld.OnTouchEnd(true); //(touchEndType != TouchEndType.RELEASE)); //cancel);
this.touchStateOriented.OnTouchEnd(true); //(touchEndType != TouchEndType.RELEASE)); //cancel);
this.touchStateScreen.OnTouchEnd(true); //(touchEndType != TouchEndType.RELEASE)); //cancel);
}
// -------------------
override public bool CanBeTouchedDirectly(TouchObject touchObj)
{
return (base.CanBeTouchedDirectly(touchObj) && (this.touchObj == null) );
}
// ---------------------
public override bool CanBeSwipedOverFromNothing(TouchObject touchObj)
{
return (base.CanBeSwipedOverFromNothingDefault(touchObj) && (this.touchObj == null) && this.IsActiveAndVisible());
}
// ---------------------
public override bool CanBeSwipedOverFromRestrictedList(TouchObject touchObj)
{
return (base.CanBeSwipedOverFromRestrictedListDefault(touchObj) && (this.touchObj == null) && this.IsActiveAndVisible());
}
// -----------------------
public override bool CanSwipeOverOthers(TouchObject touchObj)
{
return this.CanSwipeOverOthersDefault(touchObj, this.touchObj, this.touchStartType);
}
// -------------------
virtual public bool CanBeActivatedByDynamicRegion()
{
return ((this.touchObj == null) && this.IsActive());
}
// -------------------
override public bool CanBeActivatedByOtherControl(TouchControl c, TouchObject touchObj)
{
return (base.CanBeActivatedByOtherControl(c, touchObj) && (this.touchObj == null));
}
//! \endcond
}
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Net;
using System.Text;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Nini.Config;
using log4net;
namespace OpenSim.Server.Handlers.Simulation
{
public class AgentGetHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public AgentGetHandler(ISimulationService service, IAuthenticationService authentication) :
base("GET", "/agent")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
public class AgentPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
private IAuthenticationService m_AuthenticationService;
// TODO: unused: private bool m_AllowForeignGuests;
public AgentPostHandler(ISimulationService service, IAuthenticationService authentication, bool foreignGuests) :
base("POST", "/agent")
{
m_SimulationService = service;
m_AuthenticationService = authentication;
// TODO: unused: m_AllowForeignGuests = foreignGuests;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] result = new byte[0];
UUID agentID;
string action;
ulong regionHandle;
if (!RestHandlerUtils.GetParams(path, out agentID, out regionHandle, out action))
{
m_log.InfoFormat("[AgentPostHandler]: Invalid parameters for agent message {0}", path);
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Invalid parameters for agent message " + path;
return result;
}
if (m_AuthenticationService != null)
{
// Authentication
string authority = string.Empty;
string authToken = string.Empty;
if (!RestHandlerUtils.GetAuthentication(httpRequest, out authority, out authToken))
{
m_log.InfoFormat("[AgentPostHandler]: Authentication failed for agent message {0}", path);
httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized;
return result;
}
// TODO: Rethink this
//if (!m_AuthenticationService.VerifyKey(agentID, authToken))
//{
// m_log.InfoFormat("[AgentPostHandler]: Authentication failed for agent message {0}", path);
// httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
// return result;
//}
m_log.DebugFormat("[AgentPostHandler]: Authentication succeeded for {0}", agentID);
}
OSDMap args = Util.GetOSDMap(request, (int)httpRequest.ContentLength);
if (args == null)
{
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Unable to retrieve data";
m_log.DebugFormat("[AgentPostHandler]: Unable to retrieve data for post {0}", path);
return result;
}
// retrieve the regionhandle
ulong regionhandle = 0;
if (args["destination_handle"] != null)
UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
AgentCircuitData aCircuit = new AgentCircuitData();
try
{
aCircuit.UnpackAgentCircuitData(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[AgentPostHandler]: exception on unpacking CreateAgent message {0}", ex.Message);
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Problems with data deserialization";
return result;
}
string reason = string.Empty;
// We need to clean up a few things in the user service before I can do this
//if (m_AllowForeignGuests)
// m_regionClient.AdjustUserInformation(aCircuit);
// Finally!
bool success = m_SimulationService.CreateAgent(regionhandle, aCircuit, out reason);
OSDMap resp = new OSDMap(1);
resp["success"] = OSD.FromBoolean(success);
httpResponse.StatusCode = (int)HttpStatusCode.OK;
return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
}
}
public class AgentPutHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public AgentPutHandler(ISimulationService service, IAuthenticationService authentication) :
base("PUT", "/agent")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
public class AgentDeleteHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public AgentDeleteHandler(ISimulationService service, IAuthenticationService authentication) :
base("DELETE", "/agent")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.Web;
using System.Threading;
using System.IO;
using FluorineFx;
using FluorineFx.Context;
using FluorineFx.Configuration;
using FluorineFx.Messaging;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Config;
using FluorineFx.Messaging.Messages;
using FluorineFx.Messaging.Endpoints;
using FluorineFx.Messaging.Endpoints.Filter;
using FluorineFx.Messaging.Services.Remoting;
using FluorineFx.Util;
using log4net;
namespace FluorineFx.Messaging.Endpoints
{
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
class AMFEndpoint : EndpointBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(AMFEndpoint));
protected FilterChain _filterChain;
AtomicInteger _waitingPollRequests;
public AMFEndpoint(MessageBroker messageBroker, ChannelDefinition channelDefinition)
: base(messageBroker, channelDefinition)
{
_waitingPollRequests = new AtomicInteger();
}
public override void Start()
{
DeserializationFilter deserializationFilter = new DeserializationFilter();
deserializationFilter.UseLegacyCollection = this.IsLegacyCollection;
ServiceMapFilter serviceMapFilter = new ServiceMapFilter(this);
WsdlFilter wsdlFilter = new WsdlFilter();
ContextFilter contextFilter = new ContextFilter(this);
AuthenticationFilter authenticationFilter = new AuthenticationFilter(this);
DescribeServiceFilter describeServiceFilter = new DescribeServiceFilter();
//CacheFilter cacheFilter = new CacheFilter();
ProcessFilter processFilter = new ProcessFilter(this);
MessageFilter messageFilter = new MessageFilter(this);
DebugFilter debugFilter = new DebugFilter();
SerializationFilter serializationFilter = new SerializationFilter();
serializationFilter.UseLegacyCollection = this.IsLegacyCollection;
serializationFilter.UseLegacyThrowable = this.IsLegacyThrowable;
deserializationFilter.Next = serviceMapFilter;
serviceMapFilter.Next = wsdlFilter;
wsdlFilter.Next = contextFilter;
contextFilter.Next = authenticationFilter;
authenticationFilter.Next = describeServiceFilter;
describeServiceFilter.Next = processFilter;
//describeServiceFilter.Next = cacheFilter;
//cacheFilter.Next = processFilter;
processFilter.Next = debugFilter;
debugFilter.Next = messageFilter;
messageFilter.Next = serializationFilter;
_filterChain = new FilterChain(deserializationFilter);
}
public override void Stop()
{
_filterChain = null;
base.Stop();
}
public override void Service()
{
//AMFContext amfContext = new AMFContext(HttpContext.Current.Request.InputStream, HttpContext.Current.Response.OutputStream);
AMFContext amfContext = null;
if (FluorineConfiguration.Instance.FluorineSettings.Debug != null &&
FluorineConfiguration.Instance.FluorineSettings.Debug.Mode != Debug.Off)
{
MemoryStream ms = new MemoryStream();
int bufferSize = 255;
byte[] buffer = new byte[bufferSize];
int byteCount = 0;
while ((byteCount = HttpContext.Current.Request.InputStream.Read(buffer, 0, bufferSize)) > 0)
{
ms.Write(buffer, 0, byteCount);
}
ms.Seek(0, SeekOrigin.Begin);
amfContext = new AMFContext(ms, HttpContext.Current.Response.OutputStream);
}
if( amfContext == null )
amfContext = new AMFContext(HttpContext.Current.Request.InputStream, HttpContext.Current.Response.OutputStream);
AMFContext.Current = amfContext;
_filterChain.InvokeFilters(amfContext);
}
public override IMessage ServiceMessage(IMessage message)
{
if (FluorineContext.Current.Client != null)
FluorineContext.Current.Client.Renew();
if (message is CommandMessage)
{
CommandMessage commandMessage = message as CommandMessage;
switch (commandMessage.operation)
{
case CommandMessage.PollOperation:
{
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.Endpoint_HandleMessage, this.Id, message.ToString()));
if (FluorineContext.Current.Client != null)
FluorineContext.Current.Client.Renew();
//IMessage[] messages = null;
IList messages = null;
_waitingPollRequests.Increment();
int waitIntervalMillis = this.ChannelDefinition.Properties.WaitIntervalMillis != -1 ? this.ChannelDefinition.Properties.WaitIntervalMillis : 60000;// int.MaxValue;
if (commandMessage.HeaderExists(CommandMessage.FluorineSuppressPollWaitHeader))
waitIntervalMillis = 0;
//If async handling was not set long polling is not supported
if (!FluorineConfiguration.Instance.FluorineSettings.Runtime.AsyncHandler)
waitIntervalMillis = 0;
if (this.ChannelDefinition.Properties.MaxWaitingPollRequests <= 0 || _waitingPollRequests.Value >= this.ChannelDefinition.Properties.MaxWaitingPollRequests)
waitIntervalMillis = 0;
if (message.destination != null && message.destination != string.Empty)
{
string clientId = commandMessage.clientId as string;
MessageDestination messageDestination = this.GetMessageBroker().GetDestination(message.destination) as MessageDestination;
MessageClient client = messageDestination.SubscriptionManager.GetSubscriber(clientId);
client.Renew();
//messages = client.GetPendingMessages();
}
else
{
//if (FluorineContext.Current.Client != null)
// messages = FluorineContext.Current.Client.GetPendingMessages(waitIntervalMillis);
}
if (FluorineContext.Current.Client != null)
{
IEndpointPushHandler handler = FluorineContext.Current.Client.GetEndpointPushHandler(this.Id);
if (handler != null)
messages = handler.GetPendingMessages();
if (messages == null)
{
lock (handler.SyncRoot)
{
Monitor.Wait(handler.SyncRoot, waitIntervalMillis);
}
messages = handler.GetPendingMessages();
}
}
_waitingPollRequests.Decrement();
IMessage response = null;
if (messages == null || messages.Count == 0)
response = new AcknowledgeMessage();
else
{
CommandMessage resultMessage = new CommandMessage();
resultMessage.operation = CommandMessage.ClientSyncOperation;
resultMessage.body = messages;
response = resultMessage;
}
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.Endpoint_Response, this.Id, response.ToString()));
return response;
}
case CommandMessage.SubscribeOperation:
{
/*
if (FluorineContext.Current.Client == null)
FluorineContext.Current.SetCurrentClient(this.GetMessageBroker().ClientRegistry.GetClient(message));
RemotingConnection remotingConnection = null;
foreach (IConnection connection in FluorineContext.Current.Client.Connections)
{
if (connection is RemotingConnection)
{
remotingConnection = connection as RemotingConnection;
break;
}
}
if (remotingConnection == null)
{
remotingConnection = new RemotingConnection(this, null, FluorineContext.Current.Client.Id, null);
FluorineContext.Current.Client.Renew(this.ClientLeaseTime);
remotingConnection.Initialize(FluorineContext.Current.Client);
}
FluorineWebContext webContext = FluorineContext.Current as FluorineWebContext;
webContext.SetConnection(remotingConnection);
*/
if (this.ChannelDefinition.Properties.IsPollingEnabled)
{
//Create and forget, client will close the notifier
IEndpointPushHandler handler = FluorineContext.Current.Client.GetEndpointPushHandler(this.Id);
if( handler == null )
handler = new EndpointPushNotifier(this, FluorineContext.Current.Client);
/*
lock (_endpointPushHandlers.SyncRoot)
{
_endpointPushHandlers.Add(notifier.Id, notifier);
}
*/
}
}
break;
case CommandMessage.DisconnectOperation:
{
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.Endpoint_HandleMessage, this.Id, message.ToString()));
if (FluorineContext.Current.Client != null && FluorineContext.Current.Client.IsValid)
{
IList messageClients = FluorineContext.Current.Client.MessageClients;
if (messageClients != null)
{
foreach (MessageClient messageClient in messageClients)
{
messageClient.Invalidate();
}
}
FluorineContext.Current.Client.Invalidate();
}
if (FluorineContext.Current.Session != null)
{
FluorineContext.Current.Session.Invalidate();
}
//Disconnect command is received from a client channel.
//The response returned by this method is not guaranteed to get to the client, which is free to terminate its physical connection at any point.
IMessage response = new AcknowledgeMessage();
if (log.IsDebugEnabled)
log.Debug(__Res.GetString(__Res.Endpoint_Response, this.Id, response.ToString()));
return response;
}
}
}
return base.ServiceMessage(message);
}
public override void Push(IMessage message, MessageClient messageClient)
{
if (this.ChannelDefinition.Properties.IsPollingEnabled)
{
IEndpointPushHandler handler = messageClient.Client.GetEndpointPushHandler(this.Id);
if (handler != null)
{
IMessage messageClone = message.Copy() as IMessage;
messageClone.SetHeader(MessageBase.DestinationClientIdHeader, messageClient.ClientId);
messageClone.clientId = messageClient.ClientId;
handler.PushMessage(messageClone);
}
/*
IMessage messageClone = message.Clone() as IMessage;
messageClone.SetHeader(MessageBase.DestinationClientIdHeader, messageClient.ClientId);
messageClone.clientId = messageClient.ClientId;
messageClient.AddMessage(messageClone);
*/
}
else
{
if (log.IsWarnEnabled)
log.Warn("Push request received for the non-polling AMF endpoint '" + this.Id + "'");
}
}
public override int ClientLeaseTime
{
get
{
int timeout = this.GetMessageBroker().FlexClientSettings.TimeoutMinutes;
timeout = Math.Max(timeout, 1);//start with 1 minute timeout at least
if (this.ChannelDefinition.Properties.IsPollingEnabled)
{
int pollingInterval = this.ChannelDefinition.Properties.PollingIntervalSeconds / 60;
timeout = Math.Max(timeout, pollingInterval + 1);//set timout 1 minute longer then the polling interval in minutes
}
return timeout;
}
}
}
}
| |
//
// how to capture still images, video and audio using iOS AVFoundation and the AVCAptureSession
//
// This sample handles all of the low-level AVFoundation and capture graph setup required to capture and save media. This code also exposes the
// capture, configuration and notification capabilities in a more '.Netish' way of programming. The client code will not need to deal with threads, delegate classes
// buffer management, or objective-C data types but instead will create .NET objects and handle standard .NET events. The underlying iOS concepts and classes are detailed in
// the iOS developer online help (TP40010188-CH5-SW2).
//
// https://developer.apple.com/library/mac/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW2
//
// Enhancements, suggestions and bug reports can be sent to steve.millar@infinitekdev.com
//
using System;
using System.IO;
using MonoTouch.Dialog;
using Foundation;
using UIKit;
namespace MediaCapture
{
public class SettingsDialog
{
private Settings settings = null;
private RootElement menu = null;
// camera
private RadioElement fronCameraElement = null;
private RadioElement backCameraElement = null;
private RadioGroup cameraGroup = null;
private RootElement cameraElement = null;
private RadioElement lowResElement = null;
private RadioElement mediumResElement = null;
private RadioElement highResElement = null;
private RadioGroup resolutionGroup = null;
private RootElement resolutionElement = null;
// still image capture
private BooleanElement imageCaptureEnabledElement = null;
private RadioElement dontSaveImagesElement = null;
private RadioElement saveImagesToPhotoLibraryElement = null;
private RadioElement saveImagesToMyDocumentsElement = null;
private RadioGroup saveImageGroup = null;
private RootElement saveImageElement = null;
// media capture
private BooleanElement audioCaptureEnabledElement = null;
private BooleanElement videoCaptureEnabledElement = null;
private BooleanElement autoRecordNextMovieElement = null;
private RadioElement noLimitElement = null;
private RadioElement oneMinuteLimitElement = null;
private RadioElement fiveMinuteLimitElement = null;
private RadioElement tenMinuteLimitElement = null;
private RadioElement thirtyMinuteLimitElement = null;
private RadioGroup durationLimitGroup = null;
private RootElement durationElement = null;
// actions
private StringElement deleteMoviesElement = null;
private StringElement deleteImagesElement = null;
private SettingsDialog(){}
public SettingsDialog( Settings settings )
{
this.settings = settings;
}
public RootElement Menu
{
get
{
return buildSettingsRootMenu();
}
}
private RootElement buildSettingsRootMenu()
{
buildCameraSettingsElements();
buildImageCaptureSettingsElements();
buildMediaCaptureSettingsElements();
buildActionElements();
menu = new RootElement ("Settings")
{
new Section("Camera")
{
(Element)cameraElement,
(Element)resolutionElement,
},
new Section("Still Images")
{
(Element)imageCaptureEnabledElement,
(Element)saveImageElement,
},
new Section("Media")
{
audioCaptureEnabledElement,
videoCaptureEnabledElement,
autoRecordNextMovieElement,
(Element)durationElement,
},
new Section("Actions")
{
deleteMoviesElement,
deleteImagesElement,
}
};
return menu;
}
private void buildCameraSettingsElements()
{
// camera
fronCameraElement = new RadioElement("Front");
backCameraElement = new RadioElement("Back");
int index = (int)settings.Camera;
cameraGroup = new RadioGroup("CameraGroup", index );
cameraElement = new RootElement("Source Camera", cameraGroup)
{
new Section()
{
fronCameraElement,
backCameraElement
}
};
// resolution choices
lowResElement = new RadioElement("Low");
mediumResElement = new RadioElement("Medium");
highResElement = new RadioElement("High");
index = (int)settings.CaptureResolution;
resolutionGroup = new RadioGroup("ResolutionGroup", index );
resolutionElement = new RootElement("Resolution", resolutionGroup)
{
new Section()
{
lowResElement,
mediumResElement,
highResElement
}
};
}
private void buildImageCaptureSettingsElements()
{
imageCaptureEnabledElement = new BooleanElement("Capture", settings.ImageCaptureEnabled );
imageCaptureEnabledElement.ValueChanged += delegate
{
EnforceDependencies();
};
dontSaveImagesElement = new RadioElement("Don't Save");
saveImagesToPhotoLibraryElement = new RadioElement("Photo Library");
saveImagesToMyDocumentsElement = new RadioElement("My Documents");
int index = 0;
if ( settings.SaveCapturedImagesToPhotoLibrary )
{
index = 1;
}
else if ( settings.SaveCapturedImagesToMyDocuments )
{
index = 2;
}
saveImageGroup = new RadioGroup("SaveImagesGroup", index );
saveImageElement = new RootElement("Save To", saveImageGroup )
{
new Section()
{
dontSaveImagesElement,
saveImagesToPhotoLibraryElement,
saveImagesToMyDocumentsElement
}
};
}
private void buildMediaCaptureSettingsElements()
{
audioCaptureEnabledElement = new BooleanElement("Record Audio", settings.AudioCaptureEnabled );
audioCaptureEnabledElement.ValueChanged += delegate
{
EnforceDependencies();
};
videoCaptureEnabledElement = new BooleanElement("Record Video", settings.VideoCaptureEnabled );
videoCaptureEnabledElement.ValueChanged += delegate
{
EnforceDependencies();
};
autoRecordNextMovieElement = new BooleanElement("Loop Recordings", settings.AutoRecordNextMovie );
// duration choices
noLimitElement = new RadioElement("Unlimited");
oneMinuteLimitElement = new RadioElement("1 Minute");
fiveMinuteLimitElement = new RadioElement("5 Minutes");
tenMinuteLimitElement = new RadioElement("10 Minutes");
thirtyMinuteLimitElement = new RadioElement("30 Minutes");
int index = 0;
int duration = settings.MaxMovieDurationInSeconds;
if ( duration <= 0 ) { index = 0; }
else if ( duration <= 60 ) { index = 1; }
else if ( duration <= 300 ) { index = 2; }
else if ( duration <= 600 ) { index = 3; }
else if ( duration <= 1800 ) { index = 4; }
durationLimitGroup = new RadioGroup("DurationGroup", index );
durationElement = new RootElement("Maximum Time", durationLimitGroup )
{
new Section()
{
noLimitElement,
oneMinuteLimitElement,
fiveMinuteLimitElement,
tenMinuteLimitElement,
thirtyMinuteLimitElement
}
};
}
private void buildActionElements()
{
deleteMoviesElement = new StringElement("Delete Movies");
deleteMoviesElement.Tapped += delegate
{
try
{
Directory.Delete( Settings.VideoDataPath, true );
}
catch
{
}
};
deleteImagesElement = new StringElement("Delete Images");
deleteImagesElement.Tapped += delegate
{
try
{
Directory.Delete( Settings.ImageDataPath, true );
}
catch
{
}
};
}
public void EnforceDependencies()
{
try
{
// image capture save is not relevant if no images are being captured
if ( imageCaptureEnabledElement.Value == false )
{
saveImageGroup.Selected = 0;
}
saveImageElement.GetActiveCell().UserInteractionEnabled = imageCaptureEnabledElement.Value;
// looped recordings and duration are not relevant unless something is being recorded
bool isMediaCaptureEnebled = ( audioCaptureEnabledElement.Value || videoCaptureEnabledElement.Value );
if ( isMediaCaptureEnebled == false )
{
autoRecordNextMovieElement.Value = false;
}
autoRecordNextMovieElement.GetActiveCell().UserInteractionEnabled = isMediaCaptureEnebled;
durationElement.GetActiveCell().UserInteractionEnabled = isMediaCaptureEnebled;
}
catch
{
}
}
public Settings ResultSettings
{
get
{
Settings retVal = new Settings();
// camera
retVal.Camera = (CameraType)cameraGroup.Selected;
retVal.CaptureResolution = (Resolution)resolutionGroup.Selected;
// image capture
retVal.ImageCaptureEnabled = imageCaptureEnabledElement.Value;
retVal.SaveCapturedImagesToPhotoLibrary = (saveImageGroup.Selected == 1);
retVal.SaveCapturedImagesToMyDocuments = (saveImageGroup.Selected == 2);
// media capture
retVal.AudioCaptureEnabled = audioCaptureEnabledElement.Value;
retVal.VideoCaptureEnabled = videoCaptureEnabledElement.Value;
retVal.AutoRecordNextMovie = autoRecordNextMovieElement.Value;
// duration of recording
int numSeconds = 0;
int index = durationLimitGroup.Selected;
if ( index == 0 ) { numSeconds = 0; }
else if ( index == 1 ) { numSeconds = 60; }
else if ( index == 2 ) { numSeconds = 300; }
else if ( index == 3 ) { numSeconds = 600; }
else if ( index == 4 ) { numSeconds = 1800; }
retVal.MaxMovieDurationInSeconds = numSeconds;
return retVal;
}
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.HSSF.Record.Aggregates
{
using System;
using System.Collections;
using NPOI.HSSF.Record;
using NPOI.SS.Formula;
using NPOI.HSSF.Model;
using NPOI.SS.Formula.PTG;
/**
*
* Aggregate value records toGether. Things are easier to handle that way.
*
* @author andy
* @author Glen Stampoultzis (glens at apache.org)
* @author Jason Height (jheight at chariot dot net dot au)
*/
public class ValueRecordsAggregate
{
const int MAX_ROW_INDEX = 0XFFFF;
const int INDEX_NOT_SET = -1;
public const short sid = -1001; // 1000 clashes with RowRecordsAggregate
int firstcell = INDEX_NOT_SET;
int lastcell = INDEX_NOT_SET;
CellValueRecordInterface[][] records;
/** Creates a new instance of ValueRecordsAggregate */
public ValueRecordsAggregate():
this(INDEX_NOT_SET, INDEX_NOT_SET, new CellValueRecordInterface[30][]) // We start with 30 Rows.
{
}
private ValueRecordsAggregate(int firstCellIx, int lastCellIx, CellValueRecordInterface[][] pRecords)
{
firstcell = firstCellIx;
lastcell = lastCellIx;
records = pRecords;
}
public void InsertCell(CellValueRecordInterface cell)
{
int column = cell.Column;
int row = cell.Row;
if (row >= records.Length)
{
CellValueRecordInterface[][] oldRecords = records;
int newSize = oldRecords.Length * 2;
if (newSize < row + 1) newSize = row + 1;
records = new CellValueRecordInterface[newSize][];
Array.Copy(oldRecords, 0, records, 0, oldRecords.Length);
}
object objRowCells = records[row];
if (objRowCells == null)
{
int newSize = column + 1;
if (newSize < 10) newSize = 10;
objRowCells = new CellValueRecordInterface[newSize];
records[row] = (CellValueRecordInterface[])objRowCells;
}
CellValueRecordInterface[] rowCells = (CellValueRecordInterface[])objRowCells;
if (column >= rowCells.Length)
{
CellValueRecordInterface[] oldRowCells = rowCells;
int newSize = oldRowCells.Length * 2;
if (newSize < column + 1) newSize = column + 1;
// if(newSize>257) newSize=257; // activate?
rowCells = new CellValueRecordInterface[newSize];
Array.Copy(oldRowCells, 0, rowCells, 0, oldRowCells.Length);
records[row] = rowCells;
}
rowCells[column] = cell;
if ((column < firstcell) || (firstcell == -1))
{
firstcell = column;
}
if ((column > lastcell) || (lastcell == -1))
{
lastcell = column;
}
}
public void RemoveCell(CellValueRecordInterface cell)
{
if (cell == null)
{
throw new ArgumentException("cell must not be null");
}
int row = cell.Row;
if (row >= records.Length)
{
throw new Exception("cell row is out of range");
}
CellValueRecordInterface[] rowCells = records[row];
if (rowCells == null)
{
throw new Exception("cell row is already empty");
}
int column = cell.Column;
if (column >= rowCells.Length)
{
throw new Exception("cell column is out of range");
}
rowCells[column] = null;
}
public void RemoveAllCellsValuesForRow(int rowIndex)
{
if (rowIndex < 0 || rowIndex > MAX_ROW_INDEX)
{
throw new ArgumentException("Specified rowIndex " + rowIndex
+ " is outside the allowable range (0.." + MAX_ROW_INDEX + ")");
}
if (rowIndex >= records.Length)
{
// this can happen when the client code has created a row,
// and then removes/replaces it before adding any cells. (see bug 46312)
return;
}
records[rowIndex] = null;
}
public CellValueRecordInterface[] GetValueRecords()
{
ArrayList temp = new ArrayList();
for (int i = 0; i < records.Length; i++)
{
CellValueRecordInterface[] rowCells = records[i];
if (rowCells == null)
{
continue;
}
for (int j = 0; j < rowCells.Length; j++)
{
CellValueRecordInterface cell = rowCells[j];
if (cell != null)
{
temp.Add(cell);
}
}
}
return (CellValueRecordInterface[])temp.ToArray(typeof(CellValueRecordInterface));
}
public int PhysicalNumberOfCells
{
get
{
int count = 0;
for (int r = 0; r < records.Length; r++)
{
CellValueRecordInterface[] rowCells = records[r];
if (rowCells != null)
for (short c = 0; c < rowCells.Length; c++)
{
if (rowCells[c] != null) count++;
}
}
return count;
}
}
public int FirstCellNum
{
get
{
return firstcell;
}
}
public int LastCellNum
{
get
{
return lastcell;
}
}
public void AddMultipleBlanks(MulBlankRecord mbr)
{
for (int j = 0; j < mbr.NumColumns; j++)
{
BlankRecord br = new BlankRecord();
br.Column = j + mbr.FirstColumn;
br.Row = mbr.Row;
br.XFIndex = (mbr.GetXFAt(j));
InsertCell(br);
}
}
private MulBlankRecord CreateMBR(CellValueRecordInterface[] cellValues, int startIx, int nBlank)
{
short[] xfs = new short[nBlank];
for (int i = 0; i < xfs.Length; i++)
{
xfs[i] = ((BlankRecord)cellValues[startIx + i]).XFIndex;
}
int rowIx = cellValues[startIx].Row;
return new MulBlankRecord(rowIx, startIx, xfs);
}
public void Construct(CellValueRecordInterface rec, RecordStream rs, SharedValueManager sfh)
{
if (rec is FormulaRecord)
{
FormulaRecord formulaRec = (FormulaRecord)rec;
// read optional cached text value
StringRecord cachedText=null;
Type nextClass = rs.PeekNextClass();
if (nextClass == typeof(StringRecord))
{
cachedText = (StringRecord)rs.GetNext();
}
else
{
cachedText = null;
}
InsertCell(new FormulaRecordAggregate(formulaRec, cachedText, sfh));
}
else
{
InsertCell(rec);
}
}
/**
* Sometimes the shared formula flag "seems" to be erroneously Set, in which case there is no
* call to <c>SharedFormulaRecord.ConvertSharedFormulaRecord</c> and hence the
* <c>ParsedExpression</c> field of this <c>FormulaRecord</c> will not Get updated.<br/>
* As it turns out, this is not a problem, because in these circumstances, the existing value
* for <c>ParsedExpression</c> is perfectly OK.<p/>
*
* This method may also be used for Setting breakpoints to help diagnose Issues regarding the
* abnormally-Set 'shared formula' flags.
* (see TestValueRecordsAggregate.testSpuriousSharedFormulaFlag()).<p/>
*
* The method currently does nothing but do not delete it without Finding a nice home for this
* comment.
*/
static void HandleMissingSharedFormulaRecord(FormulaRecord formula)
{
// could log an info message here since this is a fairly Unusual occurrence.
}
/** Tallies a count of the size of the cell records
* that are attached to the rows in the range specified.
*/
public int GetRowCellBlockSize(int startRow, int endRow)
{
MyEnumerator itr = new MyEnumerator(ref records,startRow, endRow);
int size = 0;
while (itr.MoveNext())
{
CellValueRecordInterface cell = (CellValueRecordInterface)itr.Current;
int row = cell.Row;
if (row > endRow)
break;
if ((row >= startRow) && (row <= endRow))
size += ((RecordBase)cell).RecordSize;
}
return size;
}
/** Returns true if the row has cells attached to it */
public bool RowHasCells(int row)
{
if (row > records.Length - 1) //previously this said row > records.Length which means if
return false; // if records.Length == 60 and I pass "60" here I Get array out of bounds
CellValueRecordInterface[] rowCells = records[row]; //because a 60 Length array has the last index = 59
if (rowCells == null) return false;
for (int col = 0; col < rowCells.Length; col++)
{
if (rowCells[col] != null) return true;
}
return false;
}
public void UpdateFormulasAfterRowShift(FormulaShifter shifter, int currentExternSheetIndex)
{
for (int i = 0; i < records.Length; i++)
{
CellValueRecordInterface[] rowCells = records[i];
if (rowCells == null)
{
continue;
}
for (int j = 0; j < rowCells.Length; j++)
{
CellValueRecordInterface cell = rowCells[j];
if (cell is FormulaRecordAggregate)
{
FormulaRecordAggregate fra = (FormulaRecordAggregate)cell;
Ptg[] ptgs = fra.FormulaTokens; // needs clone() inside this getter?
Ptg[] ptgs2 = ((FormulaRecordAggregate)cell).FormulaRecord.ParsedExpression; // needs clone() inside this getter?
if (shifter.AdjustFormula(ptgs, currentExternSheetIndex))
{
fra.SetParsedExpression(ptgs);
}
}
}
}
}
public void VisitCellsForRow(int rowIndex, RecordVisitor rv)
{
CellValueRecordInterface[] rowCells = records[rowIndex];
if (rowCells == null)
{
throw new ArgumentException("Row [" + rowIndex + "] is empty");
}
for (int i = 0; i < rowCells.Length; i++)
{
RecordBase cvr = (RecordBase)rowCells[i];
if (cvr == null)
{
continue;
}
int nBlank = CountBlanks(rowCells, i);
if (nBlank > 1)
{
rv.VisitRecord(CreateMBR(rowCells, i, nBlank));
i += nBlank - 1;
}
else if (cvr is RecordAggregate)
{
RecordAggregate agg = (RecordAggregate)cvr;
agg.VisitContainedRecords(rv);
}
else
{
rv.VisitRecord((Record)cvr);
}
}
}
static int CountBlanks(CellValueRecordInterface[] rowCellValues, int startIx)
{
int i = startIx;
while (i < rowCellValues.Length)
{
CellValueRecordInterface cvr = rowCellValues[i];
if (!(cvr is BlankRecord))
{
break;
}
i++;
}
return i - startIx;
}
/** Serializes the cells that are allocated to a certain row range*/
public int SerializeCellRow(int row, int offset, byte[] data)
{
MyEnumerator itr = new MyEnumerator(ref records,row, row);
int pos = offset;
while (itr.MoveNext())
{
CellValueRecordInterface cell = (CellValueRecordInterface)itr.Current;
if (cell.Row != row)
break;
pos += ((RecordBase)cell).Serialize(pos, data);
}
return pos - offset;
}
public IEnumerator GetEnumerator()
{
return new MyEnumerator(ref records);
}
private class MyEnumerator : IEnumerator
{
short nextColumn = -1;
int nextRow, lastRow;
CellValueRecordInterface[][] records;
public MyEnumerator(ref CellValueRecordInterface[][] _records)
{
this.records = _records;
this.nextRow = 0;
this.lastRow = _records.Length - 1;
//FindNext();
}
public MyEnumerator(ref CellValueRecordInterface[][] _records,int firstRow, int lastRow)
{
this.records = _records;
this.nextRow = firstRow;
this.lastRow = lastRow;
//FindNext();
}
public bool MoveNext()
{
FindNext();
return nextRow <= lastRow; ;
}
public Object Current
{
get
{
Object o = this.records[nextRow][nextColumn];
return o;
}
}
public void Remove()
{
throw new InvalidOperationException("gibt's noch nicht");
}
private void FindNext()
{
nextColumn++;
for (; nextRow <= lastRow; nextRow++)
{
//previously this threw array out of bounds...
CellValueRecordInterface[] rowCells = (nextRow < records.Length) ? records[nextRow] : null;
if (rowCells == null)
{ // This row is empty
nextColumn = 0;
continue;
}
for (; nextColumn < rowCells.Length; nextColumn++)
{
if (rowCells[nextColumn] != null) return;
}
nextColumn = 0;
}
}
public void Reset()
{
nextColumn = -1;
nextRow = 0;
}
}
}
}
| |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Text;
using System.Collections.Generic;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
/// <summary>
///
/// </summary>
[Flags]
public enum FriendRights : int
{
/// <summary>The avatar has no rights</summary>
None = 0,
/// <summary>The avatar can see the online status of the target avatar</summary>
CanSeeOnline = 1,
/// <summary>The avatar can see the location of the target avatar on the map</summary>
CanSeeOnMap = 2,
/// <summary>The avatar can modify the ojects of the target avatar </summary>
CanModifyObjects = 4
}
/// <summary>
/// This class holds information about an avatar in the friends list. There are two ways
/// to interface to this class. The first is through the set of boolean properties. This is the typical
/// way clients of this class will use it. The second interface is through two bitflag properties,
/// TheirFriendsRights and MyFriendsRights
/// </summary>
public class FriendInfo
{
private UUID m_id;
private string m_name;
private bool m_isOnline;
private bool m_canSeeMeOnline;
private bool m_canSeeMeOnMap;
private bool m_canModifyMyObjects;
private bool m_canSeeThemOnline;
private bool m_canSeeThemOnMap;
private bool m_canModifyTheirObjects;
#region Properties
/// <summary>
/// System ID of the avatar
/// </summary>
public UUID UUID { get { return m_id; } }
/// <summary>
/// full name of the avatar
/// </summary>
public string Name
{
get { return m_name; }
set { m_name = value; }
}
/// <summary>
/// True if the avatar is online
/// </summary>
public bool IsOnline
{
get { return m_isOnline; }
set { m_isOnline = value; }
}
/// <summary>
/// True if the friend can see if I am online
/// </summary>
public bool CanSeeMeOnline
{
get { return m_canSeeMeOnline; }
set
{
m_canSeeMeOnline = value;
// if I can't see them online, then I can't see them on the map
if (!m_canSeeMeOnline)
m_canSeeMeOnMap = false;
}
}
/// <summary>
/// True if the friend can see me on the map
/// </summary>
public bool CanSeeMeOnMap
{
get { return m_canSeeMeOnMap; }
set
{
// if I can't see them online, then I can't see them on the map
if (m_canSeeMeOnline)
m_canSeeMeOnMap = value;
}
}
/// <summary>
/// True if the freind can modify my objects
/// </summary>
public bool CanModifyMyObjects
{
get { return m_canModifyMyObjects; }
set { m_canModifyMyObjects = value; }
}
/// <summary>
/// True if I can see if my friend is online
/// </summary>
public bool CanSeeThemOnline { get { return m_canSeeThemOnline; } }
/// <summary>
/// True if I can see if my friend is on the map
/// </summary>
public bool CanSeeThemOnMap { get { return m_canSeeThemOnMap; } }
/// <summary>
/// True if I can modify my friend's objects
/// </summary>
public bool CanModifyTheirObjects { get { return m_canModifyTheirObjects; } }
/// <summary>
/// My friend's rights represented as bitmapped flags
/// </summary>
public FriendRights TheirFriendRights
{
get
{
FriendRights results = FriendRights.None;
if (m_canSeeMeOnline)
results |= FriendRights.CanSeeOnline;
if (m_canSeeMeOnMap)
results |= FriendRights.CanSeeOnMap;
if (m_canModifyMyObjects)
results |= FriendRights.CanModifyObjects;
return results;
}
set
{
m_canSeeMeOnline = (value & FriendRights.CanSeeOnline) != 0;
m_canSeeMeOnMap = (value & FriendRights.CanSeeOnMap) != 0;
m_canModifyMyObjects = (value & FriendRights.CanModifyObjects) != 0;
}
}
/// <summary>
/// My rights represented as bitmapped flags
/// </summary>
public FriendRights MyFriendRights
{
get
{
FriendRights results = FriendRights.None;
if (m_canSeeThemOnline)
results |= FriendRights.CanSeeOnline;
if (m_canSeeThemOnMap)
results |= FriendRights.CanSeeOnMap;
if (m_canModifyTheirObjects)
results |= FriendRights.CanModifyObjects;
return results;
}
set
{
m_canSeeThemOnline = (value & FriendRights.CanSeeOnline) != 0;
m_canSeeThemOnMap = (value & FriendRights.CanSeeOnMap) != 0;
m_canModifyTheirObjects = (value & FriendRights.CanModifyObjects) != 0;
}
}
#endregion Properties
/// <summary>
/// Used internally when building the initial list of friends at login time
/// </summary>
/// <param name="id">System ID of the avatar being prepesented</param>
/// <param name="theirRights">Rights the friend has to see you online and to modify your objects</param>
/// <param name="myRights">Rights you have to see your friend online and to modify their objects</param>
internal FriendInfo(UUID id, FriendRights theirRights, FriendRights myRights)
{
m_id = id;
m_canSeeMeOnline = (theirRights & FriendRights.CanSeeOnline) != 0;
m_canSeeMeOnMap = (theirRights & FriendRights.CanSeeOnMap) != 0;
m_canModifyMyObjects = (theirRights & FriendRights.CanModifyObjects) != 0;
m_canSeeThemOnline = (myRights & FriendRights.CanSeeOnline) != 0;
m_canSeeThemOnMap = (myRights & FriendRights.CanSeeOnMap) != 0;
m_canModifyTheirObjects = (myRights & FriendRights.CanModifyObjects) != 0;
}
/// <summary>
/// FriendInfo represented as a string
/// </summary>
/// <returns>A string reprentation of both my rights and my friends rights</returns>
public override string ToString()
{
if (!String.IsNullOrEmpty(m_name))
return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_name, TheirFriendRights,
MyFriendRights);
else
return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_id, TheirFriendRights,
MyFriendRights);
}
}
/// <summary>
/// This class is used to add and remove avatars from your friends list and to manage their permission.
/// </summary>
public class FriendsManager
{
#region Delegates
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendOnline;
/// <summary>Raises the FriendOnline event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendOnline(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendOnline;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendOnlineLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list comes online</summary>
public event EventHandler<FriendInfoEventArgs> FriendOnline
{
add { lock (m_FriendOnlineLock) { m_FriendOnline += value; } }
remove { lock (m_FriendOnlineLock) { m_FriendOnline -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendOffline;
/// <summary>Raises the FriendOffline event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendOffline(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendOffline;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendOfflineLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list goes offline</summary>
public event EventHandler<FriendInfoEventArgs> FriendOffline
{
add { lock (m_FriendOfflineLock) { m_FriendOffline += value; } }
remove { lock (m_FriendOfflineLock) { m_FriendOffline -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendRights;
/// <summary>Raises the FriendRightsUpdate event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendRights(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendRights;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendRightsLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list grants or revokes permissions</summary>
public event EventHandler<FriendInfoEventArgs> FriendRightsUpdate
{
add { lock (m_FriendRightsLock) { m_FriendRights += value; } }
remove { lock (m_FriendRightsLock) { m_FriendRights -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendNamesEventArgs> m_FriendNames;
/// <summary>Raises the FriendNames event</summary>
/// <param name="e">A FriendNamesEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendNames(FriendNamesEventArgs e)
{
EventHandler<FriendNamesEventArgs> handler = m_FriendNames;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendNamesLock = new object();
/// <summary>Raised when the simulator sends us the names on our friends list</summary>
public event EventHandler<FriendNamesEventArgs> FriendNames
{
add { lock (m_FriendNamesLock) { m_FriendNames += value; } }
remove { lock (m_FriendNamesLock) { m_FriendNames -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipOfferedEventArgs> m_FriendshipOffered;
/// <summary>Raises the FriendshipOffered event</summary>
/// <param name="e">A FriendshipOfferedEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipOffered(FriendshipOfferedEventArgs e)
{
EventHandler<FriendshipOfferedEventArgs> handler = m_FriendshipOffered;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipOfferedLock = new object();
/// <summary>Raised when the simulator sends notification another agent is offering us friendship</summary>
public event EventHandler<FriendshipOfferedEventArgs> FriendshipOffered
{
add { lock (m_FriendshipOfferedLock) { m_FriendshipOffered += value; } }
remove { lock (m_FriendshipOfferedLock) { m_FriendshipOffered -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipResponseEventArgs> m_FriendshipResponse;
/// <summary>Raises the FriendshipResponse event</summary>
/// <param name="e">A FriendshipResponseEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipResponse(FriendshipResponseEventArgs e)
{
EventHandler<FriendshipResponseEventArgs> handler = m_FriendshipResponse;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipResponseLock = new object();
/// <summary>Raised when a request we sent to friend another agent is accepted or declined</summary>
public event EventHandler<FriendshipResponseEventArgs> FriendshipResponse
{
add { lock (m_FriendshipResponseLock) { m_FriendshipResponse += value; } }
remove { lock (m_FriendshipResponseLock) { m_FriendshipResponse -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipTerminatedEventArgs> m_FriendshipTerminated;
/// <summary>Raises the FriendshipTerminated event</summary>
/// <param name="e">A FriendshipTerminatedEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipTerminated(FriendshipTerminatedEventArgs e)
{
EventHandler<FriendshipTerminatedEventArgs> handler = m_FriendshipTerminated;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipTerminatedLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list has terminated
/// our friendship</summary>
public event EventHandler<FriendshipTerminatedEventArgs> FriendshipTerminated
{
add { lock (m_FriendshipTerminatedLock) { m_FriendshipTerminated += value; } }
remove { lock (m_FriendshipTerminatedLock) { m_FriendshipTerminated -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendFoundReplyEventArgs> m_FriendFound;
/// <summary>Raises the FriendFoundReply event</summary>
/// <param name="e">A FriendFoundReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendFoundReply(FriendFoundReplyEventArgs e)
{
EventHandler<FriendFoundReplyEventArgs> handler = m_FriendFound;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendFoundLock = new object();
/// <summary>Raised when the simulator sends the location of a friend we have
/// requested map location info for</summary>
public event EventHandler<FriendFoundReplyEventArgs> FriendFoundReply
{
add { lock (m_FriendFoundLock) { m_FriendFound += value; } }
remove { lock (m_FriendFoundLock) { m_FriendFound -= value; } }
}
#endregion Delegates
#region Events
#endregion Events
private GridClient Client;
/// <summary>
/// A dictionary of key/value pairs containing known friends of this avatar.
///
/// The Key is the <seealso cref="UUID"/> of the friend, the value is a <seealso cref="FriendInfo"/>
/// object that contains detailed information including permissions you have and have given to the friend
/// </summary>
public InternalDictionary<UUID, FriendInfo> FriendList = new InternalDictionary<UUID, FriendInfo>();
/// <summary>
/// A Dictionary of key/value pairs containing current pending frienship offers.
///
/// The key is the <seealso cref="UUID"/> of the avatar making the request,
/// the value is the <seealso cref="UUID"/> of the request which is used to accept
/// or decline the friendship offer
/// </summary>
public InternalDictionary<UUID, UUID> FriendRequests = new InternalDictionary<UUID, UUID>();
/// <summary>
/// Internal constructor
/// </summary>
/// <param name="client">A reference to the GridClient Object</param>
internal FriendsManager(GridClient client)
{
Client = client;
Client.Network.LoginProgress += Network_OnConnect;
Client.Avatars.UUIDNameReply += new EventHandler<UUIDNameReplyEventArgs>(Avatars_OnAvatarNames);
Client.Self.IM += Self_IM;
Client.Network.RegisterCallback(PacketType.OnlineNotification, OnlineNotificationHandler);
Client.Network.RegisterCallback(PacketType.OfflineNotification, OfflineNotificationHandler);
Client.Network.RegisterCallback(PacketType.ChangeUserRights, ChangeUserRightsHandler);
Client.Network.RegisterCallback(PacketType.TerminateFriendship, TerminateFriendshipHandler);
Client.Network.RegisterCallback(PacketType.FindAgent, OnFindAgentReplyHandler);
Client.Network.RegisterLoginResponseCallback(new NetworkManager.LoginResponseCallback(Network_OnLoginResponse),
new string[] { "buddy-list" });
}
#region Public Methods
/// <summary>
/// Accept a friendship request
/// </summary>
/// <param name="fromAgentID">agentID of avatatar to form friendship with</param>
/// <param name="imSessionID">imSessionID of the friendship request message</param>
public void AcceptFriendship(UUID fromAgentID, UUID imSessionID)
{
UUID callingCardFolder = Client.Inventory.FindFolderForType(AssetType.CallingCard);
AcceptFriendshipPacket request = new AcceptFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.TransactionBlock.TransactionID = imSessionID;
request.FolderData = new AcceptFriendshipPacket.FolderDataBlock[1];
request.FolderData[0] = new AcceptFriendshipPacket.FolderDataBlock();
request.FolderData[0].FolderID = callingCardFolder;
Client.Network.SendPacket(request);
FriendInfo friend = new FriendInfo(fromAgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
if (!FriendList.ContainsKey(fromAgentID))
FriendList.Add(friend.UUID, friend);
if (FriendRequests.ContainsKey(fromAgentID))
FriendRequests.Remove(fromAgentID);
Client.Avatars.RequestAvatarName(fromAgentID);
}
/// <summary>
/// Decline a friendship request
/// </summary>
/// <param name="fromAgentID"><seealso cref="UUID"/> of friend</param>
/// <param name="imSessionID">imSessionID of the friendship request message</param>
public void DeclineFriendship(UUID fromAgentID, UUID imSessionID)
{
DeclineFriendshipPacket request = new DeclineFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.TransactionBlock.TransactionID = imSessionID;
Client.Network.SendPacket(request);
if (FriendRequests.ContainsKey(fromAgentID))
FriendRequests.Remove(fromAgentID);
}
/// <summary>
/// Overload: Offer friendship to an avatar.
/// </summary>
/// <param name="agentID">System ID of the avatar you are offering friendship to</param>
public void OfferFriendship(UUID agentID)
{
OfferFriendship(agentID, "Do ya wanna be my buddy?");
}
/// <summary>
/// Offer friendship to an avatar.
/// </summary>
/// <param name="agentID">System ID of the avatar you are offering friendship to</param>
/// <param name="message">A message to send with the request</param>
public void OfferFriendship(UUID agentID, string message)
{
Client.Self.InstantMessage(Client.Self.Name,
agentID,
message,
UUID.Random(),
InstantMessageDialog.FriendshipOffered,
InstantMessageOnline.Offline,
Client.Self.SimPosition,
Client.Network.CurrentSim.ID,
null);
}
/// <summary>
/// Terminate a friendship with an avatar
/// </summary>
/// <param name="agentID">System ID of the avatar you are terminating the friendship with</param>
public void TerminateFriendship(UUID agentID)
{
if (FriendList.ContainsKey(agentID))
{
TerminateFriendshipPacket request = new TerminateFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.ExBlock.OtherID = agentID;
Client.Network.SendPacket(request);
if (FriendList.ContainsKey(agentID))
FriendList.Remove(agentID);
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
private void TerminateFriendshipHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
TerminateFriendshipPacket itsOver = (TerminateFriendshipPacket)packet;
string name = String.Empty;
if (FriendList.ContainsKey(itsOver.ExBlock.OtherID))
{
name = FriendList[itsOver.ExBlock.OtherID].Name;
FriendList.Remove(itsOver.ExBlock.OtherID);
}
if (m_FriendshipTerminated != null)
{
OnFriendshipTerminated(new FriendshipTerminatedEventArgs(itsOver.ExBlock.OtherID, name));
}
}
/// <summary>
/// Change the rights of a friend avatar.
/// </summary>
/// <param name="friendID">the <seealso cref="UUID"/> of the friend</param>
/// <param name="rights">the new rights to give the friend</param>
/// <remarks>This method will implicitly set the rights to those passed in the rights parameter.</remarks>
public void GrantRights(UUID friendID, FriendRights rights)
{
GrantUserRightsPacket request = new GrantUserRightsPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.Rights = new GrantUserRightsPacket.RightsBlock[1];
request.Rights[0] = new GrantUserRightsPacket.RightsBlock();
request.Rights[0].AgentRelated = friendID;
request.Rights[0].RelatedRights = (int)rights;
Client.Network.SendPacket(request);
}
/// <summary>
/// Use to map a friends location on the grid.
/// </summary>
/// <param name="friendID">Friends UUID to find</param>
/// <remarks><seealso cref="E:OnFriendFound"/></remarks>
public void MapFriend(UUID friendID)
{
FindAgentPacket stalk = new FindAgentPacket();
stalk.AgentBlock.Hunter = Client.Self.AgentID;
stalk.AgentBlock.Prey = friendID;
stalk.AgentBlock.SpaceIP = 0; // Will be filled in by the simulator
stalk.LocationBlock = new FindAgentPacket.LocationBlockBlock[1];
stalk.LocationBlock[0] = new FindAgentPacket.LocationBlockBlock();
stalk.LocationBlock[0].GlobalX = 0.0; // Filled in by the simulator
stalk.LocationBlock[0].GlobalY = 0.0;
Client.Network.SendPacket(stalk);
}
/// <summary>
/// Use to track a friends movement on the grid
/// </summary>
/// <param name="friendID">Friends Key</param>
public void TrackFriend(UUID friendID)
{
TrackAgentPacket stalk = new TrackAgentPacket();
stalk.AgentData.AgentID = Client.Self.AgentID;
stalk.AgentData.SessionID = Client.Self.SessionID;
stalk.TargetData.PreyID = friendID;
Client.Network.SendPacket(stalk);
}
/// <summary>
/// Ask for a notification of friend's online status
/// </summary>
/// <param name="friendID">Friend's UUID</param>
public void RequestOnlineNotification(UUID friendID)
{
GenericMessagePacket gmp = new GenericMessagePacket();
gmp.AgentData.AgentID = Client.Self.AgentID;
gmp.AgentData.SessionID = Client.Self.SessionID;
gmp.AgentData.TransactionID = UUID.Zero;
gmp.MethodData.Method = Utils.StringToBytes("requestonlinenotification");
gmp.MethodData.Invoice = UUID.Zero;
gmp.ParamList = new GenericMessagePacket.ParamListBlock[1];
gmp.ParamList[0] = new GenericMessagePacket.ParamListBlock();
gmp.ParamList[0].Parameter = Utils.StringToBytes(friendID.ToString());
Client.Network.SendPacket(gmp);
}
#endregion
#region Internal events
private void Network_OnConnect(object sender, LoginProgressEventArgs e)
{
if (e.Status != LoginStatus.Success)
{
return;
}
List<UUID> names = new List<UUID>();
if (FriendList.Count > 0)
{
FriendList.ForEach(
delegate(KeyValuePair<UUID, FriendInfo> kvp)
{
if (String.IsNullOrEmpty(kvp.Value.Name))
names.Add(kvp.Key);
}
);
Client.Avatars.RequestAvatarNames(names);
}
}
/// <summary>
/// This handles the asynchronous response of a RequestAvatarNames call.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">names cooresponding to the the list of IDs sent the the RequestAvatarNames call.</param>
private void Avatars_OnAvatarNames(object sender, UUIDNameReplyEventArgs e)
{
Dictionary<UUID, string> newNames = new Dictionary<UUID, string>();
foreach (KeyValuePair<UUID, string> kvp in e.Names)
{
FriendInfo friend;
lock (FriendList.Dictionary)
{
if (FriendList.TryGetValue(kvp.Key, out friend))
{
if (friend.Name == null)
newNames.Add(kvp.Key, e.Names[kvp.Key]);
friend.Name = e.Names[kvp.Key];
FriendList[kvp.Key] = friend;
}
}
}
if (newNames.Count > 0 && m_FriendNames != null)
{
OnFriendNames(new FriendNamesEventArgs(newNames));
}
}
#endregion
#region Packet Handlers
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void OnlineNotificationHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.OnlineNotification)
{
OnlineNotificationPacket notification = ((OnlineNotificationPacket)packet);
foreach (OnlineNotificationPacket.AgentBlockBlock block in notification.AgentBlock)
{
FriendInfo friend;
lock (FriendList.Dictionary)
{
if (!FriendList.ContainsKey(block.AgentID))
{
friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
FriendList.Add(block.AgentID, friend);
}
else
{
friend = FriendList[block.AgentID];
}
}
bool doNotify = !friend.IsOnline;
friend.IsOnline = true;
if (m_FriendOnline != null && doNotify)
{
OnFriendOnline(new FriendInfoEventArgs(friend));
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void OfflineNotificationHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.OfflineNotification)
{
OfflineNotificationPacket notification = (OfflineNotificationPacket)packet;
foreach (OfflineNotificationPacket.AgentBlockBlock block in notification.AgentBlock)
{
FriendInfo friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline);
lock (FriendList.Dictionary)
{
if (!FriendList.Dictionary.ContainsKey(block.AgentID))
FriendList.Dictionary[block.AgentID] = friend;
friend = FriendList.Dictionary[block.AgentID];
}
friend.IsOnline = false;
if (m_FriendOffline != null)
{
OnFriendOffline(new FriendInfoEventArgs(friend));
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
private void ChangeUserRightsHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.ChangeUserRights)
{
FriendInfo friend;
ChangeUserRightsPacket rights = (ChangeUserRightsPacket)packet;
foreach (ChangeUserRightsPacket.RightsBlock block in rights.Rights)
{
FriendRights newRights = (FriendRights)block.RelatedRights;
if (FriendList.TryGetValue(block.AgentRelated, out friend))
{
friend.TheirFriendRights = newRights;
if (m_FriendRights != null)
{
OnFriendRights(new FriendInfoEventArgs(friend));
}
}
else if (block.AgentRelated == Client.Self.AgentID)
{
if (FriendList.TryGetValue(rights.AgentData.AgentID, out friend))
{
friend.MyFriendRights = newRights;
if (m_FriendRights != null)
{
OnFriendRights(new FriendInfoEventArgs(friend));
}
}
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
public void OnFindAgentReplyHandler(object sender, PacketReceivedEventArgs e)
{
if (m_FriendFound != null)
{
Packet packet = e.Packet;
FindAgentPacket reply = (FindAgentPacket)packet;
float x, y;
UUID prey = reply.AgentBlock.Prey;
ulong regionHandle = Helpers.GlobalPosToRegionHandle((float)reply.LocationBlock[0].GlobalX,
(float)reply.LocationBlock[0].GlobalY, out x, out y);
Vector3 xyz = new Vector3(x, y, 0f);
OnFriendFoundReply(new FriendFoundReplyEventArgs(prey, regionHandle, xyz));
}
}
#endregion
private void Self_IM(object sender, InstantMessageEventArgs e)
{
if (e.IM.Dialog == InstantMessageDialog.FriendshipOffered)
{
if (m_FriendshipOffered != null)
{
if (FriendRequests.ContainsKey(e.IM.FromAgentID))
FriendRequests[e.IM.FromAgentID] = e.IM.IMSessionID;
else
FriendRequests.Add(e.IM.FromAgentID, e.IM.IMSessionID);
OnFriendshipOffered(new FriendshipOfferedEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.IMSessionID));
}
}
else if (e.IM.Dialog == InstantMessageDialog.FriendshipAccepted)
{
FriendInfo friend = new FriendInfo(e.IM.FromAgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
friend.Name = e.IM.FromAgentName;
lock (FriendList.Dictionary) FriendList[friend.UUID] = friend;
if (m_FriendshipResponse != null)
{
OnFriendshipResponse(new FriendshipResponseEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, true));
}
RequestOnlineNotification(e.IM.FromAgentID);
}
else if (e.IM.Dialog == InstantMessageDialog.FriendshipDeclined)
{
if (m_FriendshipResponse != null)
{
OnFriendshipResponse(new FriendshipResponseEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, false));
}
}
}
/// <summary>
/// Populate FriendList <seealso cref="InternalDictionary"/> with data from the login reply
/// </summary>
/// <param name="loginSuccess">true if login was successful</param>
/// <param name="redirect">true if login request is requiring a redirect</param>
/// <param name="message">A string containing the response to the login request</param>
/// <param name="reason">A string containing the reason for the request</param>
/// <param name="replyData">A <seealso cref="LoginResponseData"/> object containing the decoded
/// reply from the login server</param>
private void Network_OnLoginResponse(bool loginSuccess, bool redirect, string message, string reason,
LoginResponseData replyData)
{
int uuidLength = UUID.Zero.ToString().Length;
if (loginSuccess && replyData.BuddyList != null)
{
foreach (BuddyListEntry buddy in replyData.BuddyList)
{
UUID bubid;
string id = buddy.buddy_id.Length > uuidLength ? buddy.buddy_id.Substring(0, uuidLength) : buddy.buddy_id;
if (UUID.TryParse(id, out bubid))
{
lock (FriendList.Dictionary)
{
if (!FriendList.ContainsKey(bubid))
{
FriendList[bubid] = new FriendInfo(bubid,
(FriendRights)buddy.buddy_rights_given,
(FriendRights)buddy.buddy_rights_has);
}
}
}
}
}
}
}
#region EventArgs
/// <summary>Contains information on a member of our friends list</summary>
public class FriendInfoEventArgs : EventArgs
{
private readonly FriendInfo m_Friend;
/// <summary>Get the FriendInfo</summary>
public FriendInfo Friend { get { return m_Friend; } }
/// <summary>
/// Construct a new instance of the FriendInfoEventArgs class
/// </summary>
/// <param name="friend">The FriendInfo</param>
public FriendInfoEventArgs(FriendInfo friend)
{
this.m_Friend = friend;
}
}
/// <summary>Contains Friend Names</summary>
public class FriendNamesEventArgs : EventArgs
{
private readonly Dictionary<UUID, string> m_Names;
/// <summary>A dictionary where the Key is the ID of the Agent,
/// and the Value is a string containing their name</summary>
public Dictionary<UUID, string> Names { get { return m_Names; } }
/// <summary>
/// Construct a new instance of the FriendNamesEventArgs class
/// </summary>
/// <param name="names">A dictionary where the Key is the ID of the Agent,
/// and the Value is a string containing their name</param>
public FriendNamesEventArgs(Dictionary<UUID, string> names)
{
this.m_Names = names;
}
}
/// <summary>Sent when another agent requests a friendship with our agent</summary>
public class FriendshipOfferedEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
private readonly UUID m_SessionID;
/// <summary>Get the ID of the agent requesting friendship</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent requesting friendship</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>Get the ID of the session, used in accepting or declining the
/// friendship offer</summary>
public UUID SessionID { get { return m_SessionID; } }
/// <summary>
/// Construct a new instance of the FriendshipOfferedEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent requesting friendship</param>
/// <param name="agentName">The name of the agent requesting friendship</param>
/// <param name="imSessionID">The ID of the session, used in accepting or declining the
/// friendship offer</param>
public FriendshipOfferedEventArgs(UUID agentID, string agentName, UUID imSessionID)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
this.m_SessionID = imSessionID;
}
}
/// <summary>A response containing the results of our request to form a friendship with another agent</summary>
public class FriendshipResponseEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
private readonly bool m_Accepted;
/// <summary>Get the ID of the agent we requested a friendship with</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent we requested a friendship with</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>true if the agent accepted our friendship offer</summary>
public bool Accepted { get { return m_Accepted; } }
/// <summary>
/// Construct a new instance of the FriendShipResponseEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent we requested a friendship with</param>
/// <param name="agentName">The name of the agent we requested a friendship with</param>
/// <param name="accepted">true if the agent accepted our friendship offer</param>
public FriendshipResponseEventArgs(UUID agentID, string agentName, bool accepted)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
this.m_Accepted = accepted;
}
}
/// <summary>Contains data sent when a friend terminates a friendship with us</summary>
public class FriendshipTerminatedEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
/// <summary>Get the ID of the agent that terminated the friendship with us</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent that terminated the friendship with us</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>
/// Construct a new instance of the FrindshipTerminatedEventArgs class
/// </summary>
/// <param name="agentID">The ID of the friend who terminated the friendship with us</param>
/// <param name="agentName">The name of the friend who terminated the friendship with us</param>
public FriendshipTerminatedEventArgs(UUID agentID, string agentName)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
}
}
/// <summary>
/// Data sent in response to a <see cref="FindFriend"/> request which contains the information to allow us to map the friends location
/// </summary>
public class FriendFoundReplyEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly ulong m_RegionHandle;
private readonly Vector3 m_Location;
/// <summary>Get the ID of the agent we have received location information for</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the region handle where our mapped friend is located</summary>
public ulong RegionHandle { get { return m_RegionHandle; } }
/// <summary>Get the simulator local position where our friend is located</summary>
public Vector3 Location { get { return m_Location; } }
/// <summary>
/// Construct a new instance of the FriendFoundReplyEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent we have requested location information for</param>
/// <param name="regionHandle">The region handle where our friend is located</param>
/// <param name="location">The simulator local position our friend is located</param>
public FriendFoundReplyEventArgs(UUID agentID, ulong regionHandle, Vector3 location)
{
this.m_AgentID = agentID;
this.m_RegionHandle = regionHandle;
this.m_Location = location;
}
}
#endregion
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareNotGreaterThanDouble()
{
var test = new SimpleBinaryOpTest__CompareNotGreaterThanDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareNotGreaterThanDouble
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Double[] inArray1, Double[] inArray2, Double[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Double>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Double>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Double>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Double, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Double, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Double> _fld1;
public Vector128<Double> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref testStruct._fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__CompareNotGreaterThanDouble testClass)
{
var result = Sse2.CompareNotGreaterThan(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__CompareNotGreaterThanDouble testClass)
{
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareNotGreaterThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Double>>() / sizeof(Double);
private static Double[] _data1 = new Double[Op1ElementCount];
private static Double[] _data2 = new Double[Op2ElementCount];
private static Vector128<Double> _clsVar1;
private static Vector128<Double> _clsVar2;
private Vector128<Double> _fld1;
private Vector128<Double> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__CompareNotGreaterThanDouble()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
}
public SimpleBinaryOpTest__CompareNotGreaterThanDouble()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Double>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetDouble(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetDouble(); }
_dataTable = new DataTable(_data1, _data2, new Double[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.CompareNotGreaterThan(
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.CompareNotGreaterThan(
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.CompareNotGreaterThan(
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareNotGreaterThan), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.CompareNotGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Double>* pClsVar1 = &_clsVar1)
fixed (Vector128<Double>* pClsVar2 = &_clsVar2)
{
var result = Sse2.CompareNotGreaterThan(
Sse2.LoadVector128((Double*)(pClsVar1)),
Sse2.LoadVector128((Double*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareNotGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareNotGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareNotGreaterThan(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__CompareNotGreaterThanDouble();
var result = Sse2.CompareNotGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__CompareNotGreaterThanDouble();
fixed (Vector128<Double>* pFld1 = &test._fld1)
fixed (Vector128<Double>* pFld2 = &test._fld2)
{
var result = Sse2.CompareNotGreaterThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.CompareNotGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Double>* pFld1 = &_fld1)
fixed (Vector128<Double>* pFld2 = &_fld2)
{
var result = Sse2.CompareNotGreaterThan(
Sse2.LoadVector128((Double*)(pFld1)),
Sse2.LoadVector128((Double*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.CompareNotGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.CompareNotGreaterThan(
Sse2.LoadVector128((Double*)(&test._fld1)),
Sse2.LoadVector128((Double*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Double> op1, Vector128<Double> op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[Op1ElementCount];
Double[] inArray2 = new Double[Op2ElementCount];
Double[] outArray = new Double[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Double>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Double>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (BitConverter.DoubleToInt64Bits(result[0]) != (!(left[0] > right[0]) ? -1 : 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (BitConverter.DoubleToInt64Bits(result[i]) != (!(left[i] > right[i]) ? -1 : 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.CompareNotGreaterThan)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
/***************************************************************************
* ProductInformation.cs
*
* Copyright (C) 2006 Novell, Inc.
* Written by Aaron Bockover <aaron@abock.org>
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Xml;
namespace Banshee.Base
{
public static class ProductInformation
{
private static SortedList<string, ProductAuthor> authors = new SortedList<string, ProductAuthor>();
private static SortedList<string, ProductTranslation> translations
= new SortedList<string, ProductTranslation>();
private static string [] artists;
private static string [] contributors;
static ProductInformation()
{
try {
LoadContributors();
LoadTranslators();
} catch {
}
}
private static void LoadContributors()
{
List<string> artists_list = new List<string>();
List<string> contributors_list = new List<string>();
XmlDocument doc = new XmlDocument();
doc.LoadXml(Resource.GetFileContents("contributors.xml"));
foreach(XmlNode node in doc.DocumentElement.ChildNodes) {
if(node.FirstChild.Value == null) {
continue;
}
string name = node.FirstChild.Value.Trim();
switch(node.Name) {
case "author":
authors.Add(name, new ProductAuthor(name, node.Attributes["role"].Value));
break;
case "contributor":
contributors_list.Add(name);
break;
case "artist":
artists_list.Add(name);
break;
default:
break;
}
}
artists = artists_list.ToArray();
contributors = contributors_list.ToArray();
Array.Sort(artists);
Array.Sort(contributors);
}
private static void LoadTranslators()
{
XmlDocument doc = new XmlDocument();
doc.LoadXml(Resource.GetFileContents("translators.xml"));
foreach(XmlNode node in doc.DocumentElement.ChildNodes) {
if(node.Name != "language") {
continue;
}
try {
string language_code = node.Attributes["code"].Value.Trim();
string language_name = node.Attributes["name"].Value.Trim();
ProductTranslation translation = new ProductTranslation(language_code, language_name);
foreach(XmlNode person in node.ChildNodes) {
if(person.Name != "person") {
continue;
}
translation.AddTranslator(person.FirstChild.Value.Trim());
}
translations.Add(language_name, translation);
} catch {
}
}
}
public static IEnumerable<ProductTranslation> Translations {
get { return translations.Values; }
}
public static IEnumerable<ProductAuthor> Authors {
get { return authors.Values; }
}
public static string [] Contributors {
get { return contributors; }
}
public static string [] Artists {
get { return artists; }
}
public static string License {
get { return Resource.GetFileContents("COPYING"); }
}
}
public class ProductTranslation
{
private string language_code;
private string language_name;
private SortedList<string, string> translators = new SortedList<string, string>();
private ProductTranslation()
{
}
internal ProductTranslation(string languageCode, string languageName)
{
language_code = languageCode;
language_name = languageName;
}
internal void AddTranslator(string translator)
{
translators.Add(translator, translator);
}
public string LanguageCode {
get { return language_code; }
}
public string LanguageName {
get { return language_name; }
}
public IEnumerable<string> Translators {
get { return translators.Values; }
}
}
public class ProductAuthor
{
private string name;
private string role;
private ProductAuthor()
{
}
internal ProductAuthor(string name, string role)
{
if(name == null || role == null) {
throw new ArgumentNullException("name or roll cannot be null");
}
this.name = name;
this.role = role;
}
public string Name {
get { return name; }
}
public string Role {
get { return role; }
}
}
}
| |
using CrystalDecisions.CrystalReports.Engine;
using CrystalDecisions.Windows.Forms;
using DpSdkEngLib;
using DPSDKOPSLib;
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
using System.Linq;
using System.Xml.Linq;
namespace _4PosBackOffice.NET
{
[Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]
partial class frmOrderItem
{
#region "Windows Form Designer generated code "
[System.Diagnostics.DebuggerNonUserCode()]
public frmOrderItem() : base()
{
Load += frmOrderItem_Load;
FormClosed += frmOrderItem_FormClosed;
Resize += frmOrderItem_Resize;
//This call is required by the Windows Form Designer.
InitializeComponent();
}
//Form overrides dispose to clean up the component list.
[System.Diagnostics.DebuggerNonUserCode()]
protected override void Dispose(bool Disposing)
{
if (Disposing) {
if ((components != null)) {
components.Dispose();
}
}
base.Dispose(Disposing);
}
//Required by the Windows Form Designer
private System.ComponentModel.IContainer components;
public System.Windows.Forms.ToolTip ToolTip1;
public System.Windows.Forms.TextBox _txtEdit_1;
private System.Windows.Forms.Button withEventsField_cmdPriceBOM;
public System.Windows.Forms.Button cmdPriceBOM {
get { return withEventsField_cmdPriceBOM; }
set {
if (withEventsField_cmdPriceBOM != null) {
withEventsField_cmdPriceBOM.Click -= cmdPriceBOM_Click;
}
withEventsField_cmdPriceBOM = value;
if (withEventsField_cmdPriceBOM != null) {
withEventsField_cmdPriceBOM.Click += cmdPriceBOM_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdExit;
public System.Windows.Forms.Button cmdExit {
get { return withEventsField_cmdExit; }
set {
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click -= cmdExit_Click;
}
withEventsField_cmdExit = value;
if (withEventsField_cmdExit != null) {
withEventsField_cmdExit.Click += cmdExit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdNext;
public System.Windows.Forms.Button cmdNext {
get { return withEventsField_cmdNext; }
set {
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click -= cmdNext_Click;
}
withEventsField_cmdNext = value;
if (withEventsField_cmdNext != null) {
withEventsField_cmdNext.Click += cmdNext_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdBack;
public System.Windows.Forms.Button cmdBack {
get { return withEventsField_cmdBack; }
set {
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click -= cmdBack_Click;
}
withEventsField_cmdBack = value;
if (withEventsField_cmdBack != null) {
withEventsField_cmdBack.Click += cmdBack_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdStockItem;
public System.Windows.Forms.Button cmdStockItem {
get { return withEventsField_cmdStockItem; }
set {
if (withEventsField_cmdStockItem != null) {
withEventsField_cmdStockItem.Click -= cmdStockItem_Click;
}
withEventsField_cmdStockItem = value;
if (withEventsField_cmdStockItem != null) {
withEventsField_cmdStockItem.Click += cmdStockItem_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdEdit;
public System.Windows.Forms.Button cmdEdit {
get { return withEventsField_cmdEdit; }
set {
if (withEventsField_cmdEdit != null) {
withEventsField_cmdEdit.Click -= cmdEdit_Click;
}
withEventsField_cmdEdit = value;
if (withEventsField_cmdEdit != null) {
withEventsField_cmdEdit.Click += cmdEdit_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdPack;
public System.Windows.Forms.Button cmdPack {
get { return withEventsField_cmdPack; }
set {
if (withEventsField_cmdPack != null) {
withEventsField_cmdPack.Click -= cmdPack_Click;
}
withEventsField_cmdPack = value;
if (withEventsField_cmdPack != null) {
withEventsField_cmdPack.Click += cmdPack_Click;
}
}
}
private System.Windows.Forms.Button withEventsField_cmdDelete;
public System.Windows.Forms.Button cmdDelete {
get { return withEventsField_cmdDelete; }
set {
if (withEventsField_cmdDelete != null) {
withEventsField_cmdDelete.Click -= cmdDelete_Click;
}
withEventsField_cmdDelete = value;
if (withEventsField_cmdDelete != null) {
withEventsField_cmdDelete.Click += cmdDelete_Click;
}
}
}
private System.Windows.Forms.Panel withEventsField_picButtons;
public System.Windows.Forms.Panel picButtons {
get { return withEventsField_picButtons; }
set {
if (withEventsField_picButtons != null) {
withEventsField_picButtons.Resize -= picButtons_Resize;
}
withEventsField_picButtons = value;
if (withEventsField_picButtons != null) {
withEventsField_picButtons.Resize += picButtons_Resize;
}
}
}
public System.Windows.Forms.Label _lbl_2;
public System.Windows.Forms.Label lblBrokenPack;
public System.Windows.Forms.Label lblTotal;
public System.Windows.Forms.Label _lbl_1;
public System.Windows.Forms.Label _lbl_10;
public System.Windows.Forms.Label _lbl_9;
public System.Windows.Forms.Label _lbl_8;
public System.Windows.Forms.Label lblQuantity;
public System.Windows.Forms.Label lblDeposit;
public System.Windows.Forms.Label lblContent;
public System.Windows.Forms.GroupBox frmTotals;
public System.Windows.Forms.Label lblSupplier;
public System.Windows.Forms.Panel Picture1;
public System.Windows.Forms.TextBox _txtEdit_0;
private myDataGridView withEventsField_gridItem;
public myDataGridView gridItem {
get { return withEventsField_gridItem; }
set {
if (withEventsField_gridItem != null) {
withEventsField_gridItem.Enter -= gridItem_EnterCell;
withEventsField_gridItem.Enter -= gridItem_Enter;
withEventsField_gridItem.KeyPress -= gridItem_KeyPress;
withEventsField_gridItem.Leave -= gridItem_LeaveCell;
}
withEventsField_gridItem = value;
if (withEventsField_gridItem != null) {
withEventsField_gridItem.Enter += gridItem_EnterCell;
withEventsField_gridItem.Enter += gridItem_Enter;
withEventsField_gridItem.KeyPress += gridItem_KeyPress;
withEventsField_gridItem.Leave += gridItem_LeaveCell;
}
}
}
private System.Windows.Forms.TextBox withEventsField_txtSearch;
public System.Windows.Forms.TextBox txtSearch {
get { return withEventsField_txtSearch; }
set {
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter -= txtSearch_Enter;
withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress;
}
withEventsField_txtSearch = value;
if (withEventsField_txtSearch != null) {
withEventsField_txtSearch.Enter += txtSearch_Enter;
withEventsField_txtSearch.KeyDown += txtSearch_KeyDown;
withEventsField_txtSearch.KeyPress += txtSearch_KeyPress;
}
}
}
private System.Windows.Forms.ListBox withEventsField_lstWorkspace;
public System.Windows.Forms.ListBox lstWorkspace {
get { return withEventsField_lstWorkspace; }
set {
if (withEventsField_lstWorkspace != null) {
withEventsField_lstWorkspace.DoubleClick -= lstWorkspace_DoubleClick;
withEventsField_lstWorkspace.KeyPress -= lstWorkspace_KeyPress;
withEventsField_lstWorkspace.KeyDown -= lstWorkspace_KeyDown;
}
withEventsField_lstWorkspace = value;
if (withEventsField_lstWorkspace != null) {
withEventsField_lstWorkspace.DoubleClick += lstWorkspace_DoubleClick;
withEventsField_lstWorkspace.KeyPress += lstWorkspace_KeyPress;
withEventsField_lstWorkspace.KeyDown += lstWorkspace_KeyDown;
}
}
}
public System.Windows.Forms.Label _lbl_7;
public System.Windows.Forms.Label _lbl_0;
public Microsoft.VisualBasic.Compatibility.VB6.LabelArray lbl;
private Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray withEventsField_txtEdit;
public Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray txtEdit {
get { return withEventsField_txtEdit; }
set {
if (withEventsField_txtEdit != null) {
withEventsField_txtEdit.TextChanged -= txtEdit_TextChanged;
withEventsField_txtEdit.Leave -= txtEdit_Leave;
withEventsField_txtEdit.Enter -= txtEdit_Enter;
withEventsField_txtEdit.KeyDown -= txtEdit_KeyDown;
withEventsField_txtEdit.KeyPress -= txtEdit_KeyPress;
}
withEventsField_txtEdit = value;
if (withEventsField_txtEdit != null) {
withEventsField_txtEdit.TextChanged += txtEdit_TextChanged;
withEventsField_txtEdit.Leave += txtEdit_Leave;
withEventsField_txtEdit.Enter += txtEdit_Enter;
withEventsField_txtEdit.KeyDown += txtEdit_KeyDown;
withEventsField_txtEdit.KeyPress += txtEdit_KeyPress;
}
}
}
//NOTE: The following procedure is required by the Windows Form Designer
//It can be modified using the Windows Form Designer.
//Do not modify it using the code editor.
[System.Diagnostics.DebuggerStepThrough()]
private void InitializeComponent()
{
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmOrderItem));
this.components = new System.ComponentModel.Container();
this.ToolTip1 = new System.Windows.Forms.ToolTip(components);
this._txtEdit_1 = new System.Windows.Forms.TextBox();
this.picButtons = new System.Windows.Forms.Panel();
this.cmdPriceBOM = new System.Windows.Forms.Button();
this.cmdExit = new System.Windows.Forms.Button();
this.cmdNext = new System.Windows.Forms.Button();
this.cmdBack = new System.Windows.Forms.Button();
this.cmdStockItem = new System.Windows.Forms.Button();
this.cmdEdit = new System.Windows.Forms.Button();
this.cmdPack = new System.Windows.Forms.Button();
this.cmdDelete = new System.Windows.Forms.Button();
this.frmTotals = new System.Windows.Forms.GroupBox();
this._lbl_2 = new System.Windows.Forms.Label();
this.lblBrokenPack = new System.Windows.Forms.Label();
this.lblTotal = new System.Windows.Forms.Label();
this._lbl_1 = new System.Windows.Forms.Label();
this._lbl_10 = new System.Windows.Forms.Label();
this._lbl_9 = new System.Windows.Forms.Label();
this._lbl_8 = new System.Windows.Forms.Label();
this.lblQuantity = new System.Windows.Forms.Label();
this.lblDeposit = new System.Windows.Forms.Label();
this.lblContent = new System.Windows.Forms.Label();
this.Picture1 = new System.Windows.Forms.Panel();
this.lblSupplier = new System.Windows.Forms.Label();
this._txtEdit_0 = new System.Windows.Forms.TextBox();
this.gridItem = new myDataGridView();
this.txtSearch = new System.Windows.Forms.TextBox();
this.lstWorkspace = new System.Windows.Forms.ListBox();
this._lbl_7 = new System.Windows.Forms.Label();
this._lbl_0 = new System.Windows.Forms.Label();
this.lbl = new Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components);
this.txtEdit = new Microsoft.VisualBasic.Compatibility.VB6.TextBoxArray(components);
this.picButtons.SuspendLayout();
this.frmTotals.SuspendLayout();
this.Picture1.SuspendLayout();
this.SuspendLayout();
this.ToolTip1.Active = true;
((System.ComponentModel.ISupportInitialize)this.gridItem).BeginInit();
((System.ComponentModel.ISupportInitialize)this.lbl).BeginInit();
((System.ComponentModel.ISupportInitialize)this.txtEdit).BeginInit();
this.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
this.Text = "Order Form";
this.ClientSize = new System.Drawing.Size(592, 547);
this.Location = new System.Drawing.Point(4, 23);
this.ControlBox = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
this.Enabled = true;
this.KeyPreview = false;
this.MaximizeBox = true;
this.MinimizeBox = true;
this.Cursor = System.Windows.Forms.Cursors.Default;
this.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.ShowInTaskbar = true;
this.HelpButton = false;
this.Name = "frmOrderItem";
this._txtEdit_1.AutoSize = false;
this._txtEdit_1.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtEdit_1.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
this._txtEdit_1.Size = new System.Drawing.Size(55, 16);
this._txtEdit_1.Location = new System.Drawing.Point(376, 136);
this._txtEdit_1.TabIndex = 27;
this._txtEdit_1.Tag = "0";
this._txtEdit_1.Text = "0";
this._txtEdit_1.Visible = false;
this._txtEdit_1.AcceptsReturn = true;
this._txtEdit_1.CausesValidation = true;
this._txtEdit_1.Enabled = true;
this._txtEdit_1.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtEdit_1.HideSelection = true;
this._txtEdit_1.ReadOnly = false;
this._txtEdit_1.MaxLength = 0;
this._txtEdit_1.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtEdit_1.Multiline = false;
this._txtEdit_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtEdit_1.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtEdit_1.TabStop = true;
this._txtEdit_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._txtEdit_1.Name = "_txtEdit_1";
this.picButtons.Dock = System.Windows.Forms.DockStyle.Top;
this.picButtons.BackColor = System.Drawing.Color.Blue;
this.picButtons.Size = new System.Drawing.Size(592, 38);
this.picButtons.Location = new System.Drawing.Point(0, 0);
this.picButtons.TabIndex = 19;
this.picButtons.TabStop = false;
this.picButtons.CausesValidation = true;
this.picButtons.Enabled = true;
this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText;
this.picButtons.Cursor = System.Windows.Forms.Cursors.Default;
this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.picButtons.Visible = true;
this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picButtons.Name = "picButtons";
this.cmdPriceBOM.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPriceBOM.Text = "Change &BOM Price";
this.cmdPriceBOM.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdPriceBOM.Size = new System.Drawing.Size(123, 28);
this.cmdPriceBOM.Location = new System.Drawing.Point(432, 3);
this.cmdPriceBOM.TabIndex = 28;
this.cmdPriceBOM.TabStop = false;
this.cmdPriceBOM.Tag = "0";
this.cmdPriceBOM.BackColor = System.Drawing.SystemColors.Control;
this.cmdPriceBOM.CausesValidation = true;
this.cmdPriceBOM.Enabled = true;
this.cmdPriceBOM.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPriceBOM.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPriceBOM.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPriceBOM.Name = "cmdPriceBOM";
this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdExit.Text = "E&xit";
this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdExit.Size = new System.Drawing.Size(73, 28);
this.cmdExit.Location = new System.Drawing.Point(717, 3);
this.cmdExit.TabIndex = 26;
this.cmdExit.TabStop = false;
this.cmdExit.BackColor = System.Drawing.SystemColors.Control;
this.cmdExit.CausesValidation = true;
this.cmdExit.Enabled = true;
this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdExit.Name = "cmdExit";
this.cmdNext.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdNext.Text = "&Next >>";
this.cmdNext.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdNext.Size = new System.Drawing.Size(73, 28);
this.cmdNext.Location = new System.Drawing.Point(669, 3);
this.cmdNext.TabIndex = 25;
this.cmdNext.TabStop = false;
this.cmdNext.BackColor = System.Drawing.SystemColors.Control;
this.cmdNext.CausesValidation = true;
this.cmdNext.Enabled = true;
this.cmdNext.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdNext.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdNext.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdNext.Name = "cmdNext";
this.cmdBack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdBack.Text = "<< &Back";
this.cmdBack.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdBack.Size = new System.Drawing.Size(73, 28);
this.cmdBack.Location = new System.Drawing.Point(570, 3);
this.cmdBack.TabIndex = 24;
this.cmdBack.TabStop = false;
this.cmdBack.BackColor = System.Drawing.SystemColors.Control;
this.cmdBack.CausesValidation = true;
this.cmdBack.Enabled = true;
this.cmdBack.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdBack.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdBack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdBack.Name = "cmdBack";
this.cmdStockItem.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdStockItem.Text = "All Stoc&k Items";
this.cmdStockItem.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdStockItem.Size = new System.Drawing.Size(97, 28);
this.cmdStockItem.Location = new System.Drawing.Point(0, 3);
this.cmdStockItem.TabIndex = 23;
this.cmdStockItem.TabStop = false;
this.cmdStockItem.Tag = "0";
this.cmdStockItem.BackColor = System.Drawing.SystemColors.Control;
this.cmdStockItem.CausesValidation = true;
this.cmdStockItem.Enabled = true;
this.cmdStockItem.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdStockItem.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdStockItem.Name = "cmdStockItem";
this.cmdEdit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdEdit.Text = "&Edit Stock Item";
this.cmdEdit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdEdit.Size = new System.Drawing.Size(103, 28);
this.cmdEdit.Location = new System.Drawing.Point(324, 3);
this.cmdEdit.TabIndex = 22;
this.cmdEdit.TabStop = false;
this.cmdEdit.Tag = "0";
this.cmdEdit.BackColor = System.Drawing.SystemColors.Control;
this.cmdEdit.CausesValidation = true;
this.cmdEdit.Enabled = true;
this.cmdEdit.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdEdit.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdEdit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdEdit.Name = "cmdEdit";
this.cmdPack.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdPack.Text = "Break / Build P&ack";
this.cmdPack.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdPack.Size = new System.Drawing.Size(124, 28);
this.cmdPack.Location = new System.Drawing.Point(195, 3);
this.cmdPack.TabIndex = 21;
this.cmdPack.TabStop = false;
this.cmdPack.Tag = "0";
this.cmdPack.BackColor = System.Drawing.SystemColors.Control;
this.cmdPack.CausesValidation = true;
this.cmdPack.Enabled = true;
this.cmdPack.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdPack.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdPack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdPack.Name = "cmdPack";
this.cmdDelete.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.cmdDelete.Text = "Dele&te";
this.cmdDelete.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.cmdDelete.Size = new System.Drawing.Size(73, 28);
this.cmdDelete.Location = new System.Drawing.Point(117, 3);
this.cmdDelete.TabIndex = 20;
this.cmdDelete.TabStop = false;
this.cmdDelete.Tag = "0";
this.cmdDelete.BackColor = System.Drawing.SystemColors.Control;
this.cmdDelete.CausesValidation = true;
this.cmdDelete.Enabled = true;
this.cmdDelete.ForeColor = System.Drawing.SystemColors.ControlText;
this.cmdDelete.Cursor = System.Windows.Forms.Cursors.Default;
this.cmdDelete.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.cmdDelete.Name = "cmdDelete";
this.frmTotals.Text = "Sub Totals";
this.frmTotals.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.frmTotals.Size = new System.Drawing.Size(457, 58);
this.frmTotals.Location = new System.Drawing.Point(219, 366);
this.frmTotals.TabIndex = 8;
this.frmTotals.BackColor = System.Drawing.SystemColors.Control;
this.frmTotals.Enabled = true;
this.frmTotals.ForeColor = System.Drawing.SystemColors.ControlText;
this.frmTotals.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.frmTotals.Visible = true;
this.frmTotals.Padding = new System.Windows.Forms.Padding(0);
this.frmTotals.Name = "frmTotals";
this._lbl_2.Text = "Broken Packs";
this._lbl_2.Size = new System.Drawing.Size(67, 13);
this._lbl_2.Location = new System.Drawing.Point(78, 15);
this._lbl_2.TabIndex = 18;
this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_2.BackColor = System.Drawing.Color.Transparent;
this._lbl_2.Enabled = true;
this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_2.UseMnemonic = true;
this._lbl_2.Visible = true;
this._lbl_2.AutoSize = true;
this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_2.Name = "_lbl_2";
this.lblBrokenPack.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lblBrokenPack.Text = "lblQuantity";
this.lblBrokenPack.Size = new System.Drawing.Size(64, 17);
this.lblBrokenPack.Location = new System.Drawing.Point(81, 27);
this.lblBrokenPack.TabIndex = 17;
this.lblBrokenPack.BackColor = System.Drawing.SystemColors.Control;
this.lblBrokenPack.Enabled = true;
this.lblBrokenPack.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblBrokenPack.Cursor = System.Windows.Forms.Cursors.Default;
this.lblBrokenPack.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblBrokenPack.UseMnemonic = true;
this.lblBrokenPack.Visible = true;
this.lblBrokenPack.AutoSize = false;
this.lblBrokenPack.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblBrokenPack.Name = "lblBrokenPack";
this.lblTotal.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lblTotal.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
this.lblTotal.Text = "0.00";
this.lblTotal.Size = new System.Drawing.Size(91, 17);
this.lblTotal.Location = new System.Drawing.Point(357, 27);
this.lblTotal.TabIndex = 16;
this.lblTotal.Enabled = true;
this.lblTotal.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblTotal.Cursor = System.Windows.Forms.Cursors.Default;
this.lblTotal.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblTotal.UseMnemonic = true;
this.lblTotal.Visible = true;
this.lblTotal.AutoSize = false;
this.lblTotal.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblTotal.Name = "lblTotal";
this._lbl_1.Text = "Total Value";
this._lbl_1.Size = new System.Drawing.Size(91, 13);
this._lbl_1.Location = new System.Drawing.Point(358, 15);
this._lbl_1.TabIndex = 15;
this._lbl_1.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_1.BackColor = System.Drawing.Color.Transparent;
this._lbl_1.Enabled = true;
this._lbl_1.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_1.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_1.UseMnemonic = true;
this._lbl_1.Visible = true;
this._lbl_1.AutoSize = false;
this._lbl_1.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_1.Name = "_lbl_1";
this._lbl_10.Text = "Contents Value";
this._lbl_10.Size = new System.Drawing.Size(91, 13);
this._lbl_10.Location = new System.Drawing.Point(256, 15);
this._lbl_10.TabIndex = 14;
this._lbl_10.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_10.BackColor = System.Drawing.Color.Transparent;
this._lbl_10.Enabled = true;
this._lbl_10.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_10.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_10.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_10.UseMnemonic = true;
this._lbl_10.Visible = true;
this._lbl_10.AutoSize = false;
this._lbl_10.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_10.Name = "_lbl_10";
this._lbl_9.Text = "Deposit Value";
this._lbl_9.Size = new System.Drawing.Size(91, 13);
this._lbl_9.Location = new System.Drawing.Point(163, 15);
this._lbl_9.TabIndex = 13;
this._lbl_9.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_9.BackColor = System.Drawing.Color.Transparent;
this._lbl_9.Enabled = true;
this._lbl_9.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_9.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_9.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_9.UseMnemonic = true;
this._lbl_9.Visible = true;
this._lbl_9.AutoSize = false;
this._lbl_9.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_9.Name = "_lbl_9";
this._lbl_8.Text = "No Of Cases";
this._lbl_8.Size = new System.Drawing.Size(60, 13);
this._lbl_8.Location = new System.Drawing.Point(9, 15);
this._lbl_8.TabIndex = 12;
this._lbl_8.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this._lbl_8.BackColor = System.Drawing.Color.Transparent;
this._lbl_8.Enabled = true;
this._lbl_8.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_8.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_8.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_8.UseMnemonic = true;
this._lbl_8.Visible = true;
this._lbl_8.AutoSize = true;
this._lbl_8.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_8.Name = "_lbl_8";
this.lblQuantity.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lblQuantity.Text = "lblQuantity";
this.lblQuantity.Size = new System.Drawing.Size(64, 17);
this.lblQuantity.Location = new System.Drawing.Point(9, 27);
this.lblQuantity.TabIndex = 11;
this.lblQuantity.BackColor = System.Drawing.SystemColors.Control;
this.lblQuantity.Enabled = true;
this.lblQuantity.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblQuantity.Cursor = System.Windows.Forms.Cursors.Default;
this.lblQuantity.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblQuantity.UseMnemonic = true;
this.lblQuantity.Visible = true;
this.lblQuantity.AutoSize = false;
this.lblQuantity.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblQuantity.Name = "lblQuantity";
this.lblDeposit.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lblDeposit.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
this.lblDeposit.Text = "0.00";
this.lblDeposit.Size = new System.Drawing.Size(91, 17);
this.lblDeposit.Location = new System.Drawing.Point(162, 27);
this.lblDeposit.TabIndex = 10;
this.lblDeposit.Enabled = true;
this.lblDeposit.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblDeposit.Cursor = System.Windows.Forms.Cursors.Default;
this.lblDeposit.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblDeposit.UseMnemonic = true;
this.lblDeposit.Visible = true;
this.lblDeposit.AutoSize = false;
this.lblDeposit.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblDeposit.Name = "lblDeposit";
this.lblContent.TextAlign = System.Drawing.ContentAlignment.TopRight;
this.lblContent.BackColor = System.Drawing.Color.FromArgb(255, 192, 192);
this.lblContent.Text = "0.00";
this.lblContent.Size = new System.Drawing.Size(91, 17);
this.lblContent.Location = new System.Drawing.Point(255, 27);
this.lblContent.TabIndex = 9;
this.lblContent.Enabled = true;
this.lblContent.ForeColor = System.Drawing.SystemColors.ControlText;
this.lblContent.Cursor = System.Windows.Forms.Cursors.Default;
this.lblContent.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblContent.UseMnemonic = true;
this.lblContent.Visible = true;
this.lblContent.AutoSize = false;
this.lblContent.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblContent.Name = "lblContent";
this.Picture1.Dock = System.Windows.Forms.DockStyle.Top;
this.Picture1.BackColor = System.Drawing.Color.FromArgb(192, 192, 255);
this.Picture1.ForeColor = System.Drawing.Color.White;
this.Picture1.Size = new System.Drawing.Size(592, 25);
this.Picture1.Location = new System.Drawing.Point(0, 38);
this.Picture1.TabIndex = 6;
this.Picture1.TabStop = false;
this.Picture1.CausesValidation = true;
this.Picture1.Enabled = true;
this.Picture1.Cursor = System.Windows.Forms.Cursors.Default;
this.Picture1.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.Picture1.Visible = true;
this.Picture1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.Picture1.Name = "Picture1";
this.lblSupplier.Text = "lblSupplier";
this.lblSupplier.Font = new System.Drawing.Font("Arial", 12f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this.lblSupplier.ForeColor = System.Drawing.Color.Black;
this.lblSupplier.Size = new System.Drawing.Size(85, 20);
this.lblSupplier.Location = new System.Drawing.Point(0, 0);
this.lblSupplier.TabIndex = 7;
this.lblSupplier.TextAlign = System.Drawing.ContentAlignment.TopLeft;
this.lblSupplier.BackColor = System.Drawing.Color.Transparent;
this.lblSupplier.Enabled = true;
this.lblSupplier.Cursor = System.Windows.Forms.Cursors.Default;
this.lblSupplier.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lblSupplier.UseMnemonic = true;
this.lblSupplier.Visible = true;
this.lblSupplier.AutoSize = true;
this.lblSupplier.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.lblSupplier.Name = "lblSupplier";
this._txtEdit_0.AutoSize = false;
this._txtEdit_0.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this._txtEdit_0.BackColor = System.Drawing.Color.FromArgb(255, 255, 192);
this._txtEdit_0.Size = new System.Drawing.Size(55, 16);
this._txtEdit_0.Location = new System.Drawing.Point(279, 120);
this._txtEdit_0.TabIndex = 3;
this._txtEdit_0.Tag = "0";
this._txtEdit_0.Text = "0";
this._txtEdit_0.Visible = false;
this._txtEdit_0.AcceptsReturn = true;
this._txtEdit_0.CausesValidation = true;
this._txtEdit_0.Enabled = true;
this._txtEdit_0.ForeColor = System.Drawing.SystemColors.WindowText;
this._txtEdit_0.HideSelection = true;
this._txtEdit_0.ReadOnly = false;
this._txtEdit_0.MaxLength = 0;
this._txtEdit_0.Cursor = System.Windows.Forms.Cursors.IBeam;
this._txtEdit_0.Multiline = false;
this._txtEdit_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._txtEdit_0.ScrollBars = System.Windows.Forms.ScrollBars.None;
this._txtEdit_0.TabStop = true;
this._txtEdit_0.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._txtEdit_0.Name = "_txtEdit_0";
//gridItem.OcxState = CType(resources.GetObject("gridItem.OcxState"), System.Windows.Forms.AxHost.State)
this.gridItem.Size = new System.Drawing.Size(493, 355);
this.gridItem.Location = new System.Drawing.Point(195, 63);
this.gridItem.TabIndex = 5;
this.gridItem.Name = "gridItem";
this.txtSearch.AutoSize = false;
this.txtSearch.Size = new System.Drawing.Size(142, 19);
this.txtSearch.Location = new System.Drawing.Point(45, 81);
this.txtSearch.TabIndex = 1;
this.txtSearch.AcceptsReturn = true;
this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left;
this.txtSearch.BackColor = System.Drawing.SystemColors.Window;
this.txtSearch.CausesValidation = true;
this.txtSearch.Enabled = true;
this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText;
this.txtSearch.HideSelection = true;
this.txtSearch.ReadOnly = false;
this.txtSearch.MaxLength = 0;
this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam;
this.txtSearch.Multiline = false;
this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None;
this.txtSearch.TabStop = true;
this.txtSearch.Visible = true;
this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.txtSearch.Name = "txtSearch";
this.lstWorkspace.Size = new System.Drawing.Size(187, 358);
this.lstWorkspace.Location = new System.Drawing.Point(0, 102);
this.lstWorkspace.TabIndex = 2;
this.lstWorkspace.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lstWorkspace.BackColor = System.Drawing.SystemColors.Window;
this.lstWorkspace.CausesValidation = true;
this.lstWorkspace.Enabled = true;
this.lstWorkspace.ForeColor = System.Drawing.SystemColors.WindowText;
this.lstWorkspace.IntegralHeight = true;
this.lstWorkspace.Cursor = System.Windows.Forms.Cursors.Default;
this.lstWorkspace.SelectionMode = System.Windows.Forms.SelectionMode.One;
this.lstWorkspace.RightToLeft = System.Windows.Forms.RightToLeft.No;
this.lstWorkspace.Sorted = false;
this.lstWorkspace.TabStop = true;
this.lstWorkspace.Visible = true;
this.lstWorkspace.MultiColumn = false;
this.lstWorkspace.Name = "lstWorkspace";
this._lbl_7.TextAlign = System.Drawing.ContentAlignment.TopRight;
this._lbl_7.Text = "&Search";
this._lbl_7.Size = new System.Drawing.Size(34, 13);
this._lbl_7.Location = new System.Drawing.Point(6, 84);
this._lbl_7.TabIndex = 0;
this._lbl_7.BackColor = System.Drawing.Color.Transparent;
this._lbl_7.Enabled = true;
this._lbl_7.ForeColor = System.Drawing.SystemColors.ControlText;
this._lbl_7.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_7.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_7.UseMnemonic = true;
this._lbl_7.Visible = true;
this._lbl_7.AutoSize = true;
this._lbl_7.BorderStyle = System.Windows.Forms.BorderStyle.None;
this._lbl_7.Name = "_lbl_7";
this._lbl_0.TextAlign = System.Drawing.ContentAlignment.TopCenter;
this._lbl_0.BackColor = System.Drawing.Color.FromArgb(128, 128, 255);
this._lbl_0.Text = "Stock Item Selector";
this._lbl_0.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178));
this._lbl_0.ForeColor = System.Drawing.Color.White;
this._lbl_0.Size = new System.Drawing.Size(190, 16);
this._lbl_0.Location = new System.Drawing.Point(0, 63);
this._lbl_0.TabIndex = 4;
this._lbl_0.Enabled = true;
this._lbl_0.Cursor = System.Windows.Forms.Cursors.Default;
this._lbl_0.RightToLeft = System.Windows.Forms.RightToLeft.No;
this._lbl_0.UseMnemonic = true;
this._lbl_0.Visible = true;
this._lbl_0.AutoSize = false;
this._lbl_0.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this._lbl_0.Name = "_lbl_0";
this.Controls.Add(_txtEdit_1);
this.Controls.Add(picButtons);
this.Controls.Add(frmTotals);
this.Controls.Add(Picture1);
this.Controls.Add(_txtEdit_0);
this.Controls.Add(gridItem);
this.Controls.Add(txtSearch);
this.Controls.Add(lstWorkspace);
this.Controls.Add(_lbl_7);
this.Controls.Add(_lbl_0);
this.picButtons.Controls.Add(cmdPriceBOM);
this.picButtons.Controls.Add(cmdExit);
this.picButtons.Controls.Add(cmdNext);
this.picButtons.Controls.Add(cmdBack);
this.picButtons.Controls.Add(cmdStockItem);
this.picButtons.Controls.Add(cmdEdit);
this.picButtons.Controls.Add(cmdPack);
this.picButtons.Controls.Add(cmdDelete);
this.frmTotals.Controls.Add(_lbl_2);
this.frmTotals.Controls.Add(lblBrokenPack);
this.frmTotals.Controls.Add(lblTotal);
this.frmTotals.Controls.Add(_lbl_1);
this.frmTotals.Controls.Add(_lbl_10);
this.frmTotals.Controls.Add(_lbl_9);
this.frmTotals.Controls.Add(_lbl_8);
this.frmTotals.Controls.Add(lblQuantity);
this.frmTotals.Controls.Add(lblDeposit);
this.frmTotals.Controls.Add(lblContent);
this.Picture1.Controls.Add(lblSupplier);
this.lbl.SetIndex(_lbl_2, Convert.ToInt16(2));
this.lbl.SetIndex(_lbl_1, Convert.ToInt16(1));
this.lbl.SetIndex(_lbl_10, Convert.ToInt16(10));
this.lbl.SetIndex(_lbl_9, Convert.ToInt16(9));
this.lbl.SetIndex(_lbl_8, Convert.ToInt16(8));
this.lbl.SetIndex(_lbl_7, Convert.ToInt16(7));
this.lbl.SetIndex(_lbl_0, Convert.ToInt16(0));
this.txtEdit.SetIndex(_txtEdit_1, Convert.ToInt16(1));
this.txtEdit.SetIndex(_txtEdit_0, Convert.ToInt16(0));
((System.ComponentModel.ISupportInitialize)this.txtEdit).EndInit();
((System.ComponentModel.ISupportInitialize)this.lbl).EndInit();
((System.ComponentModel.ISupportInitialize)this.gridItem).EndInit();
this.picButtons.ResumeLayout(false);
this.frmTotals.ResumeLayout(false);
this.Picture1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}
}
| |
/*
* 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.Xml;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using System.Threading;
using OpenMetaverse;
using Nini.Config;
using OpenSim.Framework.Servers.HttpServer;
using log4net;
namespace OpenSim.Framework.Console
{
public class ConsoleConnection
{
public int last;
public long lastLineSeen;
}
// A console that uses REST interfaces
//
public class RemoteConsole : CommandConsole
{
private IHttpServer m_Server = null;
private IConfigSource m_Config = null;
private List<string> m_Scrollback = new List<string>();
private ManualResetEvent m_DataEvent = new ManualResetEvent(false);
private List<string> m_InputData = new List<string>();
private long m_LineNumber = 0;
private Dictionary<UUID, ConsoleConnection> m_Connections =
new Dictionary<UUID, ConsoleConnection>();
private string m_UserName = String.Empty;
private string m_Password = String.Empty;
public RemoteConsole(string defaultPrompt) : base(defaultPrompt)
{
}
public void ReadConfig(IConfigSource config)
{
m_Config = config;
IConfig netConfig = m_Config.Configs["Network"];
if (netConfig == null)
return;
m_UserName = netConfig.GetString("ConsoleUser", String.Empty);
m_Password = netConfig.GetString("ConsolePass", String.Empty);
}
public void SetServer(IHttpServer server)
{
m_Server = server;
m_Server.AddHTTPHandler("/StartSession/", HandleHttpStartSession);
m_Server.AddHTTPHandler("/CloseSession/", HandleHttpCloseSession);
m_Server.AddHTTPHandler("/SessionCommand/", HandleHttpSessionCommand);
}
public override void Output(string text, string level)
{
lock (m_Scrollback)
{
while (m_Scrollback.Count >= 1000)
m_Scrollback.RemoveAt(0);
m_LineNumber++;
m_Scrollback.Add(String.Format("{0}", m_LineNumber)+":"+level+":"+text);
}
System.Console.WriteLine(text.Trim());
}
public override void Output(string text)
{
Output(text, "normal");
}
public override string ReadLine(string p, bool isCommand, bool e)
{
m_DataEvent.WaitOne();
lock (m_InputData)
{
if (m_InputData.Count == 0)
{
m_DataEvent.Reset();
return "";
}
string cmdinput = m_InputData[0];
m_InputData.RemoveAt(0);
if (m_InputData.Count == 0)
m_DataEvent.Reset();
if (isCommand)
{
string[] cmd = Commands.Resolve(Parser.Parse(cmdinput));
if (cmd.Length != 0)
{
int i;
for (i=0 ; i < cmd.Length ; i++)
{
if (cmd[i].Contains(" "))
cmd[i] = "\"" + cmd[i] + "\"";
}
return String.Empty;
}
}
return cmdinput;
}
}
private void DoExpire()
{
List<UUID> expired = new List<UUID>();
lock (m_Connections)
{
foreach (KeyValuePair<UUID, ConsoleConnection> kvp in m_Connections)
{
if (System.Environment.TickCount - kvp.Value.last > 500000)
expired.Add(kvp.Key);
}
foreach (UUID id in expired)
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
}
private Hashtable HandleHttpStartSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 401;
reply["content_type"] = "text/plain";
if (m_UserName == String.Empty)
return reply;
if (post["USER"] == null || post["PASS"] == null)
return reply;
if (m_UserName != post["USER"].ToString() ||
m_Password != post["PASS"].ToString())
{
return reply;
}
ConsoleConnection c = new ConsoleConnection();
c.last = System.Environment.TickCount;
c.lastLineSeen = 0;
UUID sessionID = UUID.Random();
lock (m_Connections)
{
m_Connections[sessionID] = c;
}
string uri = "/ReadResponses/" + sessionID.ToString() + "/";
m_Server.AddPollServiceHTTPHandler(uri, HandleHttpCloseSession,
new PollServiceEventArgs(HasEvents, GetEvents, NoEvents,
sessionID));
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement id = xmldoc.CreateElement("", "SessionID", "");
id.AppendChild(xmldoc.CreateTextNode(sessionID.ToString()));
rootElement.AppendChild(id);
XmlElement prompt = xmldoc.CreateElement("", "Prompt", "");
prompt.AppendChild(xmldoc.CreateTextNode(DefaultPrompt));
rootElement.AppendChild(prompt);
rootElement.AppendChild(MainConsole.Instance.Commands.GetXml(xmldoc));
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/xml";
return reply;
}
private Hashtable HandleHttpCloseSession(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
lock (m_Connections)
{
if (m_Connections.ContainsKey(id))
{
m_Connections.Remove(id);
CloseConnection(id);
}
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/plain";
return reply;
}
private Hashtable HandleHttpSessionCommand(Hashtable request)
{
DoExpire();
Hashtable post = DecodePostString(request["body"].ToString());
Hashtable reply = new Hashtable();
reply["str_response_string"] = "";
reply["int_response_code"] = 404;
reply["content_type"] = "text/plain";
if (post["ID"] == null)
return reply;
UUID id;
if (!UUID.TryParse(post["ID"].ToString(), out id))
return reply;
if (post["COMMAND"] == null || post["COMMAND"].ToString() == String.Empty)
return reply;
lock (m_InputData)
{
m_DataEvent.Set();
m_InputData.Add(post["COMMAND"].ToString());
}
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
XmlElement res = xmldoc.CreateElement("", "Result", "");
res.AppendChild(xmldoc.CreateTextNode("OK"));
rootElement.AppendChild(res);
reply["str_response_string"] = xmldoc.InnerXml;
reply["int_response_code"] = 200;
reply["content_type"] = "text/plain";
return reply;
}
private Hashtable DecodePostString(string data)
{
Hashtable result = new Hashtable();
string[] terms = data.Split(new char[] {'&'});
foreach (string term in terms)
{
string[] elems = term.Split(new char[] {'='});
if (elems.Length == 0)
continue;
string name = System.Web.HttpUtility.UrlDecode(elems[0]);
string value = String.Empty;
if (elems.Length > 1)
value = System.Web.HttpUtility.UrlDecode(elems[1]);
result[name] = value;
}
return result;
}
public void CloseConnection(UUID id)
{
try
{
string uri = "/ReadResponses/" + id.ToString() + "/";
m_Server.RemovePollServiceHTTPHandler("", uri);
}
catch (Exception)
{
}
}
private bool HasEvents(UUID sessionID)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return false;
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen < m_LineNumber)
return true;
return false;
}
private Hashtable GetEvents(UUID sessionID, string request)
{
ConsoleConnection c = null;
lock (m_Connections)
{
if (!m_Connections.ContainsKey(sessionID))
return NoEvents();
c = m_Connections[sessionID];
}
c.last = System.Environment.TickCount;
if (c.lastLineSeen >= m_LineNumber)
return NoEvents();
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
lock (m_Scrollback)
{
long startLine = m_LineNumber - m_Scrollback.Count;
long sendStart = startLine;
if (sendStart < c.lastLineSeen)
sendStart = c.lastLineSeen;
for (long i = sendStart ; i < m_LineNumber ; i++)
{
XmlElement res = xmldoc.CreateElement("", "Line", "");
long line = i + 1;
res.SetAttribute("Number", line.ToString());
res.AppendChild(xmldoc.CreateTextNode(m_Scrollback[(int)(i - startLine)]));
rootElement.AppendChild(res);
}
}
c.lastLineSeen = m_LineNumber;
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "application/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
return result;
}
private Hashtable NoEvents()
{
Hashtable result = new Hashtable();
XmlDocument xmldoc = new XmlDocument();
XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
xmldoc.AppendChild(xmlnode);
XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession",
"");
xmldoc.AppendChild(rootElement);
result["str_response_string"] = xmldoc.InnerXml;
result["int_response_code"] = 200;
result["content_type"] = "text/xml";
result["keepalive"] = false;
result["reusecontext"] = false;
return result;
}
}
}
| |
//! \file ImageRCT.cs
//! \date Fri Aug 01 11:36:31 2014
//! \brief RCT image format implementation.
//
// Copyright (C) 2014-2017 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Formats.Strings;
using GameRes.Utility;
namespace GameRes.Formats.Majiro
{
internal class RctMetaData : ImageMetaData
{
public int Version;
public bool IsEncrypted;
public uint DataOffset;
public int DataSize;
public int BaseNameLength;
public int BaseRecursionDepth;
}
internal class RctOptions : ResourceOptions
{
public string Password;
}
[Serializable]
public class RctScheme : ResourceScheme
{
public Dictionary<string, string> KnownKeys;
}
[Export(typeof(ImageFormat))]
public sealed class RctFormat : ImageFormat
{
public override string Tag { get { return "RCT"; } }
public override string Description { get { return "Majiro game engine RGB image format"; } }
public override uint Signature { get { return 0x9a925a98; } }
public override bool CanWrite { get { return true; } }
public RctFormat ()
{
Settings = new[] { OverlayFrames, ApplyMask };
}
LocalResourceSetting OverlayFrames = new LocalResourceSetting ("RCTOverlayFrames");
LocalResourceSetting ApplyMask = new LocalResourceSetting ("RCTApplyMask");
public const int BaseRecursionLimit = 8;
public static Dictionary<string, string> KnownKeys = new Dictionary<string, string>();
public override ResourceScheme Scheme
{
get { return new RctScheme { KnownKeys = KnownKeys }; }
set { KnownKeys = ((RctScheme)value).KnownKeys; }
}
public override ImageMetaData ReadMetaData (IBinaryStream stream)
{
var header = stream.ReadHeader (0x14);
if (header[4] != 'T')
return null;
int encryption = header[5];
if (encryption != 'C' && encryption != 'S')
return null;
bool is_encrypted = 'S' == encryption;
if (header[6] != '0')
return null;
int version = header[7] - '0';
if (version != 0 && version != 1)
return null;
uint width = header.ToUInt32 (8);
uint height = header.ToUInt32 (12);
int data_size = header.ToInt32 (16);
int additional_size = 0;
if (1 == version)
{
additional_size = stream.ReadUInt16();
}
if (width > 0x8000 || height > 0x8000)
return null;
return new RctMetaData
{
Width = width,
Height = height,
OffsetX = 0,
OffsetY = 0,
BPP = 24,
Version = version,
IsEncrypted = is_encrypted,
DataOffset = (uint)stream.Position,
DataSize = data_size,
BaseNameLength = additional_size,
};
}
byte[] Key = null;
public override ImageData Read (IBinaryStream file, ImageMetaData info)
{
var meta = (RctMetaData)info;
var pixels = ReadPixelsData (file, meta);
if (ApplyMask.Get<bool>())
{
var mask_name = Path.GetFileNameWithoutExtension (meta.FileName) + "_.rc8";
mask_name = VFS.ChangeFileName (meta.FileName, mask_name);
if (VFS.FileExists (mask_name))
{
try
{
return ApplyMaskToImage (meta, pixels, mask_name);
}
catch { /* ignore mask read errors */ }
}
}
return ImageData.Create (meta, PixelFormats.Bgr24, null, pixels, (int)meta.Width*3);
}
static readonly ResourceInstance<ImageFormat> s_rc8_format = new ResourceInstance<ImageFormat> ("RC8");
ImageData ApplyMaskToImage (RctMetaData info, byte[] image, string mask_name)
{
using (var mask_file = VFS.OpenBinaryStream (mask_name))
{
var mask_info = s_rc8_format.Value.ReadMetaData (mask_file);
if (null == mask_info
|| info.Width != mask_info.Width || info.Height != mask_info.Height)
throw new InvalidFormatException();
using (var reader = new Rc8Format.Reader (mask_file, mask_info))
{
reader.Unpack();
var palette = reader.Palette;
int dst_stride = (int)info.Width * 4;
var pixels = new byte[dst_stride * (int)info.Height];
var alpha = reader.Data;
int a_src = 0;
int src = 0;
for (int dst = 0; dst < pixels.Length; dst += 4)
{
pixels[dst ] = image[src++];
pixels[dst+1] = image[src++];
pixels[dst+2] = image[src++];
var color = palette[alpha[a_src++]];
pixels[dst+3] = (byte)~((color.B + color.G + color.R) / 3);
}
return ImageData.Create (info, PixelFormats.Bgra32, null, pixels, dst_stride);
}
}
}
byte[] CombineImage (byte[] base_image, byte[] overlay)
{
for (int i = 2; i < base_image.Length; i += 3)
{
if (0 == overlay[i-2] && 0 == overlay[i-1] && 0xff == overlay[i])
{
overlay[i-2] = base_image[i-2];
overlay[i-1] = base_image[i-1];
overlay[i] = base_image[i];
}
}
return overlay;
}
byte[] ReadPixelsData (IBinaryStream file, RctMetaData meta)
{
byte[] base_image = null;
if (meta.FileName != null && meta.BaseNameLength > 0 && OverlayFrames.Get<bool>()
&& meta.BaseRecursionDepth < BaseRecursionLimit)
base_image = ReadBaseImage (file, meta);
file.Position = meta.DataOffset + meta.BaseNameLength;
if (meta.IsEncrypted)
file = OpenEncryptedStream (file, meta.DataSize);
try
{
using (var reader = new Reader (file, meta))
{
reader.Unpack();
if (base_image != null)
return CombineImage (base_image, reader.Data);
return reader.Data;
}
}
catch
{
if (meta.IsEncrypted)
Key = null; // probably incorrect encryption scheme caused exception, reset key
throw;
}
}
byte[] ReadBaseImage (IBinaryStream file, RctMetaData meta)
{
try
{
file.Position = meta.DataOffset;
var name = file.ReadCString (meta.BaseNameLength);
string dir_name = VFS.GetDirectoryName (meta.FileName);
name = VFS.CombinePath (dir_name, name);
if (VFS.FileExists (name))
{
using (var base_file = VFS.OpenBinaryStream (name))
{
var base_info = ReadMetaData (base_file) as RctMetaData;
if (null != base_info
&& meta.Width == base_info.Width && meta.Height == base_info.Height)
{
base_info.BaseRecursionDepth = meta.BaseRecursionDepth + 1;
base_info.FileName = name;
return ReadPixelsData (base_file, base_info);
}
}
}
}
catch { /* ignore baseline image read errors */ }
return null;
}
IBinaryStream OpenEncryptedStream (IBinaryStream file, int data_size)
{
if (null == Key)
{
var password = QueryPassword();
if (string.IsNullOrEmpty (password))
throw new UnknownEncryptionScheme();
Key = InitDecryptionKey (password);
}
byte[] data = file.ReadBytes (data_size);
if (data.Length != data_size)
throw new EndOfStreamException();
for (int i = 0; i < data.Length; ++i)
{
data[i] ^= Key[i & 0x3FF];
}
return new BinMemoryStream (data, file.Name);
}
private byte[] InitDecryptionKey (string password)
{
byte[] bin_pass = Encodings.cp932.GetBytes (password);
uint crc32 = Crc32.Compute (bin_pass, 0, bin_pass.Length);
byte[] key_table = new byte[0x400];
unsafe
{
fixed (byte* key_ptr = key_table)
{
uint* key32 = (uint*)key_ptr;
for (int i = 0; i < 0x100; ++i)
*key32++ = crc32 ^ Crc32.Table[(i + crc32) & 0xFF];
}
}
return key_table;
}
private string QueryPassword ()
{
if (VFS.IsVirtual)
{
var password = FindImageKey();
if (!string.IsNullOrEmpty (password))
return password;
}
var options = Query<RctOptions> (arcStrings.ArcImageEncrypted);
return options.Password;
}
static readonly ResourceInstance<ArchiveFormat> s_Majiro = new ResourceInstance<ArchiveFormat> ("MAJIRO");
private string FindImageKey ()
{
var arc_fs = VFS.Top as ArchiveFileSystem;
if (null == arc_fs)
return null;
try
{
// look for "start.mjo" within "scenario.arc" archive
var src_name = arc_fs.Source.File.Name;
var scenario_arc_name = Path.Combine (Path.GetDirectoryName (src_name), "scenario.arc");
if (!File.Exists (scenario_arc_name))
return null;
byte[] script;
using (var file = new ArcView (scenario_arc_name))
using (var arc = s_Majiro.Value.TryOpen (file))
{
if (null == arc)
return null;
var start_mjo = arc.Dir.First (e => e.Name == "start.mjo");
using (var mjo = arc.OpenEntry (start_mjo))
{
script = new byte[mjo.Length];
mjo.Read (script, 0, script.Length);
}
}
if (Binary.AsciiEqual (script, "MajiroObjX1.000"))
DecryptMjo (script);
else if (!Binary.AsciiEqual (script, "MjPlainBytecode"))
return null;
// locate key within start.mjo script
int n = script.ToInt32 (0x18);
for (int offset = 0x20 + n * 8; offset < script.Length - 4; ++offset)
{
offset = Array.IndexOf<byte> (script, 1, offset);
if (-1 == offset)
break;
if (8 != script[offset+1])
continue;
int str_length = script.ToUInt16 (offset+2);
if (0 == str_length || str_length + 12 > script.Length - offset
|| 0x0835 != script.ToUInt16 (offset+str_length+4)
|| 0x7A7B6ED4 != script.ToUInt32 (offset+str_length+6))
continue;
offset += 4;
int end = Array.IndexOf<byte> (script, 0, offset, str_length);
if (-1 != end)
str_length = end - offset;
var password = Encodings.cp932.GetString (script, offset, str_length);
Trace.WriteLine (string.Format ("Found key in start.mjo [{0}]", password), "[RCT]");
return password;
}
}
catch { /* ignore errors */ }
return null;
}
private void DecryptMjo (byte[] data)
{
int offset = 0x1C + 8 * data.ToInt32 (0x18);
if (offset < 0x1C || offset >= data.Length - 4)
return;
int count = data.ToInt32 (offset);
offset += 4;
if (count <= 0 || count > data.Length - offset)
return;
Debug.Assert (Crc32.Table.Length == 0x100);
unsafe
{
fixed (uint* table = Crc32.Table)
{
byte* key = (byte*)table;
for (int i = 0; i < count; ++i)
data[offset+i] ^= key[i & 0x3FF];
}
}
}
public override ResourceOptions GetDefaultOptions ()
{
return new RctOptions { Password = Properties.Settings.Default.RCTPassword };
}
public override ResourceOptions GetOptions (object widget)
{
var w = widget as GUI.WidgetRCT;
if (null != w)
Properties.Settings.Default.RCTPassword = w.Password.Text;
return GetDefaultOptions();
}
public override object GetAccessWidget ()
{
return new GUI.WidgetRCT();
}
public override void Write (Stream file, ImageData image)
{
using (var writer = new Writer (file))
writer.Pack (image.Bitmap);
}
internal class Writer : IDisposable
{
BinaryWriter m_out;
uint[] m_input;
int m_width;
int m_height;
int[] m_shift_table = new int[32];
const int MaxThunkSize = 0xffff + 0x7f;
const int MaxMatchSize = 0xffff;
struct ChunkPosition
{
public ushort Offset;
public ushort Length;
}
public Writer (Stream output)
{
m_out = new BinaryWriter (output, Encoding.ASCII, true);
}
void PrepareInput (BitmapSource bitmap)
{
m_width = bitmap.PixelWidth;
m_height = bitmap.PixelHeight;
int pixels = m_width*m_height;
m_input = new uint[pixels];
if (bitmap.Format != PixelFormats.Bgr32)
{
var converted_bitmap = new FormatConvertedBitmap();
converted_bitmap.BeginInit();
converted_bitmap.Source = bitmap;
converted_bitmap.DestinationFormat = PixelFormats.Bgr32;
converted_bitmap.EndInit();
bitmap = converted_bitmap;
}
unsafe
{
fixed (uint* buffer = m_input)
{
bitmap.CopyPixels (Int32Rect.Empty, (IntPtr)buffer, pixels*4, m_width*4);
}
}
InitShiftTable (m_width);
}
void InitShiftTable (int width)
{
for (int i = 0; i < 32; ++i)
{
int shift = Reader.ShiftTable[i];
int shift_row = shift & 0x0f;
shift >>= 4;
shift_row *= width;
shift -= shift_row;
m_shift_table[i] = shift;
}
}
List<byte> m_buffer = new List<byte>();
int m_buffer_size;
public void Pack (BitmapSource bitmap)
{
PrepareInput (bitmap);
long data_offset = 0x14;
m_out.BaseStream.Position = data_offset;
uint pixel = m_input[0];
m_out.Write ((byte)pixel);
m_out.Write ((byte)(pixel >> 8));
m_out.Write ((byte)(pixel >> 16));
m_buffer.Clear();
m_buffer_size = 0;
int last = m_input.Length;
int current = 1;
while (current != last)
{
var chunk_pos = FindLongest (current, last);
if (chunk_pos.Length > 0)
{
Flush();
WritePos (chunk_pos);
current += chunk_pos.Length;
}
else
{
WritePixel (m_input[current++]);
}
}
Flush();
var data_size = m_out.BaseStream.Position - data_offset;
m_out.BaseStream.Position = 0;
WriteHeader ((uint)data_size);
}
void WriteHeader (uint data_size)
{
m_out.Write (0x9a925a98u);
m_out.Write (0x30304354u);
m_out.Write (m_width);
m_out.Write (m_height);
m_out.Write (data_size);
}
void WritePixel (uint pixel)
{
if (MaxThunkSize == m_buffer_size)
Flush();
m_buffer.Add ((byte)pixel);
m_buffer.Add ((byte)(pixel >> 8));
m_buffer.Add ((byte)(pixel >> 16));
++m_buffer_size;
}
void Flush ()
{
if (0 != m_buffer.Count)
{
if (m_buffer_size > 0x7f)
{
m_out.Write ((byte)0x7f);
m_out.Write ((ushort)(m_buffer_size-0x80));
}
else
m_out.Write ((byte)(m_buffer_size-1));
foreach (var b in m_buffer)
m_out.Write (b);
m_buffer.Clear();
m_buffer_size = 0;
}
}
ChunkPosition FindLongest (int buf_begin, int buf_end)
{
buf_end = Math.Min (buf_begin + MaxMatchSize, buf_end);
ChunkPosition pos = new ChunkPosition { Offset = 0, Length = 0 };
for (int i = 0; i < 32; ++i)
{
int offset = buf_begin + m_shift_table[i];
if (offset < 0)
continue;
if (m_input[offset] != m_input[buf_begin])
continue;
var last = Mismatch (buf_begin+1, buf_end, offset+1);
int weight = last - offset;
if (weight > pos.Length)
{
pos.Offset = (ushort)i;
pos.Length = (ushort)weight;
}
}
return pos;
}
int Mismatch (int first1, int last1, int first2)
{
while (first1 != last1 && m_input[first1] == m_input[first2])
{
++first1;
++first2;
}
return first2;
}
void WritePos (ChunkPosition pos)
{
int code = (pos.Offset << 2) | 0x80;
if (pos.Length > 3)
code |= 3;
else
code |= pos.Length - 1;
m_out.Write ((byte)code);
if (pos.Length > 3)
m_out.Write ((ushort)(pos.Length - 4));
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
{
m_out.Dispose();
}
disposed = true;
}
}
#endregion
}
internal sealed class Reader : IDisposable
{
private IBinaryStream m_input;
private uint m_width;
private byte[] m_data;
public byte[] Data { get { return m_data; } }
public Reader (IBinaryStream file, RctMetaData info)
{
m_width = info.Width;
m_data = new byte[m_width * info.Height * 3];
m_input = file;
}
internal static readonly sbyte[] ShiftTable = new sbyte[] {
-16, -32, -48, -64, -80, -96,
49, 33, 17, 1, -15, -31, -47,
50, 34, 18, 2, -14, -30, -46,
51, 35, 19, 3, -13, -29, -45,
36, 20, 4, -12, -28,
};
public void Unpack ()
{
int pixels_remaining = m_data.Length;
int data_pos = 0;
int eax = 0;
while (pixels_remaining > 0)
{
int count = eax*3 + 3;
if (count > pixels_remaining)
throw new InvalidFormatException();
pixels_remaining -= count;
if (count != m_input.Read (m_data, data_pos, count))
throw new InvalidFormatException();
data_pos += count;
while (pixels_remaining > 0)
{
eax = m_input.ReadByte();
if (0 == (eax & 0x80))
{
if (0x7f == eax)
eax += m_input.ReadUInt16();
break;
}
int shift_index = eax >> 2;
eax &= 3;
if (3 == eax)
eax += m_input.ReadUInt16();
count = eax*3 + 3;
if (pixels_remaining < count)
throw new InvalidFormatException();
pixels_remaining -= count;
int shift = ShiftTable[shift_index & 0x1f];
int shift_row = shift & 0x0f;
shift >>= 4;
shift_row *= (int)m_width;
shift -= shift_row;
shift *= 3;
if (shift >= 0 || data_pos+shift < 0)
throw new InvalidFormatException();
Binary.CopyOverlapped (m_data, data_pos+shift, data_pos, count);
data_pos += count;
}
}
}
#region IDisposable Members
public void Dispose ()
{
GC.SuppressFinalize (this);
}
#endregion
}
}
}
| |
using System;
using System.Diagnostics;
using i64 = System.Int64;
using u8 = System.Byte;
using u32 = System.UInt32;
using u64 = System.UInt64;
namespace Community.CsharpSqlite
{
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement a pseudo-random number
** generator (PRNG) for SQLite.
**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/* All threads share a single random number generator.
** This structure is the current state of the generator.
*/
public class sqlite3PrngType
{
public bool isInit; /* True if initialized */
public int i;
public int j; /* State variables */
public u8[] s = new u8[256]; /* State variables */
public sqlite3PrngType Copy()
{
sqlite3PrngType cp = (sqlite3PrngType)MemberwiseClone();
cp.s = new u8[s.Length];
Array.Copy( s, cp.s, s.Length );
return cp;
}
}
public static sqlite3PrngType sqlite3Prng = new sqlite3PrngType();
/*
** Get a single 8-bit random value from the RC4 PRNG. The Mutex
** must be held while executing this routine.
**
** Why not just use a library random generator like lrand48() for this?
** Because the OP_NewRowid opcode in the VDBE depends on having a very
** good source of random numbers. The lrand48() library function may
** well be good enough. But maybe not. Or maybe lrand48() has some
** subtle problems on some systems that could cause problems. It is hard
** to know. To minimize the risk of problems due to bad lrand48()
** implementations, SQLite uses this random number generator based
** on RC4, which we know works very well.
**
** (Later): Actually, OP_NewRowid does not depend on a good source of
** randomness any more. But we will leave this code in all the same.
*/
static u8 randomu8()
{
u8 t;
/* The "wsdPrng" macro will resolve to the pseudo-random number generator
** state vector. If writable static data is unsupported on the target,
** we have to locate the state vector at run-time. In the more common
** case where writable static data is supported, wsdPrng can refer directly
** to the "sqlite3Prng" state vector declared above.
*/
#if SQLITE_OMIT_WSD
struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
//# define wsdPrng p[0]
#else
//# define wsdPrng sqlite3Prng
sqlite3PrngType wsdPrng = sqlite3Prng;
#endif
/* Initialize the state of the random number generator once,
** the first time this routine is called. The seed value does
** not need to contain a lot of randomness since we are not
** trying to do secure encryption or anything like that...
**
** Nothing in this file or anywhere else in SQLite does any kind of
** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
** number generator) not as an encryption device.
*/
if ( !wsdPrng.isInit )
{
int i;
u8[] k = new u8[256];
wsdPrng.j = 0;
wsdPrng.i = 0;
sqlite3OsRandomness( sqlite3_vfs_find( "" ), 256, k );
for ( i = 0; i < 255; i++ )
{
wsdPrng.s[i] = (u8)i;
}
for ( i = 0; i < 255; i++ )
{
wsdPrng.j = (u8)( wsdPrng.j + wsdPrng.s[i] + k[i] );
t = wsdPrng.s[wsdPrng.j];
wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
wsdPrng.s[i] = t;
}
wsdPrng.isInit = true;
}
/* Generate and return single random u8
*/
wsdPrng.i++;
t = wsdPrng.s[(u8)wsdPrng.i];
wsdPrng.j = (u8)( wsdPrng.j + t );
wsdPrng.s[(u8)wsdPrng.i] = wsdPrng.s[wsdPrng.j];
wsdPrng.s[wsdPrng.j] = t;
t += wsdPrng.s[(u8)wsdPrng.i];
return wsdPrng.s[t];
}
/*
** Return N random u8s.
*/
static void sqlite3_randomness( int N, ref i64 pBuf )
{
u8[] zBuf = new u8[N];
pBuf = 0;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_PRNG );
#endif
sqlite3_mutex_enter( mutex );
while ( N-- > 0 )
{
pBuf = (u32)( ( pBuf << 8 ) + randomu8() );// zBuf[N] = randomu8();
}
sqlite3_mutex_leave( mutex );
}
static void sqlite3_randomness( byte[] pBuf, int Offset, int N )
{
i64 iBuf = System.DateTime.Now.Ticks;
#if SQLITE_THREADSAFE
sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
#endif
sqlite3_mutex_enter( mutex );
while ( N-- > 0 )
{
iBuf = (u32)( ( iBuf << 8 ) + randomu8() );// zBuf[N] = randomu8();
pBuf[Offset++] = (byte)iBuf;
}
sqlite3_mutex_leave( mutex );
}
#if !SQLITE_OMIT_BUILTIN_TEST
/*
** For testing purposes, we sometimes want to preserve the state of
** PRNG and restore the PRNG to its saved state at a later time, or
** to reset the PRNG to its initial state. These routines accomplish
** those tasks.
**
** The sqlite3_test_control() interface calls these routines to
** control the PRNG.
*/
static sqlite3PrngType sqlite3SavedPrng = null;
static void sqlite3PrngSaveState()
{
sqlite3SavedPrng = sqlite3Prng.Copy();
// memcpy(
// &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
// &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
// sizeof(sqlite3Prng)
//);
}
static void sqlite3PrngRestoreState()
{
sqlite3Prng = sqlite3SavedPrng.Copy();
//memcpy(
// &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
// &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
// sizeof(sqlite3Prng)
//);
}
static void sqlite3PrngResetState()
{
sqlite3Prng.isInit = false;// GLOBAL(struct sqlite3PrngType, sqlite3Prng).isInit = 0;
}
#endif //* SQLITE_OMIT_BUILTIN_TEST */
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.