context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// 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 Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using VSLangProj;
namespace Microsoft.VisualStudioTools.Project.Automation
{
internal class OAProjectConfigurationProperties : ConnectionPointContainer, ProjectConfigurationProperties, IConnectionPointContainer, IEventSource<IPropertyNotifySink>
{
private readonly ProjectNode _project;
private readonly List<IPropertyNotifySink> _sinks = new List<IPropertyNotifySink>();
private readonly HierarchyListener _hierarchyListener;
public OAProjectConfigurationProperties(ProjectNode node)
{
this._project = node;
AddEventSource<IPropertyNotifySink>(this);
this._hierarchyListener = new HierarchyListener(this._project, this);
}
#region ProjectConfigurationProperties Members
public bool AllowUnsafeBlocks
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public uint BaseAddress
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool CheckForOverflowUnderflow
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string ConfigurationOverrideFile
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool DebugSymbols
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string DefineConstants
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool DefineDebug
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool DefineTrace
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string DocumentationFile
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool EnableASPDebugging
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool EnableASPXDebugging
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool EnableSQLServerDebugging
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool EnableUnmanagedDebugging
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string ExtenderCATID => throw new NotImplementedException();
public object ExtenderNames => throw new NotImplementedException();
public uint FileAlignment
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool IncrementalBuild
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string IntermediatePath
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool Optimize
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string OutputPath
{
get
{
return this._project.Site.GetUIThread().Invoke(() => this._project.GetProjectProperty("OutputPath"));
}
set
{
this._project.Site.GetUIThread().Invoke(() => this._project.SetProjectProperty("OutputPath", value));
}
}
public bool RegisterForComInterop
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool RemoteDebugEnabled
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string RemoteDebugMachine
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool RemoveIntegerChecks
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public prjStartAction StartAction
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string StartArguments
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string StartPage
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string StartProgram
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string StartURL
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool StartWithIE
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string StartWorkingDirectory
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public bool TreatWarningsAsErrors
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public prjWarningLevel WarningLevel
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string __id => throw new NotImplementedException();
public object get_Extender(string ExtenderName)
{
throw new NotImplementedException();
}
#endregion
#region IEventSource<IPropertyNotifySink> Members
public void OnSinkAdded(IPropertyNotifySink sink)
{
this._sinks.Add(sink);
}
public void OnSinkRemoved(IPropertyNotifySink sink)
{
this._sinks.Remove(sink);
}
#endregion
internal class HierarchyListener : IVsHierarchyEvents
{
private readonly IVsHierarchy _hierarchy;
private readonly uint _cookie;
private readonly OAProjectConfigurationProperties _props;
public HierarchyListener(IVsHierarchy hierarchy, OAProjectConfigurationProperties props)
{
this._hierarchy = hierarchy;
this._props = props;
ErrorHandler.ThrowOnFailure(this._hierarchy.AdviseHierarchyEvents(this, out this._cookie));
}
~HierarchyListener()
{
_hierarchy.UnadviseHierarchyEvents(_cookie);
}
#region IVsHierarchyEvents Members
public int OnInvalidateIcon(IntPtr hicon)
{
return VSConstants.S_OK;
}
public int OnInvalidateItems(uint itemidParent)
{
return VSConstants.S_OK;
}
public int OnItemAdded(uint itemidParent, uint itemidSiblingPrev, uint itemidAdded)
{
return VSConstants.S_OK;
}
public int OnItemDeleted(uint itemid)
{
return VSConstants.S_OK;
}
public int OnItemsAppended(uint itemidParent)
{
return VSConstants.S_OK;
}
public int OnPropertyChanged(uint itemid, int propid, uint flags)
{
foreach (var sink in this._props._sinks)
{
sink.OnChanged(propid);
}
return VSConstants.S_OK;
}
#endregion
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: NUnitTestCase.cs
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.ComponentModel;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Android.Util;
using Java.Lang;
using Java.Lang.Reflect;
using Junit.Framework;
using NUnit.Framework;
namespace Dot42.Test
{
/// <summary>
/// TestCase that supports the most commonly used NUnit test attributes.
/// </summary>
[Include(TypeCondition = typeof(TestFixtureAttribute))]
public class NUnitTestCase : TestCase
{
private TestSuite suite;
private MethodInfo method;
private MethodInfo setupMethod;
private MethodInfo teardownMethod;
private object instance;
private ExpectedExceptionAttribute expectedException;
private NUnit.Framework.IgnoreAttribute ignore;
private bool isAsync;
/// <summary>
/// Create the test suite.
/// </summary>
private TestSuite GetTestSuite(Type type)
{
var suite = new TestSuite();
suite.Name = GetType().GetSimpleName();
MethodInfo localSetupMethod = null;
MethodInfo localTeardownMethod = null;
foreach (var method in type.GetMethods())
{
if (GetCustomAttribute<SetUpAttribute>(method) == null)
continue;
localSetupMethod = method;
break;
}
foreach (var method in type.GetMethods())
{
if (GetCustomAttribute<TearDownAttribute>(method) == null)
continue;
localTeardownMethod = method;
break;
}
foreach (var method in type.GetMethods())
{
if (GetCustomAttribute<TestAttribute>(method) == null)
continue;
var instance = (NUnitTestCase)type.NewInstance();
instance.SetTestMethod(method, localSetupMethod, localTeardownMethod, this);
suite.AddTest(instance);
}
return suite;
}
/// <summary>
/// Include 1 dummy test to trigger this class to be included.
/// </summary>
//[Include]
[EditorBrowsable(EditorBrowsableState.Never)]
public void test()
{
}
/// <summary>
/// Prepare the suite.
/// </summary>
protected internal sealed override void SetUp()
{
if (method == null)
{
suite = GetTestSuite(GetType());
suite.Name = GetType().Name;
}
else
{
base.SetUp();
try
{
if (setupMethod != null)
{
setupMethod.Invoke(instance, null);
}
}
catch (InvocationTargetException ex)
{
ex.FillInStackTrace();
throw ex.GetTargetException();
}
}
}
protected internal override void TearDown()
{
base.TearDown();
try
{
if (teardownMethod != null)
{
teardownMethod.Invoke(instance, null);
}
}
catch (InvocationTargetException ex)
{
ex.FillInStackTrace();
throw ex.GetTargetException();
}
}
/// <summary>
/// Prepare the suite and run the tests.
/// </summary>
public override void Run(TestResult result)
{
if (method == null)
{
SetUp();
if (suite == null)
throw new InvalidOperationException("Suite not created");
suite.Run(result);
}
else
{
if (ignore != null)
{
// Ignore this test
//result.
}
else
{
base.Run(result);
}
}
}
/// <summary>
/// Gets the number of tests.
/// </summary>
public sealed override int CountTestCases()
{
if (method == null)
{
return suite.CountTestCases();
}
return base.CountTestCases();
}
/// <summary>
/// Gets the first attribute of type T that is attached to the given method.
/// </summary>
/// <returns>Null if there is not such attribute.</returns>
private static T GetCustomAttribute<T>(MethodInfo method)
{
var attr = method.GetCustomAttributes(typeof (T), false);
if (attr.Length == 0)
return default(T);
return (T) attr[0];
}
/// <summary>
/// Default ctor
/// </summary>
public void SetTestMethod(MethodInfo method, MethodInfo setupMethod, MethodInfo teardownMethod, object instance)
{
Name = method.Name;
this.method = method;
this.setupMethod = setupMethod;
this.teardownMethod = teardownMethod;
this.instance = instance;
expectedException = GetCustomAttribute<ExpectedExceptionAttribute>(method);
ignore = GetCustomAttribute<NUnit.Framework.IgnoreAttribute>(method);
isAsync = GetCustomAttribute<System.Runtime.CompilerServices.AsyncStateMachineAttribute>(method) != null;
}
/// <summary>
/// Override to run the test and assert its state.
/// </summary>
protected internal override void RunTest()
{
try
{
if (isAsync)
{
if (method.ReturnType == typeof(void)) //-- see case 874
//if (method.ReturnType == JavaVoid.TYPE)
{
RunVoidAsyncMethod();
}
else
{
RunTaskAsyncMethod();
}
}
else
{
RunMethod();
}
if (expectedException != null)
{
throw new AssertionFailedError("Expected exception");
}
}
catch (InvocationTargetException ex)
{
// Method has thrown an exception.
ex.FillInStackTrace();
var exception = ex.GetTargetException();
// Is this an expected exception
if (expectedException != null)
{
if (expectedException.ExpectedException == exception.GetType())
{
// It is the expected exception
return;
}
}
throw exception;
}
catch (IllegalAccessException ex)
{
// Cannot invoke the method
ex.FillInStackTrace();
throw ex;
}
}
private void RunMethod()
{
method.Invoke(instance, null);
}
private void RunVoidAsyncMethod()
{
var previousContext = SynchronizationContext.Current;
var currentContext = new AsyncSynchronizationContext();
SynchronizationContext.SetSynchronizationContext(currentContext);
try
{
method.Invoke(instance, null);
currentContext.WaitForPendingOperationsToComplete();
}
finally
{
SynchronizationContext.SetSynchronizationContext(previousContext);
}
}
private void RunTaskAsyncMethod()
{
object result = method.Invoke(instance, null);
var task = result as Task;
if (task != null)
{
task.Wait();
}
else
{
throw new InvalidCastException("async result cannot be cast to Task or Task<T>");
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.RecoveryServices.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// JobDetailsOperations operations.
/// </summary>
internal partial class JobDetailsOperations : IServiceOperations<RecoveryServicesBackupClient>, IJobDetailsOperations
{
/// <summary>
/// Initializes a new instance of the JobDetailsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal JobDetailsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Gets exteded information associated with the job.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='jobName'>
/// Name of the job whose details are to be fetched.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<JobResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string jobName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (jobName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "jobName");
}
string apiVersion = "2017-07-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("jobName", jobName);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupJobs/{jobName}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{jobName}", System.Uri.EscapeDataString(jobName));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<JobResource>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<JobResource>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Paths operations.
/// </summary>
public partial class Paths : IServiceOperations<AutoRestParameterizedCustomHostTestClient>, IPaths
{
/// <summary>
/// Initializes a new instance of the Paths class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Paths(AutoRestParameterizedCustomHostTestClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestParameterizedCustomHostTestClient
/// </summary>
public AutoRestParameterizedCustomHostTestClient Client { get; private set; }
/// <summary>
/// Get a 200 to test a valid base uri
/// </summary>
/// <param name='vault'>
/// The vault name, e.g. https://myvault
/// </param>
/// <param name='secret'>
/// Secret value.
/// </param>
/// <param name='keyName'>
/// The key name with value 'key1'.
/// </param>
/// <param name='keyVersion'>
/// The key version. Default value 'v1'.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> GetEmptyWithHttpMessagesAsync(string vault, string secret, string keyName, string keyVersion = "v1", Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vault == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vault");
}
if (secret == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "secret");
}
if (this.Client.DnsSuffix == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.DnsSuffix");
}
if (keyName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "keyName");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("vault", vault);
tracingParameters.Add("secret", secret);
tracingParameters.Add("keyName", keyName);
tracingParameters.Add("keyVersion", keyVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri;
var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "customuri/{subscriptionId}/{keyName}";
_url = _url.Replace("{vault}", vault);
_url = _url.Replace("{secret}", secret);
_url = _url.Replace("{dnsSuffix}", this.Client.DnsSuffix);
_url = _url.Replace("{keyName}", Uri.EscapeDataString(keyName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (keyVersion != null)
{
_queryParameters.Add(string.Format("keyVersion={0}", Uri.EscapeDataString(keyVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// 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,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.PythonTools;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.VisualStudioTools;
using TestUtilities;
using TestUtilities.Python;
using TestUtilities.UI;
using TestUtilities.UI.Python;
using Path = System.IO.Path;
namespace PythonToolsUITests {
public class EnvironmentUITests {
const string TestPackageSpec = "ptvsd==2.2.0";
const string TestPackageDisplay = "ptvsd (2.2.0)";
static DefaultInterpreterSetter InitPython2(PythonVisualStudioApp app) {
var dis = app.SelectDefaultInterpreter(PythonPaths.Python27 ?? PythonPaths.Python27_x64);
var pm = app.OptionsService.GetPackageManagers(dis.CurrentDefault).FirstOrDefault();
try {
if (!pm.GetInstalledPackageAsync(new PackageSpec("virtualenv"), CancellationTokens.After60s).WaitAndUnwrapExceptions().IsValid) {
pm.InstallAsync(new PackageSpec("virtualenv"), new TestPackageManagerUI(), CancellationTokens.After60s).WaitAndUnwrapExceptions();
}
var r = dis;
dis = null;
return r;
} finally {
dis?.Dispose();
}
}
static DefaultInterpreterSetter InitPython3(PythonVisualStudioApp app) {
return app.SelectDefaultInterpreter(
PythonPaths.Python37 ?? PythonPaths.Python37_x64 ??
PythonPaths.Python36 ?? PythonPaths.Python36_x64 ??
PythonPaths.Python35 ?? PythonPaths.Python35_x64 ??
PythonPaths.Python34 ?? PythonPaths.Python34_x64 ??
PythonPaths.Python33 ?? PythonPaths.Python33_x64
);
}
static EnvDTE.Project CreateTemporaryProject(VisualStudioApp app, [CallerMemberName] string projectName = null) {
var project = app.CreateProject(
PythonVisualStudioApp.TemplateLanguageName,
PythonVisualStudioApp.PythonApplicationTemplate,
TestData.GetTempPath(),
projectName ?? Path.GetFileNameWithoutExtension(Path.GetRandomFileName())
);
Assert.IsNotNull(project, "Project was not created");
return project;
}
public void InstallUninstallPackage(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
var env = app.CreateProjectVirtualEnvironment(project, out string envName);
env.Select();
app.ExecuteCommand("Python.InstallPackage", "/p:" + TestPackageSpec);
var azure = app.SolutionExplorerTreeView.WaitForChildOfProject(
project,
TimeSpan.FromSeconds(30),
Strings.Environments,
envName,
TestPackageDisplay
);
azure.Select();
using (var confirmation = AutomationDialog.FromDte(app, "Edit.Delete")) {
confirmation.OK();
}
app.SolutionExplorerTreeView.WaitForChildOfProjectRemoved(
project,
Strings.Environments,
envName,
TestPackageDisplay
);
}
}
public void CreateInstallRequirementsTxt(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
var projectHome = project.GetPythonProject().ProjectHome;
File.WriteAllText(Path.Combine(projectHome, "requirements.txt"), TestPackageSpec);
var env = app.CreateProjectVirtualEnvironment(project, out string envName);
env.Select();
app.SolutionExplorerTreeView.WaitForChildOfProject(
project,
Strings.Environments,
envName,
TestPackageDisplay
);
}
}
public void InstallGenerateRequirementsTxt(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
var env = app.CreateProjectVirtualEnvironment(project, out string envName);
env.Select();
try {
app.ExecuteCommand("Python.InstallRequirementsTxt", "/y", timeout: 5000);
Assert.Fail("Command should not have executed");
} catch (AggregateException ae) {
ae.Handle(ex => ex is COMException);
} catch (COMException) {
}
var requirementsTxt = Path.Combine(Path.GetDirectoryName(project.FullName), "requirements.txt");
File.WriteAllText(requirementsTxt, TestPackageSpec);
app.ExecuteCommand("Python.InstallRequirementsTxt", "/y");
app.SolutionExplorerTreeView.WaitForChildOfProject(
project,
TimeSpan.FromSeconds(30),
Strings.Environments,
envName,
TestPackageDisplay
);
File.Delete(requirementsTxt);
app.ExecuteCommand("Python.GenerateRequirementsTxt", "/e:\"" + envName + "\"");
app.SolutionExplorerTreeView.WaitForChildOfProject(
project,
"requirements.txt"
);
AssertUtil.ContainsAtLeast(
File.ReadAllLines(requirementsTxt).Select(s => s.Trim()),
TestPackageSpec
);
}
}
public void LoadVEnv(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
var projectName = project.UniqueName;
var env = app.CreateProjectVirtualEnvironment(project, out string envName);
var solution = app.Dte.Solution.FullName;
app.Dte.Solution.Close(true);
app.Dte.Solution.Open(solution);
project = app.Dte.Solution.Item(projectName);
app.OpenSolutionExplorer().WaitForChildOfProject(
project,
TimeSpan.FromSeconds(60),
Strings.Environments,
envName
);
}
}
public void ActivateVEnv(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
Assert.AreNotEqual(null, project.ProjectItems.Item(Path.GetFileNameWithoutExtension(app.Dte.Solution.FullName) + ".py"));
var id0 = (string)project.Properties.Item("InterpreterId").Value;
var env1 = app.CreateProjectVirtualEnvironment(project, out string envName1);
var env2 = app.CreateProjectVirtualEnvironment(project, out string envName2);
// At this point, env2 is active
var id2 = (string)project.Properties.Item("InterpreterId").Value;
Assert.AreNotEqual(id0, id2);
// Activate env1 (previously stored node is now invalid, we need to query again)
env1 = app.OpenSolutionExplorer().WaitForChildOfProject(project, Strings.Environments, envName1);
env1.Select();
app.Dte.ExecuteCommand("Python.ActivateEnvironment");
var id1 = (string)project.Properties.Item("InterpreterId").Value;
Assert.AreNotEqual(id0, id1);
Assert.AreNotEqual(id2, id1);
// Activate env2
app.SolutionExplorerTreeView.SelectProject(project);
app.Dte.ExecuteCommand("Python.ActivateEnvironment", "/env:\"" + envName2 + "\"");
var id2b = (string)project.Properties.Item("InterpreterId").Value;
Assert.AreEqual(id2, id2b);
}
}
public void RemoveVEnv(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
var env = app.CreateProjectVirtualEnvironment(project, out string envName, out string envPath);
env.Select();
using (var removeDeleteDlg = RemoveItemDialog.FromDte(app)) {
removeDeleteDlg.Remove();
}
app.OpenSolutionExplorer().WaitForChildOfProjectRemoved(
project,
Strings.Environments,
envName
);
Assert.IsTrue(Directory.Exists(envPath), envPath);
}
}
public void DeleteVEnv(PythonVisualStudioApp app) {
using (var procs = new ProcessScope("Microsoft.PythonTools.Analyzer"))
using (var dis = InitPython3(app)) {
var options = app.GetService<PythonToolsService>().GeneralOptions;
var oldAutoAnalyze = options.AutoAnalyzeStandardLibrary;
app.OnDispose(() => { options.AutoAnalyzeStandardLibrary = oldAutoAnalyze; options.Save(); });
options.AutoAnalyzeStandardLibrary = false;
options.Save();
var project = CreateTemporaryProject(app);
TreeNode env = app.CreateProjectVirtualEnvironment(project, out string envName, out string envPath);
// Need to wait some more for the database to be loaded.
app.WaitForNoDialog(TimeSpan.FromSeconds(10.0));
for (int retries = 3; !procs.ExitNewProcesses() && retries >= 0; --retries) {
Thread.Sleep(1000);
Console.WriteLine("Failed to close all analyzer processes (remaining retries {0})", retries);
}
env.Select();
using (var removeDeleteDlg = RemoveItemDialog.FromDte(app)) {
removeDeleteDlg.Delete();
}
app.WaitForNoDialog(TimeSpan.FromSeconds(5.0));
app.OpenSolutionExplorer().WaitForChildOfProjectRemoved(
project,
Strings.Environments,
envName
);
for (int retries = 10;
Directory.Exists(envPath) && retries > 0;
--retries) {
Thread.Sleep(1000);
}
Assert.IsFalse(Directory.Exists(envPath), envPath);
}
}
public void DefaultBaseInterpreterSelection(PythonVisualStudioApp app) {
// The project that will be loaded references these environments.
PythonPaths.Python27.AssertInstalled();
PythonPaths.Python37.AssertInstalled();
using (var dis = InitPython3(app)) {
var sln = app.CopyProjectForTest(@"TestData\Environments.sln");
var project = app.OpenProject(sln);
app.OpenSolutionExplorer().SelectProject(project);
app.Dte.ExecuteCommand("Python.ActivateEnvironment", "/env:\"Python 2.7 (32-bit)\"");
var environmentsNode = app.OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments);
environmentsNode.Select();
using (var createVenv = AddVirtualEnvironmentDialogWrapper.FromDte(app)) {
var baseInterp = createVenv.BaseInterpreter;
Assert.AreEqual("Python 2.7 (32-bit)", baseInterp);
createVenv.Cancel();
}
app.Dte.ExecuteCommand("Python.ActivateEnvironment", "/env:\"Python 3.7 (32-bit)\"");
environmentsNode = app.OpenSolutionExplorer().FindChildOfProject(project, Strings.Environments);
environmentsNode.Select();
using (var createVenv = AddVirtualEnvironmentDialogWrapper.FromDte(app)) {
var baseInterp = createVenv.BaseInterpreter;
Assert.AreEqual("Python 3.7 (32-bit)", baseInterp);
createVenv.Cancel();
}
}
}
public void ProjectCreateVEnv(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var pm = app.OptionsService.GetPackageManagers(dis.CurrentDefault).FirstOrDefault();
if (pm.GetInstalledPackageAsync(new PackageSpec("virtualenv"), CancellationTokens.After60s).WaitAndUnwrapExceptions().IsValid) {
if (!pm.UninstallAsync(new PackageSpec("virtualenv"), new TestPackageManagerUI(), CancellationTokens.After60s).WaitAndUnwrapExceptions()) {
Assert.Fail("Failed to uninstall 'virtualenv' from {0}", dis.CurrentDefault.Configuration.GetPrefixPath());
}
}
var project = CreateTemporaryProject(app);
var env = app.CreateProjectVirtualEnvironment(project, out string envName);
Assert.IsNotNull(env);
Assert.IsNotNull(env.Element);
Assert.AreEqual(string.Format("env (Python {0} ({1}))",
dis.CurrentDefault.Configuration.Version,
dis.CurrentDefault.Configuration.Architecture
), envName);
}
}
public void ProjectCreateCondaEnvFromPackages(PythonVisualStudioApp app) {
var project = CreateTemporaryProject(app);
var env = app.CreateProjectCondaEnvironment(project, "python=3.7 requests", null, null, out string envName, out string envPath);
Assert.IsNotNull(env);
Assert.IsNotNull(env.Element);
FileUtils.DeleteDirectory(envPath);
}
public void ProjectCreateCondaEnvFromEnvFile(PythonVisualStudioApp app) {
var envFilePath = CreateTempEnvYml();
var project = CreateTemporaryProject(app);
var envFileItem = project.ProjectItems.AddFromFileCopy(envFilePath);
var env = app.CreateProjectCondaEnvironment(project, null, envFileItem.FileNames[0], envFileItem.FileNames[0], out string envName, out string envPath);
Assert.IsNotNull(env);
Assert.IsNotNull(env.Element);
FileUtils.DeleteDirectory(envPath);
}
public void ProjectAddExistingVEnvLocal(PythonVisualStudioApp app) {
var python = PythonPaths.Python37 ?? PythonPaths.Python36 ?? PythonPaths.Python35 ?? PythonPaths.Python34 ?? PythonPaths.Python33;
python.AssertInstalled();
var project = CreateTemporaryProject(app);
var envPath = TestData.GetTempPath("venv");
FileUtils.CopyDirectory(TestData.GetPath(@"TestData\\Environments\\venv"), envPath);
File.WriteAllText(Path.Combine(envPath, "pyvenv.cfg"),
string.Format(@"home = {0}
include-system-site-packages = false
version = 3.{1}.0", python.PrefixPath, python.Version.ToVersion().Minor));
var env = app.AddProjectLocalCustomEnvironment(project, envPath, null, python.Configuration.Version.ToString(), python.Architecture.ToString(), out string envName);
Assert.IsNotNull(env);
Assert.IsNotNull(env.Element);
Assert.AreEqual(
string.Format("venv (Python 3.{0} (32-bit))", python.Version.ToVersion().Minor),
envName
);
}
public void ProjectAddCustomEnvLocal(PythonVisualStudioApp app) {
var python = PythonPaths.Python37 ?? PythonPaths.Python36 ?? PythonPaths.Python35 ?? PythonPaths.Python34 ?? PythonPaths.Python33;
python.AssertInstalled();
var project = CreateTemporaryProject(app);
var envPath = python.PrefixPath;
var env = app.AddProjectLocalCustomEnvironment(project, envPath, "Test", python.Configuration.Version.ToString(), python.Architecture.ToString(), out string envName);
Assert.IsNotNull(env);
Assert.IsNotNull(env.Element);
Assert.AreEqual(
string.Format("Test", python.Version.ToVersion().Minor),
envName
);
}
public void ProjectAddExistingEnv(PythonVisualStudioApp app) {
var python = PythonPaths.Python37 ?? PythonPaths.Python36 ?? PythonPaths.Python35 ?? PythonPaths.Python34 ?? PythonPaths.Python33;
python.AssertInstalled();
var project = CreateTemporaryProject(app);
var envPath = python.PrefixPath;
var env = app.AddExistingEnvironment(project, envPath, out string envName);
Assert.IsNotNull(env);
Assert.IsNotNull(env.Element);
Assert.AreEqual(
string.Format("Python 3.{0} (32-bit)", python.Version.ToVersion().Minor),
envName
);
}
public void WorkspaceCreateVEnv(PythonVisualStudioApp app) {
var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
globalDefault37.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(globalDefault37)) {
var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37);
// Create virtual environment dialog, it should by default create it
// under the workspace root folder, using the current environment as the base.
// Since there's no other virtual env in the workspace, it should be named "env"
app.CreateWorkspaceVirtualEnvironment(out string baseEnvDesc, out string envPath);
Assert.IsTrue(
PathUtils.IsSameDirectory(Path.Combine(workspaceFolder, "env"), envPath),
"venv should be created in env subfolder of worskpace"
);
Assert.AreEqual(
baseEnvDesc,
globalDefault37.Configuration.Description,
"venv should use current interpreter as base env"
);
var expectedEnvName = "env ({0}, {1})".FormatInvariant(
globalDefault37.Configuration.Version,
globalDefault37.Configuration.ArchitectureString
);
CheckSwitcherEnvironment(app, expectedEnvName);
}
}
public void WorkspaceCreateCondaEnvFromPackages(PythonVisualStudioApp app) {
var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
globalDefault37.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(globalDefault37)) {
var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37);
// Create conda environment dialog, using a list of packages
app.CreateWorkspaceCondaEnvironment("python=3.7 requests", null, null, out _, out string envPath, out string envDesc);
try {
CheckSwitcherEnvironment(app, envDesc);
} finally {
FileUtils.DeleteDirectory(envPath);
}
}
}
public void WorkspaceCreateCondaEnvFromNoPackages(PythonVisualStudioApp app) {
var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
globalDefault37.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(globalDefault37)) {
var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37);
// Create conda environment dialog with no packages
app.CreateWorkspaceCondaEnvironment("", null, null, out _, out string envPath, out string envDesc);
try {
CheckSwitcherEnvironment(app, envDesc);
} finally {
FileUtils.DeleteDirectory(envPath);
}
}
}
public void WorkspaceCreateCondaEnvFromEnvFile(PythonVisualStudioApp app) {
var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
globalDefault37.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(globalDefault37)) {
var workspaceFolder = CreateAndOpenWorkspace(app, globalDefault37);
var envFilePath = CreateTempEnvYml();
// Create conda environment dialog, using a environment.yml
// that is located outside of workspace root.
app.CreateWorkspaceCondaEnvironment(null, envFilePath, null, out _, out string envPath, out string envDesc);
try {
CheckSwitcherEnvironment(app, envDesc);
} finally {
FileUtils.DeleteDirectory(envPath);
}
}
}
public void WorkspaceAddExistingEnv(PythonVisualStudioApp app) {
var python37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
python37.AssertInstalled();
var python27 = PythonPaths.Python27_x64 ?? PythonPaths.Python27;
python27.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(python27)) {
var workspaceFolder = CreateAndOpenWorkspace(app, python27);
// Add existing environment dialog, selecting an already detected environment
app.AddWorkspaceExistingEnvironment(python37.PrefixPath, out string envDesc);
Assert.AreEqual(
string.Format("Python {0} ({1})", python37.Version.ToVersion(), python37.Architecture),
envDesc
);
CheckSwitcherEnvironment(app, envDesc);
}
}
public void WorkspaceAddCustomEnvLocal(PythonVisualStudioApp app) {
var python27 = PythonPaths.Python27_x64 ?? PythonPaths.Python27;
python27.AssertInstalled();
var basePython = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
basePython.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(python27)) {
var workspaceFolder = CreateAndOpenWorkspace(app, python27);
// Create a virtual environment in a folder outside the workspace
// Note: we need to use a real virtual env for this, because the
// workspace factory provider runs the env's python.exe.
var envPath = TestData.GetTempPath("testenv");
basePython.CreatePythonVirtualEnv(envPath);
// Add existing virtual environment dialog, custom path to a
// virtual env located outside of workspace root.
app.AddWorkspaceLocalCustomEnvironment(
envPath,
null,
basePython.Configuration.Version.ToString(),
basePython.Architecture.ToString()
);
var envDesc = string.Format("testenv ({0}, {1})", basePython.Version.ToVersion(), basePython.Architecture);
CheckSwitcherEnvironment(app, envDesc);
}
}
public void LaunchUnknownEnvironment(PythonVisualStudioApp app) {
var sln = app.CopyProjectForTest(@"TestData\Environments\Unknown.sln");
var project = app.OpenProject(sln);
app.ExecuteCommand("Debug.Start");
app.CheckMessageBox(MessageBoxButton.Close, "Global|PythonCore|2.8|x86", "incorrectly configured");
}
private void EnvironmentReplWorkingDirectoryTest(
PythonVisualStudioApp app,
EnvDTE.Project project,
TreeNode env
) {
var path1 = Path.Combine(Path.GetDirectoryName(project.FullName), Guid.NewGuid().ToString("N"));
var path2 = Path.Combine(Path.GetDirectoryName(project.FullName), Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(path1);
Directory.CreateDirectory(path2);
app.OpenSolutionExplorer().SelectProject(project);
app.Dte.ExecuteCommand("Python.Interactive");
using (var window = app.GetInteractiveWindow(string.Format("{0} Interactive", project.Name))) {
Assert.IsNotNull(window, string.Format("Failed to find '{0} Interactive'", project.Name));
app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().SetProjectProperty("WorkingDirectory", path1));
window.Reset();
window.ExecuteText("import os; os.getcwd()").Wait();
window.WaitForTextEnd(
string.Format("'{0}'", path1.Replace("\\", "\\\\")),
">"
);
app.ServiceProvider.GetUIThread().Invoke(() => project.GetPythonProject().SetProjectProperty("WorkingDirectory", path2));
window.Reset();
window.ExecuteText("import os; os.getcwd()").Wait();
window.WaitForTextEnd(
string.Format("'{0}'", path2.Replace("\\", "\\\\")),
">"
);
}
}
public void EnvironmentReplWorkingDirectory(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
app.ServiceProvider.GetUIThread().Invoke(() => {
var pp = project.GetPythonProject();
pp.AddInterpreter(dis.CurrentDefault.Configuration.Id);
});
var envName = dis.CurrentDefault.Configuration.Description;
var sln = app.OpenSolutionExplorer();
var env = sln.FindChildOfProject(project, Strings.Environments, envName);
EnvironmentReplWorkingDirectoryTest(app, project, env);
}
}
public void VirtualEnvironmentReplWorkingDirectory(PythonVisualStudioApp app) {
using (var dis = InitPython3(app)) {
var project = CreateTemporaryProject(app);
var env = app.CreateProjectVirtualEnvironment(project, out _);
EnvironmentReplWorkingDirectoryTest(app, project, env);
}
}
public void SwitcherSingleProject(PythonVisualStudioApp app) {
var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
globalDefault37.AssertInstalled();
var added27 = PythonPaths.Python27_x64 ?? PythonPaths.Python27;
added27.AssertInstalled();
var added36 = PythonPaths.Python36_x64 ?? PythonPaths.Python36;
added36.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(globalDefault37)) {
// Project has no references, uses global default
var project = CreateTemporaryProject(app);
CheckSwitcherEnvironment(app, globalDefault37.Configuration.Description);
// Project has one referenced interpreter
app.ServiceProvider.GetUIThread().Invoke(() => {
var pp = project.GetPythonProject();
pp.AddInterpreter(added27.Configuration.Id);
});
CheckSwitcherEnvironment(app, added27.Configuration.Description);
// Project has two referenced interpreters (active remains the same)
app.ServiceProvider.GetUIThread().Invoke(() => {
var pp = project.GetPythonProject();
pp.AddInterpreter(added36.Configuration.Id);
});
CheckSwitcherEnvironment(app, added27.Configuration.Description);
// No switcher visible when solution closed and no file opened
app.Dte.Solution.Close(SaveFirst: false);
CheckSwitcherEnvironment(app, null);
}
}
public void SwitcherWorkspace(PythonVisualStudioApp app) {
var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
globalDefault37.AssertInstalled();
var python27 = PythonPaths.Python27_x64;
python27.AssertInstalled();
var folders = TestData.GetTempPath();
FileUtils.CopyDirectory(TestData.GetPath("TestData", "EnvironmentsSwitcherFolders"), folders);
var folder1 = Path.Combine(folders, "WorkspaceWithoutSettings");
var folder2 = Path.Combine(folders, "WorkspaceWithSettings");
var folder3 = Path.Combine(folders, "WorkspaceNoPython");
using (var dis = app.SelectDefaultInterpreter(globalDefault37)) {
// Hidden before any file is opened
CheckSwitcherEnvironment(app, null);
// Workspace without PythonSettings.json shows global default
app.OpenFolder(folder1);
app.OpenDocument(Path.Combine(folder1, "app1.py"));
CheckSwitcherEnvironment(app, globalDefault37.Configuration.Description);
// Workspace with PythonSettings.json - Python 2.7 (64-bit)
app.OpenFolder(folder2);
app.OpenDocument(Path.Combine(folder2, "app2.py"));
CheckSwitcherEnvironment(app, python27.Configuration.Description);
// Keep showing even after opening non-python files
app.OpenDocument(Path.Combine(folder2, "app2.cpp"));
CheckSwitcherEnvironment(app, python27.Configuration.Description);
// Workspace without python file
app.OpenFolder(folder3);
CheckSwitcherEnvironment(app, null);
app.OpenDocument(Path.Combine(folder3, "app3.cpp"));
CheckSwitcherEnvironment(app, null);
app.Dte.Solution.Close();
CheckSwitcherEnvironment(app, null);
}
}
public void SwitcherNoProject(PythonVisualStudioApp app) {
var globalDefault37 = PythonPaths.Python37_x64 ?? PythonPaths.Python37;
globalDefault37.AssertInstalled();
using (var dis = app.SelectDefaultInterpreter(globalDefault37)) {
// Loose Python file shows global default
app.OpenDocument(TestData.GetPath("TestData", "Environments", "Program.py"));
CheckSwitcherEnvironment(app, globalDefault37.Configuration.Description);
// No switcher visible when solution closed and no file opened
app.Dte.ActiveWindow.Close();
CheckSwitcherEnvironment(app, null);
// No switcher visible when loose cpp file open
app.OpenDocument(TestData.GetPath("TestData", "Environments", "Program.cpp"));
CheckSwitcherEnvironment(app, null);
}
}
private string CreateAndOpenWorkspace(PythonVisualStudioApp app, PythonVersion expectedFactory) {
var workspaceFolder = TestData.GetTempPath();
FileUtils.CopyDirectory(TestData.GetPath("TestData", "EnvironmentsSwitcherFolders", "WorkspaceWithoutSettings"), workspaceFolder);
app.OpenFolder(workspaceFolder);
app.OpenDocument(Path.Combine(workspaceFolder, "app1.py"));
CheckSwitcherEnvironment(app, expectedFactory.Configuration.Description);
return workspaceFolder;
}
private static string CreateTempEnvYml() {
var envFileContents = @"name: test
dependencies:
- cookies==2.2.1";
var envFilePath = Path.Combine(TestData.GetTempPath("EnvFiles"), "environment.yml");
File.WriteAllText(envFilePath, envFileContents);
return envFilePath;
}
private void CheckSwitcherEnvironment(PythonVisualStudioApp app, string expectedDescription) {
var expectedVisible = expectedDescription != null;
var switchMgr = app.PythonToolsService.EnvironmentSwitcherManager;
for (int i = 10; i >= 0; i--) {
var actualVisible = UIContext.FromUIContextGuid(GuidList.guidPythonToolbarUIContext).IsActive;
var actualDescription = switchMgr.CurrentFactory?.Configuration.Description;
if (actualVisible == expectedVisible && actualDescription == expectedDescription) {
return;
}
if (i == 0) {
Assert.AreEqual(expectedVisible, actualVisible);
Assert.AreEqual(expectedDescription, actualDescription);
} else {
Thread.Sleep(500);
}
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
using System.Xml.Serialization;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Spatial.Units;
namespace MathNet.Spatial
{
[System.Diagnostics.DebuggerStepThrough]
[Serializable]
public struct Point3D : IXmlSerializable, IEquatable<Point3D>, IFormattable
{
/// <summary>
/// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx
/// </summary>
public readonly double X;
/// <summary>
/// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx
/// </summary>
public readonly double Y;
/// <summary>
/// Using public fields cos: http://blogs.msdn.com/b/ricom/archive/2006/08/31/performance-quiz-11-ten-questions-on-value-based-programming.aspx
/// </summary>
public readonly double Z;
public Point3D(double x, double y, double z)
{
this.X = x;
this.Y = y;
this.Z = z;
}
public Point3D(IEnumerable<double> data)
: this(data.ToArray())
{
}
public Point3D(double[] data)
: this(data[0], data[1], data[2])
{
if (data.Length != 3)
{
throw new ArgumentException("Size must be 3");
}
}
/// <summary>
/// Creates a Point3D from its string representation
/// </summary>
/// <param name="s">The string representation of the Point3D</param>
/// <returns></returns>
public static Point3D Parse(string s)
{
var doubles = Parser.ParseItem3D(s);
return new Point3D(doubles);
}
public static bool operator ==(Point3D left, Point3D right)
{
return left.Equals(right);
}
public static bool operator !=(Point3D left, Point3D right)
{
return !left.Equals(right);
}
[Obsolete("Not sure this is nice")]
public static Vector<double> operator *(Matrix<double> left, Point3D right)
{
return left*right.ToVector();
}
[Obsolete("Not sure this is nice")]
public static Vector<double> operator *(Point3D left, Matrix<double> right)
{
return left.ToVector()*right;
}
public override string ToString()
{
return this.ToString(null, CultureInfo.InvariantCulture);
}
public string ToString(IFormatProvider provider)
{
return this.ToString(null, provider);
}
public string ToString(string format, IFormatProvider provider = null)
{
var numberFormatInfo = provider != null ? NumberFormatInfo.GetInstance(provider) : CultureInfo.InvariantCulture.NumberFormat;
string separator = numberFormatInfo.NumberDecimalSeparator == "," ? ";" : ",";
return string.Format("({0}{1} {2}{1} {3})", this.X.ToString(format, numberFormatInfo), separator, this.Y.ToString(format, numberFormatInfo), this.Z.ToString(format, numberFormatInfo));
}
public bool Equals(Point3D other)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
return this.X == other.X && this.Y == other.Y && this.Z == other.Z;
// ReSharper restore CompareOfFloatsByEqualityOperator
}
public bool Equals(Point3D other, double tolerance)
{
if (tolerance < 0)
{
throw new ArgumentException("epsilon < 0");
}
return Math.Abs(other.X - this.X) < tolerance &&
Math.Abs(other.Y - this.Y) < tolerance &&
Math.Abs(other.Z - this.Z) < tolerance;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
return obj is Point3D && this.Equals((Point3D)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = this.X.GetHashCode();
hashCode = (hashCode*397) ^ this.Y.GetHashCode();
hashCode = (hashCode*397) ^ this.Z.GetHashCode();
return hashCode;
}
}
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>
/// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
/// </returns>
public XmlSchema GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized. </param>
public void ReadXml(XmlReader reader)
{
reader.MoveToContent();
var e = (XElement)XNode.ReadFrom(reader);
// Hacking set readonly fields here, can't think of a cleaner workaround
double x = XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("X"));
double y = XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("Y"));
double z = XmlConvert.ToDouble(e.ReadAttributeOrElementOrDefault("Z"));
XmlExt.SetReadonlyFields(ref this, new[] { "X", "Y", "Z" }, new[] { x, y, z });
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized. </param>
public void WriteXml(XmlWriter writer)
{
writer.WriteAttribute("X", this.X);
writer.WriteAttribute("Y", this.Y);
writer.WriteAttribute("Z", this.Z);
}
public static Point3D ReadFrom(XmlReader reader)
{
var p = new Point3D();
p.ReadXml(reader);
return p;
}
public static Point3D Origin
{
get { return new Point3D(0, 0, 0); }
}
public static Point3D NaN
{
get { return new Point3D(double.NaN, double.NaN, double.NaN); }
}
public static Point3D Centroid(IEnumerable<Point3D> points)
{
return Centroid(points.ToArray());
}
public static Point3D Centroid(params Point3D[] points)
{
return new Point3D(
points.Average(point => point.X),
points.Average(point => point.Y),
points.Average(point => point.Z));
}
public static Point3D MidPoint(Point3D p1, Point3D p2)
{
return Centroid(p1, p2);
}
public static Point3D ItersectionOf(Plane plane1, Plane plane2, Plane plane3)
{
var ray = plane1.IntersectionWith(plane2);
return plane3.IntersectionWith(ray);
}
public static Point3D ItersectionOf(Plane plane, Ray3D ray)
{
return plane.IntersectionWith(ray);
}
public static Point3D operator +(Point3D p, Vector3D v)
{
return new Point3D(p.X + v.X, p.Y + v.Y, p.Z + v.Z);
}
public static Point3D operator +(Point3D p, UnitVector3D v)
{
return new Point3D(p.X + v.X, p.Y + v.Y, p.Z + v.Z);
}
public static Point3D operator -(Point3D p, Vector3D v)
{
return new Point3D(p.X - v.X, p.Y - v.Y, p.Z - v.Z);
}
public static Point3D operator -(Point3D p, UnitVector3D v)
{
return new Point3D(p.X - v.X, p.Y - v.Y, p.Z - v.Z);
}
public static Vector3D operator -(Point3D lhs, Point3D rhs)
{
return new Vector3D(lhs.X - rhs.X, lhs.Y - rhs.Y, lhs.Z - rhs.Z);
}
// Not sure a ref to System.Windows.Media.Media3D is nice
////public static explicit operator Point3D(System.Windows.Media.Media3D.Point3D p)
////{
//// return new Point3D(p.X, p.Y, p.Z);
////}
////public static explicit operator System.Windows.Media.Media3D.Point3D(Point3D p)
////{
//// return new System.Windows.Media.Media3D.Point3D(p.X, p.Y, p.Z);
////}
public Point3D MirrorAbout(Plane plane)
{
return plane.MirrorAbout(this);
}
public Point3D ProjectOn(Plane plane)
{
return plane.Project(this);
}
public Point3D Rotate(Vector3D aboutVector, Angle angle)
{
return Rotate(aboutVector.Normalize(), angle);
}
public Point3D Rotate(UnitVector3D aboutVector, Angle angle)
{
var cs = CoordinateSystem.Rotation(angle, aboutVector);
return cs.Transform(this);
}
[Pure]
public Vector3D VectorTo(Point3D p)
{
return p - this;
}
public double DistanceTo(Point3D p)
{
var vector = this.VectorTo(p);
return vector.Length;
}
public Vector3D ToVector3D()
{
return new Vector3D(this.X, this.Y, this.Z);
}
public Point3D TransformBy(CoordinateSystem cs)
{
return cs.Transform(this);
}
public Point3D TransformBy(Matrix<double> m)
{
return new Point3D(m.Multiply(this.ToVector()));
}
/// <summary>
/// Create a new Point3D from a Math.NET Numerics vector of length 3.
/// </summary>
public static Point3D OfVector(Vector<double> vector)
{
if (vector.Count != 3)
{
throw new ArgumentException("The vector length must be 3 in order to convert it to a Point3D");
}
return new Point3D(vector.At(0), vector.At(1), vector.At(2));
}
/// <summary>
/// Convert to a Math.NET Numerics dense vector of length 3.
/// </summary>
public Vector<double> ToVector()
{
return Vector<double>.Build.Dense(new[] { X, Y, Z });
}
}
}
| |
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Parse.Abstractions.Infrastructure.Control;
using Parse.Abstractions.Platform.Authentication;
using Parse.Abstractions.Platform.Objects;
using Parse.Infrastructure.Utilities;
namespace Parse
{
/// <summary>
/// Represents a user for a Parse application.
/// </summary>
[ParseClassName("_User")]
public class ParseUser : ParseObject
{
/// <summary>
/// Whether the ParseUser has been authenticated on this device. Only an authenticated
/// ParseUser can be saved and deleted.
/// </summary>
public bool IsAuthenticated
{
get
{
lock (Mutex)
{
return SessionToken is { } && Services.GetCurrentUser() is { } user && user.ObjectId == ObjectId;
}
}
}
/// <summary>
/// Removes a key from the object's data if it exists.
/// </summary>
/// <param name="key">The key to remove.</param>
/// <exception cref="ArgumentException">Cannot remove the username key.</exception>
public override void Remove(string key)
{
if (key == "username")
{
throw new InvalidOperationException("Cannot remove the username key.");
}
base.Remove(key);
}
protected override bool CheckKeyMutable(string key) => !ImmutableKeys.Contains(key);
internal override void HandleSave(IObjectState serverState)
{
base.HandleSave(serverState);
SynchronizeAllAuthData();
CleanupAuthData();
MutateState(mutableClone => mutableClone.ServerData.Remove("password"));
}
public string SessionToken => State.ContainsKey("sessionToken") ? State["sessionToken"] as string : null;
internal Task SetSessionTokenAsync(string newSessionToken) => SetSessionTokenAsync(newSessionToken, CancellationToken.None);
internal Task SetSessionTokenAsync(string newSessionToken, CancellationToken cancellationToken)
{
MutateState(mutableClone => mutableClone.ServerData["sessionToken"] = newSessionToken);
return Services.SaveCurrentUserAsync(this);
}
/// <summary>
/// Gets or sets the username.
/// </summary>
[ParseFieldName("username")]
public string Username
{
get => GetProperty<string>(null, nameof(Username));
set => SetProperty(value, nameof(Username));
}
/// <summary>
/// Sets the password.
/// </summary>
[ParseFieldName("password")]
public string Password
{
get => GetProperty<string>(null, nameof(Password));
set => SetProperty(value, nameof(Password));
}
/// <summary>
/// Sets the email address.
/// </summary>
[ParseFieldName("email")]
public string Email
{
get => GetProperty<string>(null, nameof(Email));
set => SetProperty(value, nameof(Email));
}
internal Task SignUpAsync(Task toAwait, CancellationToken cancellationToken)
{
if (AuthData == null)
{
// TODO (hallucinogen): make an Extension of Task to create Task with exception/canceled.
if (String.IsNullOrEmpty(Username))
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up user with an empty name."));
return tcs.Task;
}
if (String.IsNullOrEmpty(Password))
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up user with an empty password."));
return tcs.Task;
}
}
if (!String.IsNullOrEmpty(ObjectId))
{
TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();
tcs.TrySetException(new InvalidOperationException("Cannot sign up a user that already exists."));
return tcs.Task;
}
IDictionary<string, IParseFieldOperation> currentOperations = StartSave();
return toAwait.OnSuccess(_ => Services.UserController.SignUpAsync(State, currentOperations, Services, cancellationToken)).Unwrap().ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
HandleFailedSave(currentOperations);
}
else
{
HandleSave(t.Result);
}
return t;
}).Unwrap().OnSuccess(_ => Services.SaveCurrentUserAsync(this)).Unwrap();
}
/// <summary>
/// Signs up a new user. This will create a new ParseUser on the server and will also persist the
/// session on disk so that you can access the user using <see cref="CurrentUser"/>. A username and
/// password must be set before calling SignUpAsync.
/// </summary>
public Task SignUpAsync() => SignUpAsync(CancellationToken.None);
/// <summary>
/// Signs up a new user. This will create a new ParseUser on the server and will also persist the
/// session on disk so that you can access the user using <see cref="CurrentUser"/>. A username and
/// password must be set before calling SignUpAsync.
/// </summary>
/// <param name="cancellationToken">The cancellation token.</param>
public Task SignUpAsync(CancellationToken cancellationToken) => TaskQueue.Enqueue(toAwait => SignUpAsync(toAwait, cancellationToken), cancellationToken);
protected override Task SaveAsync(Task toAwait, CancellationToken cancellationToken)
{
lock (Mutex)
{
if (ObjectId is null)
{
throw new InvalidOperationException("You must call SignUpAsync before calling SaveAsync.");
}
return base.SaveAsync(toAwait, cancellationToken).OnSuccess(_ => Services.CurrentUserController.IsCurrent(this) ? Services.SaveCurrentUserAsync(this) : Task.CompletedTask).Unwrap();
}
}
// If this is already the current user, refresh its state on disk.
internal override Task<ParseObject> FetchAsyncInternal(Task toAwait, CancellationToken cancellationToken) => base.FetchAsyncInternal(toAwait, cancellationToken).OnSuccess(t => !Services.CurrentUserController.IsCurrent(this) ? Task.FromResult(t.Result) : Services.SaveCurrentUserAsync(this).OnSuccess(_ => t.Result)).Unwrap();
internal Task LogOutAsync(Task toAwait, CancellationToken cancellationToken)
{
string oldSessionToken = SessionToken;
if (oldSessionToken == null)
{
return Task.FromResult(0);
}
// Cleanup in-memory session.
MutateState(mutableClone => mutableClone.ServerData.Remove("sessionToken"));
Task revokeSessionTask = Services.RevokeSessionAsync(oldSessionToken, cancellationToken);
return Task.WhenAll(revokeSessionTask, Services.CurrentUserController.LogOutAsync(Services, cancellationToken));
}
internal Task UpgradeToRevocableSessionAsync() => UpgradeToRevocableSessionAsync(CancellationToken.None);
internal Task UpgradeToRevocableSessionAsync(CancellationToken cancellationToken) => TaskQueue.Enqueue(toAwait => UpgradeToRevocableSessionAsync(toAwait, cancellationToken), cancellationToken);
internal Task UpgradeToRevocableSessionAsync(Task toAwait, CancellationToken cancellationToken)
{
string sessionToken = SessionToken;
return toAwait.OnSuccess(_ => Services.UpgradeToRevocableSessionAsync(sessionToken, cancellationToken)).Unwrap().OnSuccess(task => SetSessionTokenAsync(task.Result)).Unwrap();
}
/// <summary>
/// Gets the authData for this user.
/// </summary>
public IDictionary<string, IDictionary<string, object>> AuthData
{
get => TryGetValue("authData", out IDictionary<string, IDictionary<string, object>> authData) ? authData : null;
set => this["authData"] = value;
}
/// <summary>
/// Removes null values from authData (which exist temporarily for unlinking)
/// </summary>
void CleanupAuthData()
{
lock (Mutex)
{
if (!Services.CurrentUserController.IsCurrent(this))
{
return;
}
IDictionary<string, IDictionary<string, object>> authData = AuthData;
if (authData == null)
{
return;
}
foreach (KeyValuePair<string, IDictionary<string, object>> pair in new Dictionary<string, IDictionary<string, object>>(authData))
{
if (pair.Value == null)
{
authData.Remove(pair.Key);
}
}
}
}
#warning Check if the following properties should be injected via IServiceHub.UserController (except for ImmutableKeys).
internal static IParseAuthenticationProvider GetProvider(string providerName) => Authenticators.TryGetValue(providerName, out IParseAuthenticationProvider provider) ? provider : null;
internal static IDictionary<string, IParseAuthenticationProvider> Authenticators { get; } = new Dictionary<string, IParseAuthenticationProvider> { };
internal static HashSet<string> ImmutableKeys { get; } = new HashSet<string> { "sessionToken", "isNew" };
/// <summary>
/// Synchronizes authData for all providers.
/// </summary>
internal void SynchronizeAllAuthData()
{
lock (Mutex)
{
IDictionary<string, IDictionary<string, object>> authData = AuthData;
if (authData == null)
{
return;
}
foreach (KeyValuePair<string, IDictionary<string, object>> pair in authData)
{
SynchronizeAuthData(GetProvider(pair.Key));
}
}
}
internal void SynchronizeAuthData(IParseAuthenticationProvider provider)
{
bool restorationSuccess = false;
lock (Mutex)
{
IDictionary<string, IDictionary<string, object>> authData = AuthData;
if (authData == null || provider == null)
{
return;
}
if (authData.TryGetValue(provider.AuthType, out IDictionary<string, object> data))
{
restorationSuccess = provider.RestoreAuthentication(data);
}
}
if (!restorationSuccess)
{
UnlinkFromAsync(provider.AuthType, CancellationToken.None);
}
}
internal Task LinkWithAsync(string authType, IDictionary<string, object> data, CancellationToken cancellationToken) => TaskQueue.Enqueue(toAwait =>
{
IDictionary<string, IDictionary<string, object>> authData = AuthData;
if (authData == null)
{
authData = AuthData = new Dictionary<string, IDictionary<string, object>>();
}
authData[authType] = data;
AuthData = authData;
return SaveAsync(cancellationToken);
}, cancellationToken);
internal Task LinkWithAsync(string authType, CancellationToken cancellationToken)
{
IParseAuthenticationProvider provider = GetProvider(authType);
return provider.AuthenticateAsync(cancellationToken).OnSuccess(t => LinkWithAsync(authType, t.Result, cancellationToken)).Unwrap();
}
/// <summary>
/// Unlinks a user from a service.
/// </summary>
internal Task UnlinkFromAsync(string authType, CancellationToken cancellationToken) => LinkWithAsync(authType, null, cancellationToken);
/// <summary>
/// Checks whether a user is linked to a service.
/// </summary>
internal bool IsLinked(string authType)
{
lock (Mutex)
{
return AuthData != null && AuthData.ContainsKey(authType) && AuthData[authType] != null;
}
}
}
}
| |
/*
* Copyright (c) 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.Runtime.InteropServices;
using System.Globalization;
namespace OpenMetaverse
{
/// <summary>
/// A three-dimensional vector with floating-point values
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct Vector3 : IComparable<Vector3>, IEquatable<Vector3>
{
/// <summary>X value</summary>
public float X;
/// <summary>Y value</summary>
public float Y;
/// <summary>Z value</summary>
public float Z;
#region Constructors
public Vector3(float x, float y, float z)
{
X = x;
Y = y;
Z = z;
}
public Vector3(float value)
{
X = value;
Y = value;
Z = value;
}
public Vector3(Vector2 value, float z)
{
X = value.X;
Y = value.Y;
Z = z;
}
public Vector3(Vector3d vector)
{
X = (float)vector.X;
Y = (float)vector.Y;
Z = (float)vector.Z;
}
/// <summary>
/// Constructor, builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing three four-byte floats</param>
/// <param name="pos">Beginning position in the byte array</param>
public Vector3(byte[] byteArray, int pos)
{
X = Y = Z = 0f;
FromBytes(byteArray, pos);
}
public Vector3(Vector3 vector)
{
X = vector.X;
Y = vector.Y;
Z = vector.Z;
}
#endregion Constructors
#region Public Methods
public float Length()
{
return (float)Math.Sqrt(DistanceSquared(this, Zero));
}
public float LengthSquared()
{
return DistanceSquared(this, Zero);
}
public void Normalize()
{
this = Normalize(this);
}
/// <summary>
/// Test if this vector is equal to another vector, within a given
/// tolerance range
/// </summary>
/// <param name="vec">Vector to test against</param>
/// <param name="tolerance">The acceptable magnitude of difference
/// between the two vectors</param>
/// <returns>True if the magnitude of difference between the two vectors
/// is less than the given tolerance, otherwise false</returns>
public bool ApproxEquals(Vector3 vec, float tolerance)
{
Vector3 diff = this - vec;
return (diff.LengthSquared() <= tolerance * tolerance);
}
/// <summary>
/// IComparable.CompareTo implementation
/// </summary>
public int CompareTo(Vector3 vector)
{
return Length().CompareTo(vector.Length());
}
/// <summary>
/// Test if this vector is composed of all finite numbers
/// </summary>
public bool IsFinite()
{
return (Utils.IsFinite(X) && Utils.IsFinite(Y) && Utils.IsFinite(Z));
}
/// <summary>
/// Builds a vector from a byte array
/// </summary>
/// <param name="byteArray">Byte array containing a 12 byte vector</param>
/// <param name="pos">Beginning position in the byte array</param>
public void FromBytes(byte[] byteArray, int pos)
{
if (!BitConverter.IsLittleEndian)
{
// Big endian architecture
byte[] conversionBuffer = new byte[12];
Buffer.BlockCopy(byteArray, pos, conversionBuffer, 0, 12);
Array.Reverse(conversionBuffer, 0, 4);
Array.Reverse(conversionBuffer, 4, 4);
Array.Reverse(conversionBuffer, 8, 4);
X = BitConverter.ToSingle(conversionBuffer, 0);
Y = BitConverter.ToSingle(conversionBuffer, 4);
Z = BitConverter.ToSingle(conversionBuffer, 8);
}
else
{
// Little endian architecture
X = BitConverter.ToSingle(byteArray, pos);
Y = BitConverter.ToSingle(byteArray, pos + 4);
Z = BitConverter.ToSingle(byteArray, pos + 8);
}
}
/// <summary>
/// Returns the raw bytes for this vector
/// </summary>
/// <returns>A 12 byte array containing X, Y, and Z</returns>
public byte[] GetBytes()
{
byte[] byteArray = new byte[12];
ToBytes(byteArray, 0);
return byteArray;
}
/// <summary>
/// Writes the raw bytes for this vector to a byte array
/// </summary>
/// <param name="dest">Destination byte array</param>
/// <param name="pos">Position in the destination array to start
/// writing. Must be at least 12 bytes before the end of the array</param>
public void ToBytes(byte[] dest, int pos)
{
Buffer.BlockCopy(BitConverter.GetBytes(X), 0, dest, pos + 0, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Y), 0, dest, pos + 4, 4);
Buffer.BlockCopy(BitConverter.GetBytes(Z), 0, dest, pos + 8, 4);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(dest, pos + 0, 4);
Array.Reverse(dest, pos + 4, 4);
Array.Reverse(dest, pos + 8, 4);
}
}
#endregion Public Methods
#region Static Methods
public static Vector3 Add(Vector3 value1, Vector3 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3 Clamp(Vector3 value1, Vector3 min, Vector3 max)
{
return new Vector3(
Utils.Clamp(value1.X, min.X, max.X),
Utils.Clamp(value1.Y, min.Y, max.Y),
Utils.Clamp(value1.Z, min.Z, max.Z));
}
public static Vector3 Cross(Vector3 value1, Vector3 value2)
{
return new Vector3(
value1.Y * value2.Z - value2.Y * value1.Z,
value1.Z * value2.X - value2.Z * value1.X,
value1.X * value2.Y - value2.X * value1.Y);
}
public static float Distance(Vector3 value1, Vector3 value2)
{
return (float)Math.Sqrt(DistanceSquared(value1, value2));
}
public static float DistanceSquared(Vector3 value1, Vector3 value2)
{
return
(value1.X - value2.X) * (value1.X - value2.X) +
(value1.Y - value2.Y) * (value1.Y - value2.Y) +
(value1.Z - value2.Z) * (value1.Z - value2.Z);
}
public static Vector3 Divide(Vector3 value1, Vector3 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3 Divide(Vector3 value1, float value2)
{
float factor = 1f / value2;
value1.X *= factor;
value1.Y *= factor;
value1.Z *= factor;
return value1;
}
public static float Dot(Vector3 value1, Vector3 value2)
{
return value1.X * value2.X + value1.Y * value2.Y + value1.Z * value2.Z;
}
public static Vector3 Lerp(Vector3 value1, Vector3 value2, float amount)
{
return new Vector3(
Utils.Lerp(value1.X, value2.X, amount),
Utils.Lerp(value1.Y, value2.Y, amount),
Utils.Lerp(value1.Z, value2.Z, amount));
}
public static float Mag(Vector3 value)
{
return (float)Math.Sqrt((value.X * value.X) + (value.Y * value.Y) + (value.Z * value.Z));
}
public static Vector3 Max(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Max(value1.X, value2.X),
Math.Max(value1.Y, value2.Y),
Math.Max(value1.Z, value2.Z));
}
public static Vector3 Min(Vector3 value1, Vector3 value2)
{
return new Vector3(
Math.Min(value1.X, value2.X),
Math.Min(value1.Y, value2.Y),
Math.Min(value1.Z, value2.Z));
}
public static Vector3 Multiply(Vector3 value1, Vector3 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3 Multiply(Vector3 value1, float scaleFactor)
{
value1.X *= scaleFactor;
value1.Y *= scaleFactor;
value1.Z *= scaleFactor;
return value1;
}
public static Vector3 Negate(Vector3 value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3 Normalize(Vector3 value)
{
const float MAG_THRESHOLD = 0.0000001f;
float factor = Distance(value, Zero);
if (factor > MAG_THRESHOLD)
{
factor = 1f / factor;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
}
else
{
value.X = 0f;
value.Y = 0f;
value.Z = 0f;
}
return value;
}
/// <summary>
/// Parse a vector from a string
/// </summary>
/// <param name="val">A string representation of a 3D vector, enclosed
/// in arrow brackets and separated by commas</param>
public static Vector3 Parse(string val)
{
char[] splitChar = { ',' };
string[] split = val.Replace("<", String.Empty).Replace(">", String.Empty).Split(splitChar);
return new Vector3(
Single.Parse(split[0].Trim(), Utils.EnUsCulture),
Single.Parse(split[1].Trim(), Utils.EnUsCulture),
Single.Parse(split[2].Trim(), Utils.EnUsCulture));
}
public static bool TryParse(string val, out Vector3 result)
{
try
{
result = Parse(val);
return true;
}
catch (Exception)
{
result = Vector3.Zero;
return false;
}
}
/// <summary>
/// Calculate the rotation between two vectors
/// </summary>
/// <param name="a">Normalized directional vector (such as 1,0,0 for forward facing)</param>
/// <param name="b">Normalized target vector</param>
public static Quaternion RotationBetween(Vector3 a, Vector3 b)
{
float dotProduct = Dot(a, b);
Vector3 crossProduct = Cross(a, b);
float magProduct = a.Length() * b.Length();
double angle = Math.Acos(dotProduct / magProduct);
Vector3 axis = Normalize(crossProduct);
float s = (float)Math.Sin(angle / 2d);
return new Quaternion(
axis.X * s,
axis.Y * s,
axis.Z * s,
(float)Math.Cos(angle / 2d));
}
/// <summary>
/// Interpolates between two vectors using a cubic equation
/// </summary>
public static Vector3 SmoothStep(Vector3 value1, Vector3 value2, float amount)
{
return new Vector3(
Utils.SmoothStep(value1.X, value2.X, amount),
Utils.SmoothStep(value1.Y, value2.Y, amount),
Utils.SmoothStep(value1.Z, value2.Z, amount));
}
public static Vector3 Subtract(Vector3 value1, Vector3 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector3 Transform(Vector3 position, Matrix4 matrix)
{
return new Vector3(
(position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31) + matrix.M41,
(position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32) + matrix.M42,
(position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33) + matrix.M43);
}
public static Vector3 TransformNormal(Vector3 position, Matrix4 matrix)
{
return new Vector3(
(position.X * matrix.M11) + (position.Y * matrix.M21) + (position.Z * matrix.M31),
(position.X * matrix.M12) + (position.Y * matrix.M22) + (position.Z * matrix.M32),
(position.X * matrix.M13) + (position.Y * matrix.M23) + (position.Z * matrix.M33));
}
#endregion Static Methods
#region Overrides
public override bool Equals(object obj)
{
return (obj is Vector3) ? this == (Vector3)obj : false;
}
public bool Equals(Vector3 other)
{
return this == other;
}
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode();
}
/// <summary>
/// Get a formatted string representation of the vector
/// </summary>
/// <returns>A string representation of the vector</returns>
public override string ToString()
{
return String.Format(Utils.EnUsCulture, "<{0}, {1}, {2}>", X, Y, Z);
}
/// <summary>
/// Get a string representation of the vector elements with up to three
/// decimal digits and separated by spaces only
/// </summary>
/// <returns>Raw string representation of the vector</returns>
public string ToRawString()
{
CultureInfo enUs = new CultureInfo("en-us");
enUs.NumberFormat.NumberDecimalDigits = 3;
return String.Format(enUs, "{0} {1} {2}", X, Y, Z);
}
#endregion Overrides
#region Operators
public static bool operator ==(Vector3 value1, Vector3 value2)
{
return value1.X == value2.X
&& value1.Y == value2.Y
&& value1.Z == value2.Z;
}
public static bool operator !=(Vector3 value1, Vector3 value2)
{
return !(value1 == value2);
}
public static Vector3 operator +(Vector3 value1, Vector3 value2)
{
value1.X += value2.X;
value1.Y += value2.Y;
value1.Z += value2.Z;
return value1;
}
public static Vector3 operator -(Vector3 value)
{
value.X = -value.X;
value.Y = -value.Y;
value.Z = -value.Z;
return value;
}
public static Vector3 operator -(Vector3 value1, Vector3 value2)
{
value1.X -= value2.X;
value1.Y -= value2.Y;
value1.Z -= value2.Z;
return value1;
}
public static Vector3 operator *(Vector3 value1, Vector3 value2)
{
value1.X *= value2.X;
value1.Y *= value2.Y;
value1.Z *= value2.Z;
return value1;
}
public static Vector3 operator *(Vector3 value, float scaleFactor)
{
value.X *= scaleFactor;
value.Y *= scaleFactor;
value.Z *= scaleFactor;
return value;
}
public static Vector3 operator *(Vector3 vec, Quaternion rot)
{
float rw = -rot.X * vec.X - rot.Y * vec.Y - rot.Z * vec.Z;
float rx = rot.W * vec.X + rot.Y * vec.Z - rot.Z * vec.Y;
float ry = rot.W * vec.Y + rot.Z * vec.X - rot.X * vec.Z;
float rz = rot.W * vec.Z + rot.X * vec.Y - rot.Y * vec.X;
vec.X = -rw * rot.X + rx * rot.W - ry * rot.Z + rz * rot.Y;
vec.Y = -rw * rot.Y + ry * rot.W - rz * rot.X + rx * rot.Z;
vec.Z = -rw * rot.Z + rz * rot.W - rx * rot.Y + ry * rot.X;
return vec;
}
public static Vector3 operator *(Vector3 vector, Matrix4 matrix)
{
return Transform(vector, matrix);
}
public static Vector3 operator /(Vector3 value1, Vector3 value2)
{
value1.X /= value2.X;
value1.Y /= value2.Y;
value1.Z /= value2.Z;
return value1;
}
public static Vector3 operator /(Vector3 value, float divider)
{
float factor = 1f / divider;
value.X *= factor;
value.Y *= factor;
value.Z *= factor;
return value;
}
/// <summary>
/// Cross product between two vectors
/// </summary>
public static Vector3 operator %(Vector3 value1, Vector3 value2)
{
return Cross(value1, value2);
}
/// <summary>
/// Explicit casting for Vector3d > Vector3
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static explicit operator Vector3(Vector3d value)
{
Vector3d foo = (Vector3d)Vector3.Zero;
return new Vector3(value);
}
#endregion Operators
/// <summary>A vector with a value of 0,0,0</summary>
public readonly static Vector3 Zero = new Vector3();
/// <summary>A vector with a value of 1,1,1</summary>
public readonly static Vector3 One = new Vector3(1f, 1f, 1f);
/// <summary>A unit vector facing forward (X axis), value 1,0,0</summary>
public readonly static Vector3 UnitX = new Vector3(1f, 0f, 0f);
/// <summary>A unit vector facing left (Y axis), value 0,1,0</summary>
public readonly static Vector3 UnitY = new Vector3(0f, 1f, 0f);
/// <summary>A unit vector facing up (Z axis), value 0,0,1</summary>
public readonly static Vector3 UnitZ = new Vector3(0f, 0f, 1f);
}
}
| |
using System;
using System.Threading.Tasks;
namespace Orleans.Streams
{
public static class AsyncObservableExtensions
{
private static readonly Func<Exception, Task> DefaultOnError = _ => Task.CompletedTask;
private static readonly Func<Task> DefaultOnCompleted = () => Task.CompletedTask;
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <param name="onErrorAsync">Delegate that is called for IAsyncObserver.OnErrorAsync.</param>
/// <param name="onCompletedAsync">Delegate that is called for IAsyncObserver.OnCompletedAsync.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.</returns>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync,
Func<Exception, Task> onErrorAsync,
Func<Task> onCompletedAsync)
{
var genericObserver = new GenericAsyncObserver<T>(onNextAsync, onErrorAsync, onCompletedAsync);
return obs.SubscribeAsync(genericObserver);
}
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <param name="onErrorAsync">Delegate that is called for IAsyncObserver.OnErrorAsync.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.</returns>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync,
Func<Exception, Task> onErrorAsync)
{
return obs.SubscribeAsync(onNextAsync, onErrorAsync, DefaultOnCompleted);
}
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <param name="onCompletedAsync">Delegate that is called for IAsyncObserver.OnCompletedAsync.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.</returns>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync,
Func<Task> onCompletedAsync)
{
return obs.SubscribeAsync(onNextAsync, DefaultOnError, onCompletedAsync);
}
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.</returns>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync)
{
return obs.SubscribeAsync(onNextAsync, DefaultOnError, DefaultOnCompleted);
}
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <param name="onErrorAsync">Delegate that is called for IAsyncObserver.OnErrorAsync.</param>
/// <param name="onCompletedAsync">Delegate that is called for IAsyncObserver.OnCompletedAsync.</param>
/// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param>
/// <param name="filterFunc">Filter to be applied for this subscription</param>
/// <param name="filterData">Data object that will be passed in to the filterFunc.
/// This will usually contain any parameters required by the filterFunc to make it's filtering decision.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.
/// </returns>
/// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable.
/// Usually this is because it is not a static method. </exception>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync,
Func<Exception, Task> onErrorAsync,
Func<Task> onCompletedAsync,
StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
var genericObserver = new GenericAsyncObserver<T>(onNextAsync, onErrorAsync, onCompletedAsync);
return obs.SubscribeAsync(genericObserver, token, filterFunc, filterData);
}
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <param name="onErrorAsync">Delegate that is called for IAsyncObserver.OnErrorAsync.</param>
/// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param>
/// <param name="filterFunc">Filter to be applied for this subscription</param>
/// <param name="filterData">Data object that will be passed in to the filterFunc.
/// This will usually contain any parameters required by the filterFunc to make it's filtering decision.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.
/// </returns>
/// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable.
/// Usually this is because it is not a static method. </exception>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync,
Func<Exception, Task> onErrorAsync,
StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
return obs.SubscribeAsync(onNextAsync, onErrorAsync, DefaultOnCompleted, token, filterFunc, filterData);
}
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <param name="onCompletedAsync">Delegate that is called for IAsyncObserver.OnCompletedAsync.</param>
/// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param>
/// <param name="filterFunc">Filter to be applied for this subscription</param>
/// <param name="filterData">Data object that will be passed in to the filterFunc.
/// This will usually contain any parameters required by the filterFunc to make it's filtering decision.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.
/// </returns>
/// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable.
/// Usually this is because it is not a static method. </exception>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync,
Func<Task> onCompletedAsync,
StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
return obs.SubscribeAsync(onNextAsync, DefaultOnError, onCompletedAsync, token, filterFunc, filterData);
}
/// <summary>
/// Subscribe a consumer to this observable using delegates.
/// This method is a helper for the IAsyncObservable.SubscribeAsync allowing the subscribing class to inline the
/// handler methods instead of requiring an instance of IAsyncObserver.
/// </summary>
/// <typeparam name="T">The type of object produced by the observable.</typeparam>
/// <param name="obs">The Observable object.</param>
/// <param name="onNextAsync">Delegate that is called for IAsyncObserver.OnNextAsync.</param>
/// <param name="token">The stream sequence to be used as an offset to start the subscription from.</param>
/// <param name="filterFunc">Filter to be applied for this subscription</param>
/// <param name="filterData">Data object that will be passed in to the filterFunc.
/// This will usually contain any parameters required by the filterFunc to make it's filtering decision.</param>
/// <returns>A promise for a StreamSubscriptionHandle that represents the subscription.
/// The consumer may unsubscribe by using this handle.
/// The subscription remains active for as long as it is not explicitly unsubscribed.
/// </returns>
/// <exception cref="ArgumentException">Thrown if the supplied stream filter function is not suitable.
/// Usually this is because it is not a static method. </exception>
public static Task<StreamSubscriptionHandle<T>> SubscribeAsync<T>(this IAsyncObservable<T> obs,
Func<T, StreamSequenceToken, Task> onNextAsync,
StreamSequenceToken token,
StreamFilterPredicate filterFunc = null,
object filterData = null)
{
return obs.SubscribeAsync(onNextAsync, DefaultOnError, DefaultOnCompleted, token, filterFunc, filterData);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using System.Dynamic;
using Microsoft.CSharp.RuntimeBinder;
using System.Globalization;
public class PrivateDynamicObjectSpec
{
[Fact]
public void WhenAsPrivateDynamicOfNullType_ThenReturnsNull()
{
var obj = default(Type);
dynamic target = obj.AsDynamicReflection();
Assert.Null(target);
}
[Fact]
public void WhenAccessingPrivateField_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
target.field = 5;
Assert.Equal(5, target.field);
}
[Fact]
public void WhenAccessingPrivateProperty_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
target.Property = "hello";
Assert.Equal("hello", target.Property);
}
[Fact]
public void WhenInvokingMethod_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var result = target.Echo("hello");
Assert.Equal("hello", result);
}
[Fact]
public void WhenInvokingMethod2_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var result = target.Echo("hello {0}", "world");
Assert.Equal("hello world", result);
}
[Fact]
public void WhenInvokingMethod_ThenResolvesOverload()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var result = target.Echo("hello", 2);
Assert.Equal("hellohello", result);
}
[Fact]
public void WhenInvokingMethodWithRef_ThenResolvesOverload()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var value = default(string);
var result = target.Echo("hello ", ref value);
Assert.True(result);
}
[Fact]
public void WhenInvokingMethodWithRef_ThenReturnsRefValue()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var value = default(string);
var r1 = RefValue.Create(() => value, s => value = s);
var result = target.Echo("hello ", r1);
Assert.True(result);
Assert.Equal("hello world", value);
}
[Fact]
public void WhenInvokingMethodWithOut_ThenReturnsOutValue()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var value1 = default(string);
var value2 = default(int);
var r1 = OutValue.Create<string>(s => value1 = s);
var r2 = OutValue.Create<int>(s => value2 = s);
var result = target.Echo("hello ", true, out r1, out r2);
Assert.True(result);
Assert.Equal("hello world", value1);
Assert.Equal(25, value2);
}
[Fact]
public void WhenInvokingMethodWithTwoOut_ThenReturnsOutValue()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var value = default(string);
var i = 0;
var out1 = OutValue.Create<string>(s => value = s);
var out2 = OutValue.Create<int>(x => i = x);
var result = target.Echo("hello ", true, out1, out2);
Assert.True(result);
Assert.Equal("hello world", value);
Assert.Equal(25, i);
}
[Fact]
public void WhenInvokingIndexerOverload1_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var result = target[9];
Assert.Equal("9", result);
}
[Fact]
public void WhenInvokingIndexerOverload2_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var result = target["9"];
Assert.Equal(9, result);
}
[Fact]
public void WhenSettingIndexedProperty_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
target[9] = "kzu";
}
[Fact]
public void WhenSettingNonExistingIndexedProperty_ThenThrows()
{
dynamic target = new PrivateObject().AsDynamicReflection();
Assert.Throws<RuntimeBinderException>(() => target[Guid.NewGuid()] = 23);
}
[Fact]
public void WhenInvokingIndexerTwoArgs_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var result = target["hello", 2];
Assert.Equal("llo", result);
}
[Fact]
public void WhenNullObject_ThenAsPrivateDinamicReturnsNull()
{
var target = default(object);
Assert.Null(target.AsDynamicReflection());
}
[Fact]
public void WhenInvokingExplicitlyImplementedMethod_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var clone = target.Clone();
Assert.Equal(target.Id, clone.Id);
}
[Fact]
public void WhenInvokingExplicitlyImplementedProperty_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
target.Name = "foo";
Assert.Equal("foo", target.Name);
}
[Fact]
public void WhenInvokingNonExistingMethod_ThenFails()
{
dynamic target = new PrivateObject().AsDynamicReflection();
Assert.Throws<RuntimeBinderException>(() => target.Do());
}
[Fact]
public void WhenGettingNonExistingProperty_ThenFails()
{
dynamic target = new PrivateObject().AsDynamicReflection();
Assert.Throws<RuntimeBinderException>(() => target.Blah);
}
[Fact]
public void WhenGettingNonExistingIndex_ThenFails()
{
dynamic target = new PrivateObject().AsDynamicReflection();
Assert.Throws<RuntimeBinderException>(() => target[true, 24]);
}
[Fact]
public void WhenSettingNonExistingProperty_ThenFails()
{
dynamic target = new PrivateObject().AsDynamicReflection();
Assert.Throws<RuntimeBinderException>(() => target.Blah = true);
}
[Fact]
public void WhenConverting_ThenConvertsTargetObject()
{
var inner = new PrivateObject();
dynamic target = inner.AsDynamicReflection();
PrivateObject obj = target;
Assert.Same(inner, obj);
}
[Fact]
public void WhenConvertingToImplementedInterface_ThenConvertsTargetObject()
{
var inner = new PrivateObject();
dynamic target = inner.AsDynamicReflection();
ICloneable obj = target;
Assert.Same(inner, obj);
}
[Fact]
public void WhenInvokingGenericMethod_ThenSucceeds()
{
dynamic target = new PrivateObject().AsDynamicReflection();
var value = target.Get<ICloneable>(23);
}
[Fact]
public void WhenInvokingConstructorSecondTime_ThenChangesId()
{
var inner = new PrivateObject();
var id = inner.Id;
dynamic target = inner.AsDynamicReflection();
target.ctor();
Assert.NotEqual(id, inner.Id);
}
[Fact]
public void WhenInvokingStaticMembers_ThenSucceeds()
{
var target = typeof(PrivateObject).AsDynamicReflection();
var value1 = target.StaticProp;
target.cctor();
var value2 = target.StaticProp;
Assert.NotEqual(value1, value2);
target.StaticField = "foo";
Assert.Equal("foo", PrivateObject.StaticField);
var value = target.StaticMethod("hello");
Assert.Equal("hello", value);
var refvalue = default(string);
value = target.StaticMethod("hello", ref refvalue);
Assert.Equal("hello", value);
}
[Fact]
public void WhenInvokingStaticMembersWithDerivedTypeArgument_ThenSucceeds()
{
var target = typeof(PrivateObject).AsDynamicReflection();
target.cctor();
List<int> d = new List<int>();
List<int> value = target.StaticMethod(d);
Assert.Equal(d, value);
}
[Fact]
public void WhenInvokingCtorForType_ThenSucceeds()
{
var target = typeof(PrivateObject).AsDynamicReflection();
var id = Guid.NewGuid();
var obj = target.ctor(id);
Assert.Equal(id, obj.Id);
}
[Fact]
public void WhenConvertingToIncompatible_ThenThrows()
{
var target = new PrivateObject().AsDynamicReflection();
int id = 0;
Assert.Throws<RuntimeBinderException>(() => id = target);
}
[Fact]
public void WhenConvertingToIConvertibleCompatibleBuiltInType_ThenSucceeds()
{
var target = new ConvertibleObject().AsDynamicReflection();
int id = target;
Assert.Equal(25, id);
}
[Fact]
public void WhenConvertingToIConvertibleCompatibleCustomType_ThenSucceeds()
{
var target = new ConvertibleObject().AsDynamicReflection();
PrivateObject converted = target;
Assert.NotNull(converted);
}
[Fact]
public void WhenConvertingToIConvertibleIncompatibleCustomType_ThenSucceeds()
{
var target = new ConvertibleObject().AsDynamicReflection();
ICloneable converted = null;
Assert.Throws<RuntimeBinderException>(() => converted = target);
}
[Fact]
public void WhenPassingTypeParameter_ThenResolves()
{
var foo = new PrivateObject().AsDynamicReflection();
var type = typeof(IFormattable);
var result = foo.Get(typeof(IFormattable).AsGenericTypeParameter(), 5);
Assert.Equal(typeof(IFormattable).Name, result);
}
[Fact]
public void WhenPassingTypeParameterAtEnd_ThenResolves()
{
var foo = new PrivateObject().AsDynamicReflection();
var type = typeof(IFormattable);
var result = foo.Get(5, typeof(IFormattable).AsGenericTypeParameter());
Assert.Equal("IFormattable", result);
}
[Fact]
public void WhenPassingMultipleTypeParameterCanMixGenericAndTypeParam_ThenResolves()
{
var foo = new PrivateObject().AsDynamicReflection();
var type = typeof(IFormattable);
var result = foo.Get<IFormattable>(5, typeof(bool).AsGenericTypeParameter());
Assert.Equal("IFormattable|Boolean", result);
}
[Fact]
public void WhenInvokingWithAssignableType_ThenSucceeds()
{
var foo = new PrivateObject().AsDynamicReflection();
var result = foo.Echo("foo", (byte)2);
Assert.Equal("foofoo", result);
result = foo.Echo("foo", (double)2);
Assert.Equal("foofoo", result);
result = foo.Echo("foo", (decimal)2);
Assert.Equal("foofoo", result);
}
private class PrivateObject : ICloneable, IPrivate
{
static PrivateObject()
{
StaticProp = Guid.NewGuid().ToString();
StaticField = null;
}
private PrivateObject(Guid id)
{
this.Id = id;
}
public PrivateObject()
{
this.Id = Guid.NewGuid();
}
public static string StaticProp { get; set; }
public static string StaticField;
public static string StaticMethod(string value)
{
return value;
}
public static IEnumerable<int> StaticMethod(IEnumerable<int> value)
{
return value;
}
public static string StaticMethod(string value, ref string refstring)
{
return value;
}
public Guid Id { get; set; }
#pragma warning disable 0169
private int field;
#pragma warning restore 0169
private string Property { get; set; }
private string Echo(string value)
{
return value;
}
private string Echo(string value, string format)
{
return string.Format(value, format);
}
private string Echo(string value, int count)
{
return Enumerable.Range(0, count)
.Aggregate("", (s, i) => s += value);
}
private string Echo(string value, IConvertible convertible)
{
return Enumerable.Range(0, convertible.ToInt32(CultureInfo.CurrentCulture))
.Aggregate("", (s, i) => s += value);
}
private bool Echo(string value, ref string result)
{
result = value + "world";
return true;
}
private bool Echo(string value, bool valid, out string result, out int count)
{
result = value + "world";
count = 25;
return true;
}
private string this[int index]
{
get { return index.ToString(); }
set { }
}
private int this[string index]
{
get { return int.Parse(index); }
}
private string this[string value, int index]
{
get { return value.Substring(index); }
}
private string Get<T>(int id)
{
return typeof(T).Name;
}
private string Get<T, R>(int id)
{
return typeof(T).Name + "|" + typeof(R).Name;
}
object ICloneable.Clone()
{
return this;
}
string IPrivate.Name { get; set; }
}
private class ConvertibleObject : IConvertible
{
public TypeCode GetTypeCode()
{
throw new NotImplementedException();
}
public bool ToBoolean(IFormatProvider provider)
{
throw new NotImplementedException();
}
public byte ToByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
public char ToChar(IFormatProvider provider)
{
throw new NotImplementedException();
}
public DateTime ToDateTime(IFormatProvider provider)
{
throw new NotImplementedException();
}
public decimal ToDecimal(IFormatProvider provider)
{
throw new NotImplementedException();
}
public double ToDouble(IFormatProvider provider)
{
throw new NotImplementedException();
}
public short ToInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
public int ToInt32(IFormatProvider provider)
{
return 25;
}
public long ToInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
public sbyte ToSByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
public float ToSingle(IFormatProvider provider)
{
throw new NotImplementedException();
}
public string ToString(IFormatProvider provider)
{
throw new NotImplementedException();
}
public object ToType(Type conversionType, IFormatProvider provider)
{
if (conversionType == typeof(PrivateObject))
return new PrivateObject();
throw new NotSupportedException();
}
public ushort ToUInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
public uint ToUInt32(IFormatProvider provider)
{
throw new NotImplementedException();
}
public ulong ToUInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
}
public interface IPrivate
{
string Name { get; set; }
}
}
| |
// 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 AndNotSByte()
{
var test = new SimpleBinaryOpTest__AndNotSByte();
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__AndNotSByte
{
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(SByte[] inArray1, SByte[] inArray2, SByte[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<SByte>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<SByte>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<SByte>();
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<SByte, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<SByte, 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<SByte> _fld1;
public Vector128<SByte> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref testStruct._fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AndNotSByte testClass)
{
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotSByte testClass)
{
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(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<SByte>>() / sizeof(SByte);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<SByte>>() / sizeof(SByte);
private static SByte[] _data1 = new SByte[Op1ElementCount];
private static SByte[] _data2 = new SByte[Op2ElementCount];
private static Vector128<SByte> _clsVar1;
private static Vector128<SByte> _clsVar2;
private Vector128<SByte> _fld1;
private Vector128<SByte> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AndNotSByte()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _clsVar2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
}
public SimpleBinaryOpTest__AndNotSByte()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld1), ref Unsafe.As<SByte, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<SByte>, byte>(ref _fld2), ref Unsafe.As<SByte, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<SByte>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSByte(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSByte(); }
_dataTable = new DataTable(_data1, _data2, new SByte[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.AndNot(
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_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.AndNot(
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_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.AndNot(
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_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.AndNot), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(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.AndNot), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(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.AndNot), new Type[] { typeof(Vector128<SByte>), typeof(Vector128<SByte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<SByte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<SByte>* pClsVar1 = &_clsVar1)
fixed (Vector128<SByte>* pClsVar2 = &_clsVar2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((SByte*)(pClsVar1)),
Sse2.LoadVector128((SByte*)(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<SByte>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<SByte>>(_dataTable.inArray2Ptr);
var result = Sse2.AndNot(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((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(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((SByte*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((SByte*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AndNotSByte();
var result = Sse2.AndNot(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__AndNotSByte();
fixed (Vector128<SByte>* pFld1 = &test._fld1)
fixed (Vector128<SByte>* pFld2 = &test._fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<SByte>* pFld1 = &_fld1)
fixed (Vector128<SByte>* pFld2 = &_fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((SByte*)(pFld1)),
Sse2.LoadVector128((SByte*)(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.AndNot(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.AndNot(
Sse2.LoadVector128((SByte*)(&test._fld1)),
Sse2.LoadVector128((SByte*)(&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<SByte> op1, Vector128<SByte> op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
SByte[] inArray1 = new SByte[Op1ElementCount];
SByte[] inArray2 = new SByte[Op2ElementCount];
SByte[] outArray = new SByte[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<SByte>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<SByte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<SByte>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(SByte[] left, SByte[] right, SByte[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((sbyte)(~left[0] & right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((sbyte)(~left[i] & right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<SByte>(Vector128<SByte>, Vector128<SByte>): {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;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.IO;
using System.Management.Automation.Tracing;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using Dbg = System.Diagnostics.Debug;
namespace System.Management.Automation.Remoting
{
[SerializableAttribute]
internal class HyperVSocketEndPoint : EndPoint
{
#region Members
private readonly System.Net.Sockets.AddressFamily _addressFamily;
private Guid _vmId;
private Guid _serviceId;
public const System.Net.Sockets.AddressFamily AF_HYPERV = (System.Net.Sockets.AddressFamily)34;
public const int HYPERV_SOCK_ADDR_SIZE = 36;
#endregion
#region Constructor
public HyperVSocketEndPoint(System.Net.Sockets.AddressFamily AddrFamily,
Guid VmId,
Guid ServiceId)
{
_addressFamily = AddrFamily;
_vmId = VmId;
_serviceId = ServiceId;
}
public override System.Net.Sockets.AddressFamily AddressFamily
{
get { return _addressFamily; }
}
public Guid VmId
{
get { return _vmId; }
set { _vmId = value; }
}
public Guid ServiceId
{
get { return _serviceId; }
set { _serviceId = value; }
}
#endregion
#region Overrides
public override EndPoint Create(SocketAddress SockAddr)
{
if (SockAddr == null ||
SockAddr.Family != AF_HYPERV ||
SockAddr.Size != 34)
{
return null;
}
HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(SockAddr.Family, Guid.Empty, Guid.Empty);
string sockAddress = SockAddr.ToString();
endpoint.VmId = new Guid(sockAddress.Substring(4, 16));
endpoint.ServiceId = new Guid(sockAddress.Substring(20, 16));
return endpoint;
}
public override bool Equals(object obj)
{
HyperVSocketEndPoint endpoint = (HyperVSocketEndPoint)obj;
if (endpoint == null)
{
return false;
}
if ((_addressFamily == endpoint.AddressFamily) &&
(_vmId == endpoint.VmId) &&
(_serviceId == endpoint.ServiceId))
{
return true;
}
return false;
}
public override int GetHashCode()
{
return Serialize().GetHashCode();
}
public override SocketAddress Serialize()
{
SocketAddress sockAddress = new SocketAddress((System.Net.Sockets.AddressFamily)_addressFamily, HYPERV_SOCK_ADDR_SIZE);
byte[] vmId = _vmId.ToByteArray();
byte[] serviceId = _serviceId.ToByteArray();
sockAddress[2] = (byte)0;
for (int i = 0; i < vmId.Length; i++)
{
sockAddress[i + 4] = vmId[i];
}
for (int i = 0; i < serviceId.Length; i++)
{
sockAddress[i + 4 + vmId.Length] = serviceId[i];
}
return sockAddress;
}
public override string ToString()
{
return _vmId.ToString() + _serviceId.ToString();
}
#endregion
}
internal sealed class RemoteSessionHyperVSocketServer : IDisposable
{
#region Members
private readonly object _syncObject;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
#endregion
#region Properties
/// <summary>
/// Returns the Hyper-V socket object.
/// </summary>
public Socket HyperVSocket { get; }
/// <summary>
/// Returns the network stream object.
/// </summary>
public NetworkStream Stream { get; }
/// <summary>
/// Accessor for the Hyper-V socket reader.
/// </summary>
public StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the Hyper-V socket writer.
/// </summary>
public StreamWriter TextWriter { get; private set; }
/// <summary>
/// Returns true if object is currently disposed.
/// </summary>
public bool IsDisposed { get; private set; }
#endregion
#region Constructors
public RemoteSessionHyperVSocketServer(bool LoopbackMode)
{
// TODO: uncomment below code when .NET supports Hyper-V socket duplication
/*
NamedPipeClientStream clientPipeStream;
byte[] buffer = new byte[1000];
int bytesRead;
*/
_syncObject = new object();
Exception ex = null;
try
{
// TODO: uncomment below code when .NET supports Hyper-V socket duplication
/*
if (!LoopbackMode)
{
//
// Create named pipe client.
//
using (clientPipeStream = new NamedPipeClientStream(".",
"PS_VMSession",
PipeDirection.InOut,
PipeOptions.None,
TokenImpersonationLevel.None))
{
//
// Connect to named pipe server.
//
clientPipeStream.Connect(10*1000);
//
// Read LPWSAPROTOCOL_INFO.
//
bytesRead = clientPipeStream.Read(buffer, 0, 1000);
}
}
//
// Create duplicate socket.
//
byte[] protocolInfo = new byte[bytesRead];
Array.Copy(buffer, protocolInfo, bytesRead);
SocketInformation sockInfo = new SocketInformation();
sockInfo.ProtocolInformation = protocolInfo;
sockInfo.Options = SocketInformationOptions.Connected;
socket = new Socket(sockInfo);
if (socket == null)
{
Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer.");
tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty,
"Unexpected error in constructor: {0}", "socket duplication failure");
}
*/
// TODO: remove below 6 lines of code when .NET supports Hyper-V socket duplication
Guid serviceId = new Guid("a5201c21-2770-4c11-a68e-f182edb29220"); // HV_GUID_VM_SESSION_SERVICE_ID_2
HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, Guid.Empty, serviceId);
Socket listenSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType)1);
listenSocket.Bind(endpoint);
listenSocket.Listen(1);
HyperVSocket = listenSocket.Accept();
Stream = new NetworkStream(HyperVSocket, true);
// Create reader/writer streams.
TextReader = new StreamReader(Stream);
TextWriter = new StreamWriter(Stream);
TextWriter.AutoFlush = true;
//
// listenSocket is not closed when it goes out of scope here. Sometimes it is
// closed later in this thread, while other times it is not closed at all. This will
// cause problem when we set up a second PowerShell Direct session. Let's
// explicitly close listenSocket here for safe.
//
if (listenSocket != null)
{
try { listenSocket.Dispose(); }
catch (ObjectDisposedException) { }
}
}
catch (Exception e)
{
ex = e;
}
if (ex != null)
{
Dbg.Fail("Unexpected error in RemoteSessionHyperVSocketServer.");
// Unexpected error.
string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty;
_tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty,
"Unexpected error in constructor: {0}", errorMessage);
throw new PSInvalidOperationException(
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketServerConstructorFailure),
ex,
nameof(PSRemotingErrorId.RemoteSessionHyperVSocketServerConstructorFailure),
ErrorCategory.InvalidOperation,
null);
}
}
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
lock (_syncObject)
{
if (IsDisposed) { return; }
IsDisposed = true;
}
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (Stream != null)
{
try { Stream.Dispose(); }
catch (ObjectDisposedException) { }
}
if (HyperVSocket != null)
{
try { HyperVSocket.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
}
internal sealed class RemoteSessionHyperVSocketClient : IDisposable
{
#region Members
private readonly object _syncObject;
private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource();
private static readonly ManualResetEvent s_connectDone =
new ManualResetEvent(false);
#endregion
#region constants in hvsocket.h
public const int HV_PROTOCOL_RAW = 1;
public const int HVSOCKET_CONTAINER_PASSTHRU = 2;
#endregion
#region Properties
/// <summary>
/// Returns the Hyper-V socket endpoint object.
/// </summary>
public HyperVSocketEndPoint EndPoint { get; }
/// <summary>
/// Returns the Hyper-V socket object.
/// </summary>
public Socket HyperVSocket { get; }
/// <summary>
/// Returns the network stream object.
/// </summary>
public NetworkStream Stream { get; private set; }
/// <summary>
/// Accessor for the Hyper-V socket reader.
/// </summary>
public StreamReader TextReader { get; private set; }
/// <summary>
/// Accessor for the Hyper-V socket writer.
/// </summary>
public StreamWriter TextWriter { get; private set; }
/// <summary>
/// Returns true if object is currently disposed.
/// </summary>
public bool IsDisposed { get; private set; }
#endregion
#region Constructors
internal RemoteSessionHyperVSocketClient(
Guid vmId,
bool isFirstConnection,
bool isContainer = false)
{
Guid serviceId;
_syncObject = new object();
if (isFirstConnection)
{
// HV_GUID_VM_SESSION_SERVICE_ID
serviceId = new Guid("999e53d4-3d5c-4c3e-8779-bed06ec056e1");
}
else
{
// HV_GUID_VM_SESSION_SERVICE_ID_2
serviceId = new Guid("a5201c21-2770-4c11-a68e-f182edb29220");
}
EndPoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, vmId, serviceId);
HyperVSocket = new Socket(EndPoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType)1);
//
// We need to call SetSocketOption() in order to set up Hyper-V socket connection between container host and Hyper-V container.
// Here is the scenario: the Hyper-V container is inside a utility vm, which is inside the container host
//
if (isContainer)
{
var value = new byte[sizeof(uint)];
value[0] = 1;
try
{
HyperVSocket.SetSocketOption((System.Net.Sockets.SocketOptionLevel)HV_PROTOCOL_RAW,
(System.Net.Sockets.SocketOptionName)HVSOCKET_CONTAINER_PASSTHRU,
(byte[])value);
}
catch
{
throw new PSDirectException(
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure));
}
}
}
#endregion
#region IDisposable
/// <summary>
/// Dispose.
/// </summary>
public void Dispose()
{
lock (_syncObject)
{
if (IsDisposed) { return; }
IsDisposed = true;
}
if (TextReader != null)
{
try { TextReader.Dispose(); }
catch (ObjectDisposedException) { }
TextReader = null;
}
if (TextWriter != null)
{
try { TextWriter.Dispose(); }
catch (ObjectDisposedException) { }
TextWriter = null;
}
if (Stream != null)
{
try { Stream.Dispose(); }
catch (ObjectDisposedException) { }
}
if (HyperVSocket != null)
{
try { HyperVSocket.Dispose(); }
catch (ObjectDisposedException) { }
}
}
#endregion
#region Public Methods
/// <summary>
/// Connect to Hyper-V socket server. This is a blocking call until a
/// connection occurs or the timeout time has elapsed.
/// </summary>
/// <param name="networkCredential">The credential used for authentication.</param>
/// <param name="configurationName">The configuration name of the PS session.</param>
/// <param name="isFirstConnection">Whether this is the first connection.</param>
public bool Connect(
NetworkCredential networkCredential,
string configurationName,
bool isFirstConnection)
{
bool result = false;
//
// Check invalid input and throw exception before setting up socket connection.
// This check is done only in VM case.
//
if (isFirstConnection)
{
if (string.IsNullOrEmpty(networkCredential.UserName))
{
throw new PSDirectException(
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidUsername));
}
}
HyperVSocket.Connect(EndPoint);
if (HyperVSocket.Connected)
{
_tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty,
"Client connected.");
Stream = new NetworkStream(HyperVSocket, true);
if (isFirstConnection)
{
if (string.IsNullOrEmpty(networkCredential.Domain))
{
networkCredential.Domain = "localhost";
}
bool emptyPassword = string.IsNullOrEmpty(networkCredential.Password);
bool emptyConfiguration = string.IsNullOrEmpty(configurationName);
byte[] domain = Encoding.Unicode.GetBytes(networkCredential.Domain);
byte[] userName = Encoding.Unicode.GetBytes(networkCredential.UserName);
byte[] password = Encoding.Unicode.GetBytes(networkCredential.Password);
byte[] response = new byte[4]; // either "PASS" or "FAIL"
string responseString;
//
// Send credential to VM so that PowerShell process inside VM can be
// created under the correct security context.
//
HyperVSocket.Send(domain);
HyperVSocket.Receive(response);
HyperVSocket.Send(userName);
HyperVSocket.Receive(response);
//
// We cannot simply send password because if it is empty,
// the vmicvmsession service in VM will block in recv method.
//
if (emptyPassword)
{
HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYPW"));
HyperVSocket.Receive(response);
responseString = Encoding.ASCII.GetString(response);
}
else
{
HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYPW"));
HyperVSocket.Receive(response);
HyperVSocket.Send(password);
HyperVSocket.Receive(response);
responseString = Encoding.ASCII.GetString(response);
}
//
// There are 3 cases for the responseString received above.
// - "FAIL": credential is invalid
// - "PASS": credential is valid, but PowerShell Direct in VM does not support configuration (Server 2016 TP4 and before)
// - "CONF": credential is valid, and PowerShell Direct in VM supports configuration (Server 2016 TP5 and later)
//
//
// Credential is invalid.
//
if (string.Equals(responseString, "FAIL", StringComparison.Ordinal))
{
HyperVSocket.Send(response);
throw new PSDirectException(
PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential));
}
//
// If PowerShell Direct in VM supports configuration, send configuration name.
//
if (string.Equals(responseString, "CONF", StringComparison.Ordinal))
{
if (emptyConfiguration)
{
HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYCF"));
}
else
{
HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYCF"));
HyperVSocket.Receive(response);
byte[] configName = Encoding.Unicode.GetBytes(configurationName);
HyperVSocket.Send(configName);
}
}
else
{
HyperVSocket.Send(response);
}
}
TextReader = new StreamReader(Stream);
TextWriter = new StreamWriter(Stream);
TextWriter.AutoFlush = true;
result = true;
}
else
{
_tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty,
"Client unable to connect.");
result = false;
}
return result;
}
public void Close()
{
Stream.Dispose();
HyperVSocket.Dispose();
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Hyak.Common;
using Microsoft.Azure.Management.OperationalInsights.Models;
namespace Microsoft.Azure.Management.OperationalInsights.Models
{
/// <summary>
/// Metadata for search results.
/// </summary>
public partial class SearchMetadata
{
private string _aggregatedGroupingFields;
/// <summary>
/// Optional. Gets or sets the aggregated grouping fields.
/// </summary>
public string AggregatedGroupingFields
{
get { return this._aggregatedGroupingFields; }
set { this._aggregatedGroupingFields = value; }
}
private string _aggregatedValueField;
/// <summary>
/// Optional. Gets or sets the aggregated value field.
/// </summary>
public string AggregatedValueField
{
get { return this._aggregatedValueField; }
set { this._aggregatedValueField = value; }
}
private IList<CoreSummary> _coreSummaries;
/// <summary>
/// Optional. Gets or sets the core summaries.
/// </summary>
public IList<CoreSummary> CoreSummaries
{
get { return this._coreSummaries; }
set { this._coreSummaries = value; }
}
private string _eTag;
/// <summary>
/// Optional. Gets or sets the ETag of the search results.
/// </summary>
public string ETag
{
get { return this._eTag; }
set { this._eTag = value; }
}
private System.Guid? _id;
/// <summary>
/// Optional. Gets or sets the id of the search results request.
/// </summary>
public System.Guid? Id
{
get { return this._id; }
set { this._id = value; }
}
private System.DateTime? _lastUpdated;
/// <summary>
/// Optional. Gets or sets the time of last update.
/// </summary>
public System.DateTime? LastUpdated
{
get { return this._lastUpdated; }
set { this._lastUpdated = value; }
}
private int? _max;
/// <summary>
/// Optional. Gets or sets the max.
/// </summary>
public int? Max
{
get { return this._max; }
set { this._max = value; }
}
private int? _requestTime;
/// <summary>
/// Optional. Gets or sets the request time.
/// </summary>
public int? RequestTime
{
get { return this._requestTime; }
set { this._requestTime = value; }
}
private string _resultType;
/// <summary>
/// Optional. Gets or sets the search result type.
/// </summary>
public string ResultType
{
get { return this._resultType; }
set { this._resultType = value; }
}
private MetadataSchema _schema;
/// <summary>
/// Optional. Gets or sets the schema.
/// </summary>
public MetadataSchema Schema
{
get { return this._schema; }
set { this._schema = value; }
}
private string _searchId;
/// <summary>
/// Optional. Gets or sets the request id of the search.
/// </summary>
public string SearchId
{
get { return this._searchId; }
set { this._searchId = value; }
}
private IList<SearchSort> _sort;
/// <summary>
/// Optional. Gets or sets sort.
/// </summary>
public IList<SearchSort> Sort
{
get { return this._sort; }
set { this._sort = value; }
}
private System.DateTime? _startTime;
/// <summary>
/// Optional. Gets or sets the start time for the search.
/// </summary>
public System.DateTime? StartTime
{
get { return this._startTime; }
set { this._startTime = value; }
}
private string _status;
/// <summary>
/// Optional. Gets or sets the status of the search results.
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
private int? _sum;
/// <summary>
/// Optional. Gets or sets the sum.
/// </summary>
public int? Sum
{
get { return this._sum; }
set { this._sum = value; }
}
private int? _top;
/// <summary>
/// Optional. Gets or sets the number of top search results.
/// </summary>
public int? Top
{
get { return this._top; }
set { this._top = value; }
}
private int? _total;
/// <summary>
/// Optional. Gets or sets the total search results.
/// </summary>
public int? Total
{
get { return this._total; }
set { this._total = value; }
}
/// <summary>
/// Initializes a new instance of the SearchMetadata class.
/// </summary>
public SearchMetadata()
{
this.CoreSummaries = new LazyList<CoreSummary>();
this.Sort = new LazyList<SearchSort>();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Reflection;
using Microsoft.AspNetCore.Mvc.ApplicationModels;
using Microsoft.Extensions.DependencyInjection;
using Moq;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure
{
public class CompiledPageActionDescriptorFactoryTest
{
[Fact]
public void ApplyConventions_InvokesApplicationModelConventions()
{
// Arrange
var descriptor = new PageActionDescriptor();
var model = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var convention = new Mock<IPageApplicationModelConvention>();
convention.Setup(c => c.Apply(It.IsAny<PageApplicationModel>()))
.Callback((PageApplicationModel m) =>
{
Assert.Same(model, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>())
{
convention.Object,
};
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, model);
// Assert
convention.Verify();
}
[Fact]
public void ApplyConventions_InvokesApplicationModelConventions_SpecifiedOnHandlerType()
{
// Arrange
var descriptor = new PageActionDescriptor();
var handlerConvention = new Mock<IPageApplicationModelConvention>();
var model = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), new[] { handlerConvention.Object });
var globalConvention = new Mock<IPageApplicationModelConvention>();
globalConvention.Setup(c => c.Apply(It.IsAny<PageApplicationModel>()))
.Callback((PageApplicationModel m) =>
{
Assert.Same(model, m);
})
.Verifiable();
handlerConvention.Setup(c => c.Apply(It.IsAny<PageApplicationModel>()))
.Callback((PageApplicationModel m) =>
{
Assert.Same(model, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>())
{
globalConvention.Object,
};
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, model);
// Assert
globalConvention.Verify();
handlerConvention.Verify();
}
[Fact]
public void ApplyConventions_InvokesHandlerModelConventions()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var handlerModelConvention = new Mock<IPageHandlerModelConvention>();
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, new[] { handlerModelConvention.Object });
applicationModel.HandlerMethods.Add(handlerModel);
handlerModelConvention.Setup(p => p.Apply(It.IsAny<PageHandlerModel>()))
.Callback((PageHandlerModel m) =>
{
Assert.Same(handlerModel, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>());
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
handlerModelConvention.Verify();
}
[Fact]
public void ApplyConventions_InvokesHandlerModelConventions_DefinedGlobally()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, Array.Empty<object>());
applicationModel.HandlerMethods.Add(handlerModel);
var handlerModelConvention = new Mock<IPageHandlerModelConvention>();
handlerModelConvention.Setup(p => p.Apply(It.IsAny<PageHandlerModel>()))
.Callback((PageHandlerModel m) =>
{
Assert.Same(handlerModel, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>()) { handlerModelConvention.Object };
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
handlerModelConvention.Verify();
}
[Fact]
public void ApplyConventions_RemovingHandlerAsPartOfHandlerModelConvention_Works()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var handlerModelConvention = new Mock<IPageHandlerModelConvention>();
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, new[] { handlerModelConvention.Object })
{
Page = applicationModel,
};
applicationModel.HandlerMethods.Add(handlerModel);
handlerModelConvention.Setup(p => p.Apply(It.IsAny<PageHandlerModel>()))
.Callback((PageHandlerModel m) =>
{
m.Page.HandlerMethods.Remove(m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>());
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
handlerModelConvention.Verify();
}
[Fact]
public void ApplyConventions_InvokesParameterModelConventions()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var parameterInfo = methodInfo.GetParameters()[0];
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, Array.Empty<object>());
var parameterModelConvention = new Mock<IParameterModelBaseConvention>();
var parameterModel = new PageParameterModel(parameterInfo, new[] { parameterModelConvention.Object });
applicationModel.HandlerMethods.Add(handlerModel);
handlerModel.Parameters.Add(parameterModel);
parameterModelConvention.Setup(p => p.Apply(It.IsAny<ParameterModelBase>()))
.Callback((ParameterModelBase m) =>
{
Assert.Same(parameterModel, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>());
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
parameterModelConvention.Verify();
}
[Fact]
public void ApplyConventions_InvokesParameterModelConventions_DeclaredGlobally()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var parameterInfo = methodInfo.GetParameters()[0];
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, Array.Empty<object>());
var parameterModel = new PageParameterModel(parameterInfo, Array.Empty<object>());
applicationModel.HandlerMethods.Add(handlerModel);
handlerModel.Parameters.Add(parameterModel);
var parameterModelConvention = new Mock<IParameterModelBaseConvention>();
parameterModelConvention.Setup(p => p.Apply(It.IsAny<ParameterModelBase>()))
.Callback((ParameterModelBase m) =>
{
Assert.Same(parameterModel, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>()) { parameterModelConvention.Object };
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
parameterModelConvention.Verify();
}
[Fact]
public void ApplyConventions_RemovingParameterModelAsPartOfConventionWorks()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var parameterInfo = methodInfo.GetParameters()[0];
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, Array.Empty<object>());
var parameterModelConvention = new Mock<IParameterModelBaseConvention>();
var parameterModel = new PageParameterModel(parameterInfo, new[] { parameterModelConvention.Object })
{
Handler = handlerModel,
};
applicationModel.HandlerMethods.Add(handlerModel);
handlerModel.Parameters.Add(parameterModel);
parameterModelConvention.Setup(p => p.Apply(It.IsAny<ParameterModelBase>()))
.Callback((ParameterModelBase m) =>
{
var model = Assert.IsType<PageParameterModel>(m);
model.Handler.Parameters.Remove(model);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>());
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
parameterModelConvention.Verify();
}
[Fact]
public void ApplyConventions_InvokesPropertyModelConventions()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var propertyInfo = GetType().GetProperty(nameof(TestProperty), BindingFlags.Instance | BindingFlags.NonPublic);
var parameterInfo = methodInfo.GetParameters()[0];
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, Array.Empty<object>());
var parameterModel = new PageParameterModel(parameterInfo, Array.Empty<object>());
var propertyModelConvention = new Mock<IParameterModelBaseConvention>();
var propertyModel = new PagePropertyModel(propertyInfo, new[] { propertyModelConvention.Object });
applicationModel.HandlerMethods.Add(handlerModel);
applicationModel.HandlerProperties.Add(propertyModel);
handlerModel.Parameters.Add(parameterModel);
propertyModelConvention.Setup(p => p.Apply(It.IsAny<ParameterModelBase>()))
.Callback((ParameterModelBase m) =>
{
Assert.Same(propertyModel, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>());
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
propertyModelConvention.Verify();
}
[Fact]
public void ApplyConventions_InvokesPropertyModelConventions_DeclaredGlobally()
{
// Arrange
var descriptor = new PageActionDescriptor();
var methodInfo = GetType().GetMethod(nameof(OnGet), BindingFlags.Instance | BindingFlags.NonPublic);
var propertyInfo = GetType().GetProperty(nameof(TestProperty), BindingFlags.Instance | BindingFlags.NonPublic);
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var handlerModel = new PageHandlerModel(methodInfo, Array.Empty<object>());
var propertyModel = new PagePropertyModel(propertyInfo, Array.Empty<object>());
applicationModel.HandlerMethods.Add(handlerModel);
applicationModel.HandlerProperties.Add(propertyModel);
var propertyModelConvention = new Mock<IParameterModelBaseConvention>();
propertyModelConvention.Setup(p => p.Apply(It.IsAny<ParameterModelBase>()))
.Callback((ParameterModelBase m) =>
{
Assert.Same(propertyModel, m);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>()) { propertyModelConvention.Object };
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
propertyModelConvention.Verify();
}
[Fact]
public void ApplyConventions_RemovingPropertyModelAsPartOfConvention_Works()
{
// Arrange
var descriptor = new PageActionDescriptor();
var propertyInfo = GetType().GetProperty(nameof(TestProperty), BindingFlags.Instance | BindingFlags.NonPublic);
var applicationModel = new PageApplicationModel(descriptor, typeof(object).GetTypeInfo(), Array.Empty<object>());
var propertyModelConvention = new Mock<IParameterModelBaseConvention>();
var propertyModel = new PagePropertyModel(propertyInfo, new[] { propertyModelConvention.Object })
{
Page = applicationModel,
};
applicationModel.HandlerProperties.Add(propertyModel);
propertyModelConvention.Setup(p => p.Apply(It.IsAny<ParameterModelBase>()))
.Callback((ParameterModelBase m) =>
{
var model = Assert.IsType<PagePropertyModel>(m);
model.Page.HandlerProperties.Remove(model);
})
.Verifiable();
var conventionCollection = new PageConventionCollection(Mock.Of<IServiceProvider>());
// Act
CompiledPageActionDescriptorFactory.ApplyConventions(conventionCollection, applicationModel);
// Assert
propertyModelConvention.Verify();
}
private void OnGet(string parameter)
{
}
private string TestProperty { get; set; }
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// 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.Runtime.InteropServices;
namespace SharpDX.Win32
{
/// <summary>
/// Implementation of OLE IPropertyBag2.
/// </summary>
/// <unmanaged>IPropertyBag2</unmanaged>
public class PropertyBag : ComObject
{
private IPropertyBag2 nativePropertyBag;
/// <summary>
/// Initializes a new instance of the <see cref="PropertyBag"/> class.
/// </summary>
/// <param name="propertyBagPointer">The property bag pointer.</param>
public PropertyBag(IntPtr propertyBagPointer) : base(propertyBagPointer)
{
}
protected override void NativePointerUpdated(IntPtr oldNativePointer)
{
base.NativePointerUpdated(oldNativePointer);
if (NativePointer != IntPtr.Zero)
nativePropertyBag = (IPropertyBag2)Marshal.GetObjectForIUnknown(NativePointer);
else
nativePropertyBag = null;
}
private void CheckIfInitialized()
{
if (nativePropertyBag == null)
throw new InvalidOperationException("This instance is not bound to an unmanaged IPropertyBag2");
}
/// <summary>
/// Gets the number of properties.
/// </summary>
public int Count
{
get
{
CheckIfInitialized();
int propertyCount;
nativePropertyBag.CountProperties(out propertyCount);
return propertyCount;
}
}
/// <summary>
/// Gets the keys.
/// </summary>
public string[] Keys
{
get
{
CheckIfInitialized();
var keys = new List<string>();
for (int i = 0; i < Count; i++)
{
PROPBAG2 propbag2;
int temp;
nativePropertyBag.GetPropertyInfo(i, 1, out propbag2, out temp);
keys.Add(propbag2.Name);
}
return keys.ToArray();
}
}
/// <summary>
/// Gets the value of the property with this name.
/// </summary>
/// <param name="name">The name.</param>
/// <returns>Value of the property</returns>
public object Get(string name)
{
CheckIfInitialized();
object value;
var propbag2 = new PROPBAG2() {Name = name};
Result error;
// Gets the property
var result = nativePropertyBag.Read(1, ref propbag2, IntPtr.Zero, out value, out error);
if (result.Failure || error.Failure)
throw new InvalidOperationException(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Property with name [{0}] is not valid for this instance", name));
propbag2.Dispose();
return value;
}
/// <summary>
/// Gets the value of the property by using a <see cref="PropertyBagKey{T1,T2}"/>
/// </summary>
/// <typeparam name="T1">The public type of this property.</typeparam>
/// <typeparam name="T2">The marshaling type of this property.</typeparam>
/// <param name="propertyKey">The property key.</param>
/// <returns>Value of the property</returns>
public T1 Get<T1, T2>(PropertyBagKey<T1, T2> propertyKey)
{
var value = Get(propertyKey.Name);
return (T1) Convert.ChangeType(value, typeof (T1));
}
/// <summary>
/// Sets the value of the property with this name
/// </summary>
/// <param name="name">The name.</param>
/// <param name="value">The value.</param>
public void Set(string name, object value)
{
CheckIfInitialized();
// In order to set a property in the property bag
// we need to convert the value to the destination type
var previousValue = Get(name);
value = Convert.ChangeType(value, previousValue==null?value.GetType() : previousValue.GetType());
// Set the property
var propbag2 = new PROPBAG2() { Name = name };
var result = nativePropertyBag.Write(1, ref propbag2, value);
result.CheckError();
propbag2.Dispose();
}
/// <summary>
/// Sets the value of the property by using a <see cref="PropertyBagKey{T1,T2}"/>
/// </summary>
/// <typeparam name="T1">The public type of this property.</typeparam>
/// <typeparam name="T2">The marshaling type of this property.</typeparam>
/// <param name="propertyKey">The property key.</param>
/// <param name="value">The value.</param>
public void Set<T1,T2>(PropertyBagKey<T1,T2> propertyKey, T1 value)
{
Set(propertyKey.Name, value);
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
private struct PROPBAG2 : IDisposable
{
internal uint type;
internal ushort vt;
internal ushort cfType;
internal IntPtr dwHint;
internal IntPtr pstrName;
internal Guid clsid;
public string Name
{
get
{
unsafe
{
return Marshal.PtrToStringUni(pstrName);
}
}
set
{
pstrName = Marshal.StringToCoTaskMemUni(value);
}
}
public void Dispose()
{
if (pstrName != IntPtr.Zero)
{
Marshal.FreeCoTaskMem(pstrName);
pstrName = IntPtr.Zero;
}
}
}
[ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("22F55882-280B-11D0-A8A9-00A0C90C2004")]
private interface IPropertyBag2
{
[PreserveSig()]
Result Read([In] int cProperties, [In] ref PROPBAG2 pPropBag, IntPtr pErrLog, [Out] out object pvarValue, out Result phrError);
[PreserveSig()]
Result Write([In] int cProperties, [In] ref PROPBAG2 pPropBag, ref object value);
[PreserveSig()]
Result CountProperties(out int pcProperties);
[PreserveSig()]
Result GetPropertyInfo([In] int iProperty, [In] int cProperties, out PROPBAG2 pPropBag, out int pcProperties);
[PreserveSig()]
Result LoadObject([In, MarshalAs(UnmanagedType.LPWStr)] string pstrName, [In] uint dwHint, [In, MarshalAs(UnmanagedType.IUnknown)] object pUnkObject, IntPtr pErrLog);
}
}
}
| |
// -----------------------------------------------------------------------
// <copyright file="DismissiblePopup.Generated.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// <auto-generated>
// This code was generated by a tool. DO NOT EDIT
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// -----------------------------------------------------------------------
#region StyleCop Suppression - generated code
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
namespace Microsoft.Management.UI.Internal
{
/// <summary>
/// A popup which child controls can signal to be dismissed.
/// </summary>
/// <remarks>
/// If a control wants to dismiss the popup then they should execute the DismissPopupCommand on a target in the popup window.
/// </remarks>
[Localizability(LocalizationCategory.None)]
partial class DismissiblePopup
{
//
// DismissPopup routed command
//
/// <summary>
/// A command which child controls can use to tell the popup to close.
/// </summary>
public static readonly RoutedCommand DismissPopupCommand = new RoutedCommand("DismissPopup",typeof(DismissiblePopup));
static private void DismissPopupCommand_CommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) sender;
obj.OnDismissPopupExecuted( e );
}
/// <summary>
/// Called when DismissPopup executes.
/// </summary>
/// <remarks>
/// A command which child controls can use to tell the popup to close.
/// </remarks>
protected virtual void OnDismissPopupExecuted(ExecutedRoutedEventArgs e)
{
OnDismissPopupExecutedImplementation(e);
}
partial void OnDismissPopupExecutedImplementation(ExecutedRoutedEventArgs e);
//
// CloseOnEscape dependency property
//
/// <summary>
/// Identifies the CloseOnEscape dependency property.
/// </summary>
public static readonly DependencyProperty CloseOnEscapeProperty = DependencyProperty.Register( "CloseOnEscape", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.TrueBox, CloseOnEscapeProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether the popup closes when ESC is pressed.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether the popup closes when ESC is pressed.")]
[Localizability(LocalizationCategory.None)]
public bool CloseOnEscape
{
get
{
return (bool) GetValue(CloseOnEscapeProperty);
}
set
{
SetValue(CloseOnEscapeProperty,BooleanBoxes.Box(value));
}
}
static private void CloseOnEscapeProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnCloseOnEscapeChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when CloseOnEscape property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> CloseOnEscapeChanged;
/// <summary>
/// Called when CloseOnEscape property changes.
/// </summary>
protected virtual void OnCloseOnEscapeChanged(PropertyChangedEventArgs<bool> e)
{
OnCloseOnEscapeChangedImplementation(e);
RaisePropertyChangedEvent(CloseOnEscapeChanged, e);
}
partial void OnCloseOnEscapeChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// FocusChildOnOpen dependency property
//
/// <summary>
/// Identifies the FocusChildOnOpen dependency property.
/// </summary>
public static readonly DependencyProperty FocusChildOnOpenProperty = DependencyProperty.Register( "FocusChildOnOpen", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.TrueBox, FocusChildOnOpenProperty_PropertyChanged) );
/// <summary>
/// Gets or sets a value indicating whether focus should be set on the child when the popup opens.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Gets or sets a value indicating whether focus should be set on the child when the popup opens.")]
[Localizability(LocalizationCategory.None)]
public bool FocusChildOnOpen
{
get
{
return (bool) GetValue(FocusChildOnOpenProperty);
}
set
{
SetValue(FocusChildOnOpenProperty,BooleanBoxes.Box(value));
}
}
static private void FocusChildOnOpenProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnFocusChildOnOpenChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when FocusChildOnOpen property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> FocusChildOnOpenChanged;
/// <summary>
/// Called when FocusChildOnOpen property changes.
/// </summary>
protected virtual void OnFocusChildOnOpenChanged(PropertyChangedEventArgs<bool> e)
{
OnFocusChildOnOpenChangedImplementation(e);
RaisePropertyChangedEvent(FocusChildOnOpenChanged, e);
}
partial void OnFocusChildOnOpenChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// SetFocusOnClose dependency property
//
/// <summary>
/// Identifies the SetFocusOnClose dependency property.
/// </summary>
public static readonly DependencyProperty SetFocusOnCloseProperty = DependencyProperty.Register( "SetFocusOnClose", typeof(bool), typeof(DismissiblePopup), new PropertyMetadata( BooleanBoxes.FalseBox, SetFocusOnCloseProperty_PropertyChanged) );
/// <summary>
/// Indicates whether the focus returns to either a defined by the FocusOnCloseTarget dependency property UIElement or PlacementTarget or not.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("Indicates whether the focus returns to either a defined by the FocusOnCloseTarget dependency property UIElement or PlacementTarget or not.")]
[Localizability(LocalizationCategory.None)]
public bool SetFocusOnClose
{
get
{
return (bool) GetValue(SetFocusOnCloseProperty);
}
set
{
SetValue(SetFocusOnCloseProperty,BooleanBoxes.Box(value));
}
}
static private void SetFocusOnCloseProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnSetFocusOnCloseChanged( new PropertyChangedEventArgs<bool>((bool)e.OldValue, (bool)e.NewValue) );
}
/// <summary>
/// Occurs when SetFocusOnClose property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<bool>> SetFocusOnCloseChanged;
/// <summary>
/// Called when SetFocusOnClose property changes.
/// </summary>
protected virtual void OnSetFocusOnCloseChanged(PropertyChangedEventArgs<bool> e)
{
OnSetFocusOnCloseChangedImplementation(e);
RaisePropertyChangedEvent(SetFocusOnCloseChanged, e);
}
partial void OnSetFocusOnCloseChangedImplementation(PropertyChangedEventArgs<bool> e);
//
// SetFocusOnCloseElement dependency property
//
/// <summary>
/// Identifies the SetFocusOnCloseElement dependency property.
/// </summary>
public static readonly DependencyProperty SetFocusOnCloseElementProperty = DependencyProperty.Register( "SetFocusOnCloseElement", typeof(UIElement), typeof(DismissiblePopup), new PropertyMetadata( null, SetFocusOnCloseElementProperty_PropertyChanged) );
/// <summary>
/// If the SetFocusOnClose property is set True and this property is set to a valid UIElement, focus returns to this UIElement after the DismissiblePopup is closed.
/// </summary>
[Bindable(true)]
[Category("Common Properties")]
[Description("If the SetFocusOnClose property is set True and this property is set to a valid UIElement, focus returns to this UIElement after the DismissiblePopup is closed.")]
[Localizability(LocalizationCategory.None)]
public UIElement SetFocusOnCloseElement
{
get
{
return (UIElement) GetValue(SetFocusOnCloseElementProperty);
}
set
{
SetValue(SetFocusOnCloseElementProperty,value);
}
}
static private void SetFocusOnCloseElementProperty_PropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
DismissiblePopup obj = (DismissiblePopup) o;
obj.OnSetFocusOnCloseElementChanged( new PropertyChangedEventArgs<UIElement>((UIElement)e.OldValue, (UIElement)e.NewValue) );
}
/// <summary>
/// Occurs when SetFocusOnCloseElement property changes.
/// </summary>
public event EventHandler<PropertyChangedEventArgs<UIElement>> SetFocusOnCloseElementChanged;
/// <summary>
/// Called when SetFocusOnCloseElement property changes.
/// </summary>
protected virtual void OnSetFocusOnCloseElementChanged(PropertyChangedEventArgs<UIElement> e)
{
OnSetFocusOnCloseElementChangedImplementation(e);
RaisePropertyChangedEvent(SetFocusOnCloseElementChanged, e);
}
partial void OnSetFocusOnCloseElementChangedImplementation(PropertyChangedEventArgs<UIElement> e);
/// <summary>
/// Called when a property changes.
/// </summary>
private void RaisePropertyChangedEvent<T>(EventHandler<PropertyChangedEventArgs<T>> eh, PropertyChangedEventArgs<T> e)
{
if(eh != null)
{
eh(this,e);
}
}
//
// Static constructor
//
/// <summary>
/// Called when the type is initialized.
/// </summary>
static DismissiblePopup()
{
CommandManager.RegisterClassCommandBinding( typeof(DismissiblePopup), new CommandBinding( DismissiblePopup.DismissPopupCommand, DismissPopupCommand_CommandExecuted ));
StaticConstructorImplementation();
}
static partial void StaticConstructorImplementation();
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using System.Web.Mvc.Routing.Constraints;
using System.Web.UI.DataVisualization.Charting;
using AjaxControlToolkit;
using Microsoft.EntityFrameworkCore.Query.ExpressionTranslators;
using MOE.Common.Business.TimingAndActuations;
using MOE.Common.Migrations;
using MOE.Common.Models;
using MOE.Common.Models.Repositories;
namespace MOE.Common.Business.WCFServiceLibrary
{
[DataContract]
public class TimingAndActuationsOptions : MetricOptions
{
[Display(Name = "Legend")]
[Required]
[DataMember]
public bool ShowLegend { get; set; }
[Display(Name = "Header For Each Phase")]
[Required]
[DataMember]
public bool ShowHeaderForEachPhase { get; set; }
[Display(Name = "Combine Lanes for Phase")]
[Required]
[DataMember]
public bool CombineLanesForEachGroup { get; set; }
[Display(Name = "Dot and Marker Size")]
[Required]
[DataMember]
public int DotAndBarSize { get; set; }
[Display(Name = "Phase Filter")]
[DataMember]
public string PhaseFilter { get; set; }
[Display(Name = "Phase Event Codes")]
[DataMember]
public string PhaseEventCodes { get; set; }
[Display(Name = "Global Event Codes")]
[DataMember]
public string GlobalCustomEventCodes { get; set; }
[Display(Name = "Global Event Params")]
[DataMember]
public string GlobalCustomEventParams { get; set; }
[Display(Name = "Extend Search (left) Minutes.decimal")]
[Required]
[DataMember]
public double ExtendVsdSearch { get; set; }
[Display(Name = "Vehicle Signal Display")]
[Required]
[DataMember]
public bool ShowVehicleSignalDisplay { get; set; }
[Display(Name = "Pedestrian Intervals")]
[Required]
[DataMember]
public bool ShowPedestrianIntervals { get; set; }
[Display(Name = "Pedestrian Actuations")]
[Required]
[DataMember]
public bool ShowPedestrianActuation { get; set; }
[Display(Name = "Extend Start/Stop Search Minutes.decimal")]
[Required]
[DataMember]
public double ExtendStartStopSearch { get; set; }
[Display(Name = "Stop Bar Presence")]
[Required]
[DataMember]
public bool ShowStopBarPresence { get; set; }
[Display(Name = "Lane-by-lane Count")]
[ Required]
[DataMember]
public bool ShowLaneByLaneCount { get; set; }
[Display(Name = "Advanced Presence")]
[Required]
[DataMember]
public bool ShowAdvancedDilemmaZone { get; set; }
[Display(Name = "Advanced Count")]
[Required]
[DataMember]
public bool ShowAdvancedCount { get; set; }
[Display(Name = "Advd Count Offset")]
[DataMember]
public double AdvancedOffset { get; set; }
[Display(Name = "All Lanes For Each Phase")]
[Required]
[DataMember]
public bool ShowAllLanesInfo { get; set; }
[Display(Name = "On/Off Lines")]
[Required]
[DataMember]
public bool ShowLinesStartEnd { get; set; }
[Display(Name = "Event Start Stop Pairs")]
[Required]
[DataMember]
public bool ShowEventPairs { get; set; }
[Display(Name = "Raw Data Display")]
[Required]
[DataMember]
public bool ShowRawEventData { get; set; }
public List<int> GlobalEventCodesList { get; set; }
public List<int> GlobalEventParamsList { get; set; }
public List<int> PhaseEventCodesList { get; set; }
public List<int> PhaseFilterList { get; set; }
public int GlobalEventCounter { get; set; }
public Models.Signal Signal { get; set; }
public int HeadTitleCounter { get; set; }
public TimingAndActuationsOptions(string signalID, DateTime startDate, DateTime endDate)
{
SignalID = signalID;
StartDate = startDate;
EndDate = endDate;
MetricTypeID = 17;
//ExtendSearch = 0;
}
public TimingAndActuationsOptions()
{
MetricTypeID = 17;
//ExtendSearch = 0;
SetDefaults();
}
public void SetDefaults()
{
ShowLegend = false;
CombineLanesForEachGroup = false;
ShowAdvancedCount = true;
ShowAdvancedDilemmaZone = true;
ShowAllLanesInfo = true;
ShowEventPairs = false;
ShowHeaderForEachPhase = false;
ShowLaneByLaneCount = true;
ShowLinesStartEnd = true;
ShowPedestrianActuation = true;
ShowPedestrianIntervals = true;
ShowStopBarPresence = true;
ShowRawEventData = false;
ShowVehicleSignalDisplay = true;
DotAndBarSize = 6;
AdvancedOffset = 0.0;
ExtendStartStopSearch = 2.0;
ExtendVsdSearch = 5.0;
}
public override List<string> CreateMetric()
{
base.CreateMetric();
var signalRepository = SignalsRepositoryFactory.Create();
Signal = signalRepository.GetVersionOfSignalByDateWithDetectionTypes(SignalID, StartDate);
var chart = new Chart();
HeadTitleCounter = 0;
var timingAndActuationsForPhases = new List<TimingAndActuationsForPhase>();
PhaseEventCodesList = ExtractListOfNumbers(PhaseEventCodes);
int phaseCounter = 0;
PhaseFilterList = ExtractListOfNumbers(PhaseFilter);
if (ShowRawEventData)
{
for (int i = 1; i <= 16; i++)
{
if (PhaseFilterList.Any() && PhaseFilterList.Contains(i) || PhaseFilterList.Count == 0)
{
var phaseOrOverlap = true;
timingAndActuationsForPhases.Add(new TimingAndActuationsForPhase(i, phaseOrOverlap, this));
timingAndActuationsForPhases[phaseCounter++].PhaseNumberSort = "Phase - " + i.ToString("D2");
phaseOrOverlap = false;
timingAndActuationsForPhases.Add(new TimingAndActuationsForPhase(i, phaseOrOverlap, this));
timingAndActuationsForPhases[phaseCounter++].PhaseNumberSort = "zOverlap - " + i.ToString("D2");
}
}
}
else
{
//var approachNumber = 1;
if (Signal.Approaches.Count > 0)
{
//Parallel.ForEach(Signal.Approaches, approach =>
foreach (var approach in Signal.Approaches)
{
bool permissivePhase;
if (approach.PermissivePhaseNumber != null && approach.PermissivePhaseNumber > 0)
{
if (PhaseFilterList.Any() && PhaseFilterList.Contains((int) approach.PermissivePhaseNumber)
|| PhaseFilterList.Count == 0)
{
var permissivePhaseNumber = (int) approach.PermissivePhaseNumber;
permissivePhase = true;
timingAndActuationsForPhases.Add(
new TimingAndActuationsForPhase(approach, this, permissivePhase));
timingAndActuationsForPhases[phaseCounter++].PhaseNumberSort =
approach.PermissivePhaseNumber.Value.ToString("D2") + "-1";
}
}
if (approach.ProtectedPhaseNumber > 0)
{
if (PhaseFilterList.Any() && PhaseFilterList.Contains(approach.ProtectedPhaseNumber)
|| PhaseFilterList.Count == 0)
{
permissivePhase = false;
timingAndActuationsForPhases.Add(
new TimingAndActuationsForPhase(approach, this, permissivePhase));
timingAndActuationsForPhases[phaseCounter++].PhaseNumberSort =
approach.ProtectedPhaseNumber.ToString("D2") + "-2";
}
}
}
//});
}
}
timingAndActuationsForPhases = timingAndActuationsForPhases.OrderBy(t => t.PhaseNumberSort).ToList();
// Can not add parrallelism because of contention for the same chart.
//Parallel.ForEach(timingAndActuationsForPhases, timingAndActutionsForPhase =>
foreach (var timingAndActutionsForPhase in timingAndActuationsForPhases)
{
GetChart(timingAndActutionsForPhase);
// });
}
GlobalEventCodesList = ExtractListOfNumbers(GlobalCustomEventCodes);
GlobalEventParamsList = ExtractListOfNumbers(GlobalCustomEventParams);
GlobalEventCounter = 0;
if (GlobalEventCodesList != null && GlobalEventParamsList != null &&
GlobalEventCodesList.Any() && GlobalEventCodesList.Count > 0 &&
GlobalEventParamsList.Any() && GlobalEventParamsList.Count > 0)
{
var globalGetDataTimingAndActuations = new GlobalGetDataTimingAndActuations(SignalID, this);
GetGlobalChart(globalGetDataTimingAndActuations, this);
}
if (ShowLegend)
{
GetChartLegend();
}
return ReturnList;
}
//private void CreateFilesForPartitions()
//{
// string path = @"C:\temp\PFunction_ControllerAndSpeed.txt";
// //using (var PF = new StreamWriter(path, false))
//{
// PF.WriteLine("USE [MOE]");
// PF.WriteLine("GO");
// PF.WriteLine();
// PF.WriteLine("CREATE PARTITION FUNCTION [PF_MOE_ControllerAndSpeed](datetime2(7)) AS RANGE RIGHT FOR VALUES ");
// PF.Write("(");
// var inTheBegining = this.StartDate;
// var inTheEnd = this.EndDate;
// for (int i = 0; i < 265; i++)
// {
// PF.Write("N'");
// PF.WriteLine(inTheBegining.ToString("s") + "',");
// inTheBegining = inTheBegining.AddDays(7);
// }
// PF.WriteLine();
// PF.WriteLine("GO");
// PF.Close();
//}
//path = @"C:\temp\PSchema_ControllerAndSpeed.txt";
//using (var PS = new StreamWriter(path, false))
//{
// var inTheBegining = this.StartDate;
// PS.WriteLine("USE [MOE]");
// PS.WriteLine("GO");
// PS.WriteLine();
// PS.WriteLine("CREATE PARTITION SCHEME [PS_MOE_ControllerAndSpeed] AS PARTITION [PF_MOE_ControllerAndSpeed] TO (");
// for (int i = 0; i < 265; i++)
// {
// PS.Write("[MOE_");
// PS.WriteLine(inTheBegining.ToString("yyyy-MM-dd") + "],");
// inTheBegining = inTheBegining.AddDays(7);
// }
// PS.WriteLine(")");
// PS.WriteLine("GO");
// PS.Close();
//}
//path = @"C:\temp\Files_ControllerAndSpeed.txt";
//using (var PF = new StreamWriter(path, false))
//{
// PF.WriteLine("USE [MOE]");
// PF.WriteLine("GO");
// PF.WriteLine();
// var inTheBegining = this.StartDate;
// var inTheEnd = this.EndDate;
// for (int i = 0; i < 265; i++)
// {
// PF.Write("ALTER DATABASE [MOE] ADD FILE (NAME = N'MOE_ControllerAndSpeed_");
// PF.WriteLine(inTheBegining.ToString("yyyy-MM-dd")
// + @"', FILENAME = N'E:\MSSQL\DATA\MOE_PARTITIONS\ControllerAndSpeed\ControllerAndSpeed_"
// + inTheBegining.ToString("yyyy-MM-dd")
// + ".NDF', SIZE = 8192MB, MAXSIZE = UNLIMITED, FILEGROWTH = 64MB) TO FILEGROUP "
// + "[MOE_ControllerAndSpeed_" + inTheBegining.ToString("yyyy-MM-dd") + "]");
// inTheBegining = inTheBegining.AddDays(7);
// }
// PF.WriteLine();
// PF.WriteLine("GO");
// PF.Close();
//}
//path = @"C:\temp\FileGroup_ControllerAndSpeed.txt";
//using (var PS = new StreamWriter(path, false))
//{
// var inTheBegining = this.StartDate;
// PS.WriteLine("USE [MOE]");
// PS.WriteLine("GO");
// PS.WriteLine();
// for (int i = 0; i < 265; i++)
// {
// PS.Write("ALTER DATABASE [MOE] ADD FILEGROUP [MOE_ControllerAndSpeed_");
// PS.WriteLine(inTheBegining.ToString("yyyy-MM-dd") + "]");
// inTheBegining = inTheBegining.AddDays(7);
// }
// PS.WriteLine();
// PS.WriteLine("GO");
// PS.Close();
//}
// path = @"C:\temp\PFunction_Aggregation.txt";
// using (var PF = new StreamWriter(path, false))
// {
// PF.WriteLine("USE [MOE]");
// PF.WriteLine("GO");
// PF.WriteLine();
// PF.WriteLine("CREATE PARTITION FUNCTION [PF_MOE_Aggregation](datetime2(7)) AS RANGE RIGHT FOR VALUES ");
// PF.Write("(");
// var inTheBegining = this.EndDate;
// for (int i = 0; i < 100; i++)
// {
// PF.Write("N'");
// PF.WriteLine(inTheBegining.ToString("s") + "',");
// inTheBegining = inTheBegining.AddMonths(1);
// }
// PF.WriteLine();
// PF.WriteLine("GO");
// PF.Close();
// }
// path = @"C:\temp\PSchema_Aggregation.txt";
// using (var PS = new StreamWriter(path, false))
// {
// var inTheBegining = this.EndDate;
// PS.WriteLine("USE [MOE]");
// PS.WriteLine("GO");
// PS.WriteLine();
// PS.WriteLine("CREATE PARTITION SCHEME [PS_MOE_Aggregation] AS PARTITION [PF_MOE_Aggregation] TO (");
// for (int i = 0; i < 100; i++)
// {
// PS.Write("[MOE_Aggregation_");
// PS.WriteLine(inTheBegining.ToString("yyyy-MM-dd") + "],");
// inTheBegining = inTheBegining.AddMonths(1);
// }
// PS.WriteLine(")");
// PS.WriteLine("GO");
// PS.Close();
// }
// path = @"C:\temp\Files_Aggregation.txt";
// using (var PF = new StreamWriter(path, false))
// {
// PF.WriteLine("USE [MOE]");
// PF.WriteLine("GO");
// PF.WriteLine();
// var inTheBegining = this.EndDate;
// for (int i = 0; i < 100; i++)
// {
// PF.Write("ALTER DATABASE [MOE] ADD FILE (NAME = N'MOE_Aggregation_");
// PF.WriteLine(inTheBegining.ToString("yyyy-MM-dd")
// + @"', FILENAME = N'E:\MSSQL\DATA\MOE_PARTITIONS\Aggregation\Aggregation_"
// + inTheBegining.ToString("yyyy-MM-dd")
// + ".NDF', SIZE = 2048MB, MAXSIZE = UNLIMITED, FILEGROWTH = 64MB) TO FILEGROUP "
// + "[MOE_Aggregation_" + inTheBegining.ToString("yyyy-MM-dd") + "]");
// inTheBegining = inTheBegining.AddMonths(1);
// }
// PF.WriteLine();
// PF.WriteLine("GO");
// PF.Close();
// }
// path = @"C:\temp\FileGroup_Aggregation.txt";
// using (var PS = new StreamWriter(path, false))
// {
// var inTheBegining = this.EndDate;
// PS.WriteLine("USE [MOE]");
// PS.WriteLine("GO");
// PS.WriteLine();
// for (int i = 0; i < 100; i++)
// {
// PS.WriteLine("ALTER DATABASE [MOE] ADD FILEGROUP [MOE_Aggregation_" + inTheBegining.ToString("yyyy-MM-dd") + "]");
// inTheBegining = inTheBegining.AddMonths(1);
// }
// PS.WriteLine();
// PS.WriteLine("GO");
// PS.Close();
// }
//}
private void GetChartLegend()
{
if (ReturnList == null)
ReturnList = new List<string>();
bool showRawData = true;
var taaLegendChart = new TimingAndActuationsChartForPhase(showRawData);
if (taaLegendChart.Chart != null)
{
taaLegendChart.Chart.BackColor = Color.Goldenrod;
var chartName = CreateFileName();
taaLegendChart.Chart.ImageLocation = MetricFileLocation + chartName;
taaLegendChart.Chart.SaveImage(MetricFileLocation + chartName, ChartImageFormat.Jpeg);
ReturnList.Add(MetricWebPath + chartName);
}
}
private void GetGlobalChart(GlobalGetDataTimingAndActuations globalGetDataTimingAndActuations,
TimingAndActuationsOptions options)
{
if (ReturnList == null) ReturnList = new List<string>();
var taaGlobalChart =
new ChartForGlobalEventsTimingAndActuations(globalGetDataTimingAndActuations, options)
{
Chart = {BackColor = Color.LightSkyBlue}
};
var chartName = CreateFileName();
taaGlobalChart.Chart.ImageLocation = MetricFileLocation + chartName;
taaGlobalChart.Chart.SaveImage(MetricFileLocation + chartName, ChartImageFormat.Jpeg);
ReturnList.Add(MetricWebPath + chartName);
}
private void GetChart(TimingAndActuationsForPhase timingAndActutionsForPhase)
{
if (ReturnList == null)
ReturnList = new List<string>();
var taaChart = new TimingAndActuationsChartForPhase(timingAndActutionsForPhase);
if (taaChart.Chart != null)
{
if (timingAndActutionsForPhase.GetPermissivePhase)
{
taaChart.Chart.BackColor = Color.LightGray;
}
var chartName = CreateFileName();
taaChart.Chart.ImageLocation = MetricFileLocation + chartName;
taaChart.Chart.SaveImage(MetricFileLocation + chartName, ChartImageFormat.Jpeg);
ReturnList.Add(MetricWebPath + chartName);
}
}
public List<int> ExtractListOfNumbers(string comnmaDashSepartedList)
{
var numbers = new List<int>();
if (String.IsNullOrEmpty(comnmaDashSepartedList))
{
return numbers;
}
numbers = CommaDashSeparated(comnmaDashSepartedList);
return numbers;
}
private List<int> CommaDashSeparated(string codesList)
{
var processedNumbers = new List<int>();
var codes = codesList.Split(',');
try
{
foreach (string code in codes)
{
if (code.Contains('-'))
{
string[] withDash = code.Split('-');
int minNum = Convert.ToInt32(withDash[0]);
int maxNum = Convert.ToInt32(withDash[1]);
if (minNum > maxNum)
{
int temp = minNum;
minNum = maxNum;
maxNum = temp;
}
for (int ii = minNum; ii <= maxNum; ii++)
{
processedNumbers.Add(ii);
}
}
else
{
processedNumbers.Add(Convert.ToInt32(code));
}
}
processedNumbers = processedNumbers.Distinct().OrderByDescending(p => p).ToList();
}
catch (Exception e)
{
}
return processedNumbers;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsAzureCompositeModelClient
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// PrimitiveOperations operations.
/// </summary>
public partial interface IPrimitiveOperations
{
/// <summary>
/// Get complex types with integer properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<IntWrapper>> GetIntWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with integer properties
/// </summary>
/// <param name='complexBody'>
/// Please put -1 and 2
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutIntWithHttpMessagesAsync(IntWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with long properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<LongWrapper>> GetLongWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with long properties
/// </summary>
/// <param name='complexBody'>
/// Please put 1099511627775 and -999511627788
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutLongWithHttpMessagesAsync(LongWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with float properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<FloatWrapper>> GetFloatWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with float properties
/// </summary>
/// <param name='complexBody'>
/// Please put 1.05 and -0.003
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutFloatWithHttpMessagesAsync(FloatWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with double properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DoubleWrapper>> GetDoubleWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with double properties
/// </summary>
/// <param name='complexBody'>
/// Please put 3e-100 and
/// -0.000000000000000000000000000000000000000000000000000000005
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutDoubleWithHttpMessagesAsync(DoubleWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with bool properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<BooleanWrapper>> GetBoolWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with bool properties
/// </summary>
/// <param name='complexBody'>
/// Please put true and false
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutBoolWithHttpMessagesAsync(BooleanWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with string properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<StringWrapper>> GetStringWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with string properties
/// </summary>
/// <param name='complexBody'>
/// Please put 'goodrequest', '', and null
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutStringWithHttpMessagesAsync(StringWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with date properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DateWrapper>> GetDateWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with date properties
/// </summary>
/// <param name='complexBody'>
/// Please put '0001-01-01' and '2016-02-29'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutDateWithHttpMessagesAsync(DateWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with datetime properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DatetimeWrapper>> GetDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with datetime properties
/// </summary>
/// <param name='complexBody'>
/// Please put '0001-01-01T12:00:00-04:00' and
/// '2015-05-18T11:38:00-08:00'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutDateTimeWithHttpMessagesAsync(DatetimeWrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<Datetimerfc1123Wrapper>> GetDateTimeRfc1123WithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with datetimeRfc1123 properties
/// </summary>
/// <param name='complexBody'>
/// Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015
/// 11:38:00 GMT'
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutDateTimeRfc1123WithHttpMessagesAsync(Datetimerfc1123Wrapper complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with duration properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<DurationWrapper>> GetDurationWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with duration properties
/// </summary>
/// <param name='field'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutDurationWithHttpMessagesAsync(TimeSpan? field = default(TimeSpan?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get complex types with byte properties
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse<ByteWrapper>> GetByteWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Put complex types with byte properties
/// </summary>
/// <param name='field'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<AzureOperationResponse> PutByteWithHttpMessagesAsync(byte[] field = default(byte[]), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
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;
// ERROR: Not supported in C#: OptionDeclaration
using Microsoft.VisualBasic.PowerPacks;
namespace _4PosBackOffice.NET
{
internal partial class frmOrderSummary : System.Windows.Forms.Form
{
ADODB.Recordset adoPrimaryRS;
List<Label> lblLabels = new List<Label>();
List<Label> lbl = new List<Label>();
List<TextBox> txtFields = new List<TextBox>();
List<Label> lblData = new List<Label>();
private void loadLanguage()
{
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1594;
//Complete Order|Checked
if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1579;
//Back|Checked
if (modRecordSet.rsLang.RecordCount){cmdBack.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdBack.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010;
//General|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1288;
//Telephone|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_8.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_8.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1289;
//Fax|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_9.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_9.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1291;
//Physical Address|
if (modRecordSet.rsLang.RecordCount){_lblLabels_6.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_6.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1292;
//Postal Address|Checked
if (modRecordSet.rsLang.RecordCount){_lblLabels_7.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lblLabels_7.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1458;
//Ordering Details|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1455;
//Representative Name|Checked
if (modRecordSet.rsLang.RecordCount){lblLabels[38].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lblLabels[38].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1456;
//Representative Number|Checked
if (modRecordSet.rsLang.RecordCount){lblLabels[37].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lblLabels[37].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1457;
//Account Number|Checked
if (modRecordSet.rsLang.RecordCount){lblLabels[36].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lblLabels[36].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//frmOrder = No Code [Order Totals]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _lbl_5.Caption = rsLang("LanguageLayoutLnk_Description"): _lbl_5.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1605;
//Content Total|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1606;
//Deposit Total|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_4.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_4.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1607;
//Order Exclusive Total|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1608;
//Process this Order|Checked
if (modRecordSet.rsLang.RecordCount){lbl[8].Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;lbl[8].RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1609;
//Order Reference|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_6.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_6.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1610;
//Order Attention Line|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_7.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_7.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1332;
//Process|Checked
if (modRecordSet.rsLang.RecordCount){cmdNext.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdNext.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmOrderSummary.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"'
if (modRecordSet.rsHelp.RecordCount)
this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value;
}
public void doTotals()
{
decimal lContent = default(decimal);
decimal lQuantity = default(decimal);
decimal lDeposit = default(decimal);
lContent = Convert.ToDecimal(My.MyProject.Forms.frmOrderItem.lblContent.Text);
lDeposit = Convert.ToDecimal(My.MyProject.Forms.frmOrderItem.lblDeposit.Text);
this.lblContentTotal.Text = Strings.FormatNumber(lContent, 2);
lblDepositTotal.Text = Strings.FormatNumber(lDeposit, 2);
lblTotal.Text = Strings.FormatNumber(lContent + lDeposit, 2);
}
private void cmdBack_Click(System.Object eventSender, System.EventArgs eventArgs)
{
System.Windows.Forms.Application.DoEvents();
this.Close();
}
private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs)
{
System.Windows.Forms.Application.DoEvents();
this.Close();
System.Windows.Forms.Application.DoEvents();
My.MyProject.Forms.frmOrderItem.Close();
System.Windows.Forms.Application.DoEvents();
My.MyProject.Forms.frmOrder.Close();
}
private void cmdNext_Click(System.Object eventSender, System.EventArgs eventArgs)
{
int gID = 0;
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rsComp = default(ADODB.Recordset);
string sql = null;
if (Interaction.MsgBox("You are about to commit this order." + Constants.vbCrLf + "Are you sure you wish to continue?", MsgBoxStyle.Question + MsgBoxStyle.YesNo + MsgBoxStyle.DefaultButton2, "Commit Order") == MsgBoxResult.Yes) {
update_Renamed();
modRecordSet.cnnDB.Execute("INSERT INTO PurchaseOrder ( PurchaseOrder_SupplierID, PurchaseOrder_DayEndID, PurchaseOrder_DateCreated, PurchaseOrder_DatePosted, PurchaseOrder_Reference, PurchaseOrder_PurchaseOrderStatusID, PurchaseOrder_AttentionLine ) SELECT TempOrder.TempOrder_SupplierID, Company.Company_DayEndID, TempOrder.TempOrder_DateCreated, Now() AS [date], TempOrder.TempOrder_Reference, 1 AS Status, TempOrder.TempOrder_AttentionLine From TempOrder, Company WHERE (((TempOrder.TempOrder_SupplierID)=" + adoPrimaryRS.Fields("SupplierID").Value + "));");
rs = modRecordSet.getRS(ref "SELECT Max(PurchaseOrder.PurchaseOrderID) AS id FROM PurchaseOrder;");
gID = rs.Fields("id").Value;
//sql = "INSERT INTO PurchaseOrderItem ( PurchaseOrderItem_PurchaseOrderID, PurchaseOrderItem_StockItemID, PurchaseOrderItem_PackSize, PurchaseOrderItem_QuantityRequired, PurchaseOrderItem_Quantity, PurchaseOrderItem_QuantityDelivered, PurchaseOrderItem_DepositUnitCost, PurchaseOrderItem_DepositPackCost, PurchaseOrderItem_DepositCost, PurchaseOrderItem_ContentCost ) SELECT " & gID & " AS purchaseOrder, TempOrderItem.TempOrderItem_StockItemID, TempOrderItem.TempOrderItem_PackSize, TempOrderItem.TempOrderItem_QuantityRequired, TempOrderItem.TempOrderItem_Quantity, 0 AS delivered, Deposit.Deposit_UnitCost, Deposit.Deposit_CaseCost, (Abs([TempOrderItem_PackSize]=[StockItem_Quantity])*[Deposit_CaseCost])+([TempOrderItem_PackSize]*[Deposit_UnitCost]) AS deposit, [StockItem_ListCost] AS content "
sql = "INSERT INTO PurchaseOrderItem ( PurchaseOrderItem_PurchaseOrderID, PurchaseOrderItem_StockItemID, PurchaseOrderItem_PackSize, PurchaseOrderItem_QuantityRequired, PurchaseOrderItem_Quantity, PurchaseOrderItem_QuantityDelivered, PurchaseOrderItem_DepositUnitCost, PurchaseOrderItem_DepositPackCost, PurchaseOrderItem_DepositCost, PurchaseOrderItem_ContentCost ) SELECT " + gID + " AS purchaseOrder, TempOrderItem.TempOrderItem_StockItemID, TempOrderItem.TempOrderItem_PackSize, TempOrderItem.TempOrderItem_QuantityRequired, TempOrderItem.TempOrderItem_Quantity, 0 AS delivered, Deposit.Deposit_UnitCost, Deposit.Deposit_CaseCost, (Abs([TempOrderItem_PackSize]=[StockItem_Quantity])*[Deposit_CaseCost])+([TempOrderItem_PackSize]*[Deposit_UnitCost]) AS deposit, TempOrderItem.TempOrderItem_ContentCost AS content ";
sql = sql + "FROM (StockItem INNER JOIN TempOrderItem ON StockItem.StockItemID = TempOrderItem.TempOrderItem_StockItemID) INNER JOIN Deposit ON StockItem.StockItem_DepositID = Deposit.DepositID WHERE (((TempOrderItem.TempOrderItem_SupplierID)=" + adoPrimaryRS.Fields("SupplierID").Value + "));";
modRecordSet.cnnDB.Execute(sql);
rsComp = modRecordSet.getRS(ref "SELECT Company_POPrintBC FROM Company;");
if (rsComp.RecordCount) {
if ((Information.IsDBNull(rsComp.Fields("Company_POPrintBC").Value) ? false : rsComp.Fields("Company_POPrintBC").Value)) {
//cnnDB.Execute "UPDATE PurchaseOrderItem INNER JOIN Catalogue ON PurchaseOrderItem.PurchaseOrderItem_StockItemID = Catalogue.Catalogue_StockItemID SET PurchaseOrderItem.PurchaseOrderItem_Code = [Catalogue]![Catalogue_Barcode] WHERE (((Catalogue.Catalogue_Quantity)=1) AND ((PurchaseOrderItem.PurchaseOrderItem_PurchaseOrderID)=" & gID & "));"
modRecordSet.cnnDB.Execute("UPDATE (PurchaseOrderItem INNER JOIN Catalogue ON PurchaseOrderItem.PurchaseOrderItem_StockItemID = Catalogue.Catalogue_StockItemID) INNER JOIN StockItem ON PurchaseOrderItem.PurchaseOrderItem_StockItemID = StockItem.StockItemID SET PurchaseOrderItem.PurchaseOrderItem_Name = [StockItem]![StockItem_Name], PurchaseOrderItem.PurchaseOrderItem_Code = [Catalogue]![Catalogue_Barcode] WHERE (((Catalogue.Catalogue_Quantity)=1) AND ((PurchaseOrderItem.PurchaseOrderItem_PurchaseOrderID)=" + gID + "));");
} else {
modRecordSet.cnnDB.Execute("UPDATE PurchaseOrderItem INNER JOIN StockItem ON PurchaseOrderItem.PurchaseOrderItem_StockItemID = StockItem.StockItemID SET PurchaseOrderItem.PurchaseOrderItem_Name = [StockItem]![StockItem_Name], PurchaseOrderItem.PurchaseOrderItem_Code = '' WHERE (((PurchaseOrderItem.PurchaseOrderItem_PurchaseOrderID)=" + gID + "));");
modRecordSet.cnnDB.Execute("UPDATE ((PurchaseOrderItem INNER JOIN StockItem ON PurchaseOrderItem.PurchaseOrderItem_StockItemID = StockItem.StockItemID) INNER JOIN BrandItemSupplier ON StockItem.StockItem_BrandItemID = BrandItemSupplier.BrandItemSupplier_BrandItemID) INNER JOIN PurchaseOrder ON (PurchaseOrder.PurchaseOrderID = PurchaseOrderItem.PurchaseOrderItem_PurchaseOrderID) AND (BrandItemSupplier.BrandItemSupplier_SupplierID = PurchaseOrder.PurchaseOrder_SupplierID) SET PurchaseOrderItem.PurchaseOrderItem_Code = [BrandItemSupplier]![BrandItemSupplier_Code] WHERE (((PurchaseOrder.PurchaseOrderID)=" + gID + "));");
}
} else {
modRecordSet.cnnDB.Execute("UPDATE PurchaseOrderItem INNER JOIN StockItem ON PurchaseOrderItem.PurchaseOrderItem_StockItemID = StockItem.StockItemID SET PurchaseOrderItem.PurchaseOrderItem_Name = [StockItem]![StockItem_Name], PurchaseOrderItem.PurchaseOrderItem_Code = '' WHERE (((PurchaseOrderItem.PurchaseOrderItem_PurchaseOrderID)=" + gID + "));");
modRecordSet.cnnDB.Execute("UPDATE ((PurchaseOrderItem INNER JOIN StockItem ON PurchaseOrderItem.PurchaseOrderItem_StockItemID = StockItem.StockItemID) INNER JOIN BrandItemSupplier ON StockItem.StockItem_BrandItemID = BrandItemSupplier.BrandItemSupplier_BrandItemID) INNER JOIN PurchaseOrder ON (PurchaseOrder.PurchaseOrderID = PurchaseOrderItem.PurchaseOrderItem_PurchaseOrderID) AND (BrandItemSupplier.BrandItemSupplier_SupplierID = PurchaseOrder.PurchaseOrder_SupplierID) SET PurchaseOrderItem.PurchaseOrderItem_Code = [BrandItemSupplier]![BrandItemSupplier_Code] WHERE (((PurchaseOrder.PurchaseOrderID)=" + gID + "));");
}
modRecordSet.cnnDB.Execute("DELETE FROM TempOrderItem WHERE (TempOrderItem_SupplierID = " + adoPrimaryRS.Fields("SupplierID").Value + ")");
modRecordSet.cnnDB.Execute("DELETE FROM TempOrder WHERE (TempOrder_SupplierID = " + adoPrimaryRS.Fields("SupplierID").Value + ")");
modApplication.report_PurchaseOrder(ref gID);
cmdExit_Click(cmdExit, new System.EventArgs());
}
}
private void frmOrderSummary_Load(System.Object eventSender, System.EventArgs eventArgs)
{
lblLabels.AddRange(new Label[] {
_lblLabels_36,
_lblLabels_37,
_lblLabels_38,
_lblLabels_6,
_lblLabels_7,
_lblLabels_8,
_lblLabels_8,
_lblLabels_9
});
lbl.AddRange(new Label[] {
_lbl_0,
_lbl_1,
_lbl_2,
_lbl_3,
_lbl_4,
_lbl_5,
_lbl_6,
_lbl_7,
_lbl_8
});
lblData.AddRange(new Label[] {
_lblData_0,
_lblData_1,
_lblData_2,
_lblData_3,
_lblData_4,
_lblData_5,
_lblData_6,
_lblData_7
});
txtFields.AddRange(new TextBox[] {
_txtFields_0,
_txtFields_1
});
TextBox tb = new TextBox();
foreach (TextBox tb_loopVariable in txtFields) {
tb = tb_loopVariable;
tb.Enter += txtFields_Enter;
}
System.Windows.Forms.Label oLabel = null;
System.Windows.Forms.TextBox oText = null;
adoPrimaryRS = modRecordSet.getRS(ref "SELECT Supplier.*, TempOrder.* FROM Supplier INNER JOIN TempOrder ON Supplier.SupplierID = TempOrder.TempOrder_SupplierID WHERE (((Supplier.SupplierID)=" + My.MyProject.Forms.frmOrder.adoPrimaryRS.Fields("SupplierID").Value + "));");
foreach (TextBox oText_loopVariable in txtFields) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
foreach (Label oLabel_loopVariable in this.lblData) {
oLabel = oLabel_loopVariable;
oLabel.DataBindings.Add(adoPrimaryRS);
}
loadLanguage();
doTotals();
}
private void frmOrderSummary_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
update_Renamed();
}
private void update_Renamed()
{
// On Error GoTo UpdateErr
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
return;
UpdateErr:
Interaction.MsgBox(Err().Description);
}
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox txtBox = new TextBox();
txtBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref txtBox, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[Index]);
}
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the Microsoft Public License.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using SDKTemplate;
using Windows.Security.Credentials;
using Windows.Security.Authentication.Web.Core;
using System;
using Windows.Storage;
using System.Threading.Tasks;
using System.Collections.Generic;
using Windows.UI.Popups;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace Accounts
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class SingleAccountScenario : Page
{
private MainPage rootPage;
const string AppSpecificProviderId = "myproviderid";
const string AppSpecificProviderName = "App specific provider";
const string MicrosoftProviderId = "https://login.microsoft.com";
const string MicrosoftAccountAuthority = "consumers";
const string AzureActiveDirectoryAuthority = "organizations";
const string StoredAccountIdKey = "accountid";
const string StoredProviderIdKey = "providerid";
const string StoredAuthorityKey = "authority";
const string MicrosoftAccountClientId = "none";
const string MicrosoftAccountScopeRequested = "service::wl.basic::DELEGATION";
// To obtain azureAD tokens, you must register this app on the AzureAD portal, and obtain the client ID
const string AzureActiveDirectoryClientId = "";
const string AzureActiveDirectoryScopeRequested = "";
public SingleAccountScenario()
{
this.InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested += OnAccountCommandsRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
AccountsSettingsPane.GetForCurrentView().AccountCommandsRequested -= OnAccountCommandsRequested;
}
private void Button_ShowAccountSettings(object sender, RoutedEventArgs e)
{
((Button)sender).IsEnabled = false;
rootPage.NotifyUser("Launching AccountSettingsPane", NotifyType.StatusMessage);
AccountsSettingsPane.Show();
((Button)sender).IsEnabled = true;
}
private async void Button_Reset(object sender, RoutedEventArgs e)
{
((Button)sender).IsEnabled = false;
rootPage.NotifyUser("Resetting...", NotifyType.StatusMessage);
await LogoffAndRemoveAccount();
((Button)sender).IsEnabled = true;
}
private async void OnAccountCommandsRequested(
AccountsSettingsPane sender,
AccountsSettingsPaneCommandsRequestedEventArgs e)
{
// In order to make async calls within this callback, the deferral object is needed
AccountsSettingsPaneEventDeferral deferral = e.GetDeferral();
// This scenario only lets the user have one account at a time.
// If there already is an account, we do not include a provider in the list
// This will prevent the add account button from showing up.
if (HasAccountStored())
{
await AddWebAccountToPane(e);
}
else
{
await AddWebAccountProvidersToPane(e);
}
AddLinksAndDescription(e);
deferral.Complete();
}
private void AddLinksAndDescription(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
e.HeaderText = "Describe what adding an account to your application will do for the user";
// You can add links such as privacy policy, help, general account settings
e.Commands.Add(new SettingsCommand("privacypolicy", "Privacy Policy", PrivacyPolicyInvoked));
e.Commands.Add(new SettingsCommand("otherlink", "Other Link", OtherLinkInvoked));
}
private async Task AddWebAccountProvidersToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
List<WebAccountProvider> providers = new List<WebAccountProvider>();
// Microsoft account and Azure AD providers will always return. Non-installed plugins or incorrect identities will return null
providers.Add(await GetProvider(MicrosoftProviderId, MicrosoftAccountAuthority));
providers.Add(await GetProvider(MicrosoftProviderId, AzureActiveDirectoryAuthority));
providers.Add(await GetProvider(AppSpecificProviderId));
foreach (WebAccountProvider provider in providers)
{
WebAccountProviderCommand providerCommand = new WebAccountProviderCommand(provider, WebAccountProviderCommandInvoked);
e.WebAccountProviderCommands.Add(providerCommand);
}
}
private async Task<WebAccount> GetWebAccount()
{
String accountID = ApplicationData.Current.LocalSettings.Values[StoredAccountIdKey] as String;
String providerID = ApplicationData.Current.LocalSettings.Values[StoredProviderIdKey] as String;
String authority = ApplicationData.Current.LocalSettings.Values[StoredAuthorityKey] as String;
WebAccount account;
WebAccountProvider provider = await GetProvider(providerID);
if (providerID == AppSpecificProviderId)
{
account = new WebAccount(provider, accountID, WebAccountState.None);
}
else
{
account = await WebAuthenticationCoreManager.FindAccountAsync(provider, accountID);
// The account has been deleted if FindAccountAsync returns null
if (account == null)
{
RemoveAccountData();
}
}
return account;
}
private async Task AddWebAccountToPane(AccountsSettingsPaneCommandsRequestedEventArgs e)
{
WebAccount account = await GetWebAccount();
WebAccountCommand command = new WebAccountCommand(account, WebAccountInvoked, SupportedWebAccountActions.Remove | SupportedWebAccountActions.Manage);
e.WebAccountCommands.Add(command);
}
private async Task<WebAccountProvider> GetProvider(string ProviderID, string AuthorityId = "")
{
if (ProviderID == AppSpecificProviderId)
{
return new WebAccountProvider(AppSpecificProviderId, AppSpecificProviderName, new Uri(this.BaseUri, "Assets/smallTile-sdk.png"));
}
else
{
return await WebAuthenticationCoreManager.FindAccountProviderAsync(ProviderID, AuthorityId);
}
}
private void OtherLinkInvoked(IUICommand command)
{
rootPage.NotifyUser("Other link pressed by user", NotifyType.StatusMessage);
}
private void PrivacyPolicyInvoked(IUICommand command)
{
rootPage.NotifyUser("Privacy policy clicked by user", NotifyType.StatusMessage);
}
private void WebAccountProviderCommandInvoked(WebAccountProviderCommand command)
{
if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == MicrosoftAccountAuthority))
{
// ClientID is ignored by MSA
AuthenticateWithRequestToken(command.WebAccountProvider, MicrosoftAccountScopeRequested, MicrosoftAccountClientId);
}
else if ((command.WebAccountProvider.Id == MicrosoftProviderId) && (command.WebAccountProvider.Authority == AzureActiveDirectoryAuthority))
{
AuthenticateWithRequestToken(command.WebAccountProvider, AzureActiveDirectoryAuthority, AzureActiveDirectoryClientId);
}
else if (command.WebAccountProvider.Id == AppSpecificProviderId)
{
// Show user registration/login for your app specific account type.
// Store the user if registration/login successful
StoreNewAccountDataLocally(new WebAccount(command.WebAccountProvider, "App Specific User", WebAccountState.None));
}
}
public async void AuthenticateWithRequestToken(WebAccountProvider Provider, String Scope, String ClientID)
{
try
{
WebTokenRequest webTokenRequest = new WebTokenRequest(Provider, Scope, ClientID);
// Azure Active Directory requires a resource to return a token
if(Provider.Id == "https://login.microsoft.com" && Provider.Authority == "organizations")
{
webTokenRequest.Properties.Add("resource", "https://graph.windows.net");
}
// If the user selected a specific account, RequestTokenAsync will return a token for that account.
// The user may be prompted for credentials or to authorize using that account with your app
// If the user selected a provider, the user will be prompted for credentials to login to a new account
WebTokenRequestResult webTokenRequestResult = await WebAuthenticationCoreManager.RequestTokenAsync(webTokenRequest);
if (webTokenRequestResult.ResponseStatus == WebTokenRequestStatus.Success)
{
StoreNewAccountDataLocally(webTokenRequestResult.ResponseData[0].WebAccount);
}
OutputTokenResult(webTokenRequestResult);
}
catch (Exception ex)
{
rootPage.NotifyUser("Web Token request failed: " + ex, NotifyType.ErrorMessage);
}
}
public void StoreNewAccountDataLocally(WebAccount account)
{
if (account.Id != "")
{
ApplicationData.Current.LocalSettings.Values["AccountID"] = account.Id;
}
else
{
// It's a custom account
ApplicationData.Current.LocalSettings.Values["AccountID"] = account.UserName;
}
ApplicationData.Current.LocalSettings.Values["ProviderID"] = account.WebAccountProvider.Id;
if (account.WebAccountProvider.Authority != null)
{
ApplicationData.Current.LocalSettings.Values["Authority"] = account.WebAccountProvider.Authority;
}
else
{
ApplicationData.Current.LocalSettings.Values["Authority"] = "";
}
}
public void OutputTokenResult(WebTokenRequestResult result)
{
if (result.ResponseStatus == WebTokenRequestStatus.Success)
{
rootPage.NotifyUser("Web Token request successful for user:" + result.ResponseData[0].WebAccount.UserName, NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser("Web Token request error: " + result.ResponseStatus + " Code: " + result.ResponseError.ErrorMessage, NotifyType.StatusMessage);
}
}
private async void WebAccountInvoked(WebAccountCommand command, WebAccountInvokedArgs args)
{
if (args.Action == WebAccountAction.Remove)
{
rootPage.NotifyUser("Removing account", NotifyType.StatusMessage);
await LogoffAndRemoveAccount();
}
else if (args.Action == WebAccountAction.Manage)
{
// Display user management UI for this account
rootPage.NotifyUser("Managing account", NotifyType.StatusMessage);
}
}
private bool HasAccountStored()
{
return (ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAccountIdKey) &&
ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredProviderIdKey) &&
ApplicationData.Current.LocalSettings.Values.ContainsKey(StoredAuthorityKey));
}
private async Task LogoffAndRemoveAccount()
{
if (HasAccountStored())
{
WebAccount account = await GetWebAccount();
// Check if the account has been deleted already by Token Broker
if (account != null)
{
if (account.WebAccountProvider.Id == AppSpecificProviderId)
{
// perform actions to sign out of the app specific provider
}
else
{
await account.SignOutAsync();
}
}
account = null;
RemoveAccountData();
}
}
private void RemoveAccountData()
{
ApplicationData.Current.LocalSettings.Values.Remove(StoredAccountIdKey);
ApplicationData.Current.LocalSettings.Values.Remove(StoredProviderIdKey);
ApplicationData.Current.LocalSettings.Values.Remove(StoredAuthorityKey);
}
}
}
| |
using System;
using Android.Content;
using Android.Graphics;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace Plugin.ImageCropper
{
public abstract class ImageViewTouchBase : ImageView
{
#region Members
// This is the base transformation which is used to show the image
// initially. The current computation for this shows the image in
// it's entirety, letterboxing as needed. One could choose to
// show the image as cropped instead.
//
// This MatrixImage is recomputed when we go from the thumbnail image to
// the full size image.
protected Matrix baseMatrix = new Matrix ();
// This is the supplementary transformation which reflects what
// the user has done in terms of zooming and panning.
//
// This MatrixImage remains the same when we go from the thumbnail image
// to the full size image.
protected Matrix suppMatrix = new Matrix ();
// This is the final MatrixImage which is computed as the concatentation
// of the base MatrixImage and the supplementary MatrixImage.
private Matrix displayMatrix = new Matrix ();
// Temporary buffer used for getting the values out of a MatrixImage.
private float[] matrixValues = new float[9];
// The current bitmap being displayed.
protected RotateBitmap bitmapDisplayed = new RotateBitmap (null);
private int thisWidth = -1;
private int thisHeight = -1;
const float SCALE_RATE = 1.25F;
private float maxZoom;
private Handler handler = new Handler ();
private Action onLayoutRunnable = null;
#endregion
protected ImageViewTouchBase (Context context) : base (context)
{
Init ();
}
protected ImageViewTouchBase (Context context, IAttributeSet attrs) : base (context, attrs)
{
Init ();
}
#region Private helpers
private void Init ()
{
SetScaleType (ImageView.ScaleType.Matrix);
}
private void SetImageBitmap (Bitmap bitmap, int rotation)
{
base.SetImageBitmap (bitmap);
Drawable?.SetDither (true);
bitmapDisplayed.Bitmap = bitmap;
bitmapDisplayed.Rotation = rotation;
}
#endregion
#region Public methods
public void Clear ()
{
SetImageBitmapResetBase (null, true);
}
/// <summary>
/// This function changes bitmap, reset base MatrixImage according to the size
/// of the bitmap, and optionally reset the supplementary MatrixImage.
/// </summary>
public void SetImageBitmapResetBase (Bitmap bitmap, bool resetSupp)
{
SetImageRotateBitmapResetBase (new RotateBitmap (bitmap), resetSupp);
}
public void SetImageRotateBitmapResetBase (RotateBitmap bitmap, bool resetSupp)
{
if (Width <= 0)
{
onLayoutRunnable = () => SetImageRotateBitmapResetBase (bitmap, resetSupp);
return;
}
if (bitmap.Bitmap != null)
{
GetProperBaseMatrix (bitmap, baseMatrix);
SetImageBitmap (bitmap.Bitmap, bitmap.Rotation);
}
else
{
baseMatrix.Reset ();
base.SetImageBitmap (null);
}
if (resetSupp)
{
suppMatrix.Reset ();
}
ImageMatrix = GetImageViewMatrix ();
maxZoom = CalculateMaxZoom ();
}
#endregion
#region Overrides
protected override void OnLayout (bool changed, int left, int top, int right, int bottom)
{
IvLeft = left;
IvRight = right;
IvTop = top;
IvBottom = bottom;
thisWidth = right - left;
thisHeight = bottom - top;
var r = onLayoutRunnable;
if (r != null)
{
onLayoutRunnable = null;
r ();
}
if (bitmapDisplayed.Bitmap != null)
{
GetProperBaseMatrix (bitmapDisplayed, baseMatrix);
ImageMatrix = GetImageViewMatrix ();
}
}
public override bool OnKeyDown (Keycode keyCode, KeyEvent e)
{
if (keyCode == Keycode.Back && GetScale () > 1.0f)
{
// If we're zoomed in, pressing Back jumps out to show the entire
// image, otherwise Back returns the user to the gallery.
ZoomTo (1.0f);
return true;
}
return base.OnKeyDown (keyCode, e);
}
public override void SetImageBitmap (Bitmap bm)
{
SetImageBitmap (bm, 0);
}
#endregion
#region Properties
public int IvLeft { get; private set; }
public int IvRight { get; private set; }
public int IvTop { get; private set; }
public int IvBottom { get; private set; }
#endregion
#region Protected methods
protected float GetValue (Matrix matrix, int whichValue)
{
matrix.GetValues (matrixValues);
return matrixValues[whichValue];
}
/// <summary>
/// Get the scale factor out of the MatrixImage.
/// </summary>
protected float GetScale (Matrix matrix)
{
return GetValue (matrix, Matrix.MscaleX);
}
protected float GetScale ()
{
return GetScale (suppMatrix);
}
/// <summary>
/// Setup the base MatrixImage so that the image is centered and scaled properly.
/// </summary>
private void GetProperBaseMatrix (RotateBitmap bitmap, Matrix matrix)
{
float viewWidth = Width;
float viewHeight = Height;
float w = bitmap.Width;
float h = bitmap.Height;
int rotation = bitmap.Rotation;
matrix.Reset ();
// We limit up-scaling to 2x otherwise the result may look bad if it's
// a small icon.
float widthScale = Math.Min (viewWidth / w, 2.0f);
float heightScale = Math.Min (viewHeight / h, 2.0f);
float scale = Math.Min (widthScale, heightScale);
matrix.PostConcat (bitmap.GetRotateMatrix ());
matrix.PostScale (scale, scale);
matrix.PostTranslate (
(viewWidth - w * scale) / 2F,
(viewHeight - h * scale) / 2F);
}
// Combine the base MatrixImage and the supp MatrixImage to make the final MatrixImage.
protected Matrix GetImageViewMatrix ()
{
// The final MatrixImage is computed as the concatentation of the base MatrixImage
// and the supplementary MatrixImage.
displayMatrix.Set (baseMatrix);
displayMatrix.PostConcat (suppMatrix);
return displayMatrix;
}
// Sets the maximum zoom, which is a scale relative to the base MatrixImage. It
// is calculated to show the image at 400% zoom regardless of screen or
// image orientation. If in the future we decode the full 3 megapixel image,
// rather than the current 1024x768, this should be changed down to 200%.
protected float CalculateMaxZoom ()
{
if (bitmapDisplayed.Bitmap == null)
{
return 1F;
}
float fw = (float)bitmapDisplayed.Width / thisWidth;
float fh = (float)bitmapDisplayed.Height / thisHeight;
return (Math.Max (fw, fh) * 4);
}
protected virtual void ZoomTo (float scale, float centerX, float centerY)
{
if (scale > maxZoom)
{
scale = maxZoom;
}
float oldScale = GetScale ();
float deltaScale = scale / oldScale;
suppMatrix.PostScale (deltaScale, deltaScale, centerX, centerY);
ImageMatrix = GetImageViewMatrix ();
Center (true, true);
}
protected void ZoomTo (float scale, float centerX, float centerY, float durationMs)
{
float incrementPerMs = (scale - GetScale ()) / durationMs;
float oldScale = GetScale ();
long startTime = System.Environment.TickCount;
Action anim = null;
anim = () => {
long now = System.Environment.TickCount;
float currentMs = Math.Min (durationMs, now - startTime);
float target = oldScale + (incrementPerMs * currentMs);
ZoomTo (target, centerX, centerY);
if (currentMs < durationMs)
{
handler.Post (anim);
}
};
handler.Post (anim);
}
protected void ZoomTo (float scale)
{
float cx = Width / 2F;
float cy = Height / 2F;
ZoomTo (scale, cx, cy);
}
protected virtual void ZoomIn ()
{
ZoomIn (SCALE_RATE);
}
protected virtual void ZoomOut ()
{
ZoomOut (SCALE_RATE);
}
protected virtual void ZoomIn (float rate)
{
if (GetScale () >= maxZoom)
{
// Don't let the user zoom into the molecular level.
return;
}
if (bitmapDisplayed.Bitmap == null)
{
return;
}
float cx = Width / 2F;
float cy = Height / 2F;
suppMatrix.PostScale (rate, rate, cx, cy);
ImageMatrix = GetImageViewMatrix ();
}
protected void ZoomOut (float rate)
{
if (bitmapDisplayed.Bitmap == null)
{
return;
}
float cx = Width / 2F;
float cy = Height / 2F;
// Zoom out to at most 1x.
var tmp = new Matrix (suppMatrix);
tmp.PostScale (1F / rate, 1F / rate, cx, cy);
if (GetScale (tmp) < 1F)
{
suppMatrix.SetScale (1F, 1F, cx, cy);
}
else
{
suppMatrix.PostScale (1F / rate, 1F / rate, cx, cy);
}
ImageMatrix = GetImageViewMatrix ();
Center (true, true);
}
protected virtual void PostTranslate (float dx, float dy)
{
suppMatrix.PostTranslate (dx, dy);
}
protected void PanBy (float dx, float dy)
{
PostTranslate (dx, dy);
ImageMatrix = GetImageViewMatrix ();
}
/// <summary>
/// Center as much as possible in one or both axis. Centering is
/// defined as follows: if the image is scaled down below the
/// view's dimensions then center it (literally). If the image
/// is scaled larger than the view and is translated out of view
/// then translate it back into view (i.e. eliminate black bars).
/// </summary>
protected void Center (bool horizontal, bool vertical)
{
if (bitmapDisplayed.Bitmap == null)
{
return;
}
var rect = new RectF (0, 0, bitmapDisplayed.Bitmap.Width, bitmapDisplayed.Bitmap.Height);
Matrix m = GetImageViewMatrix ();
m.MapRect (rect);
float height = rect.Height ();
float width = rect.Width ();
float deltaX = 0, deltaY = 0;
if (vertical)
{
int viewHeight = Height;
if (height < viewHeight)
{
deltaY = (viewHeight - height) / 2 - rect.Top;
}
else if (rect.Top > 0)
{
deltaY = -rect.Top;
}
else if (rect.Bottom < viewHeight)
{
deltaY = Height - rect.Bottom;
}
}
if (horizontal)
{
int viewWidth = Width;
if (width < viewWidth)
{
deltaX = (viewWidth - width) / 2 - rect.Left;
}
else if (rect.Left > 0)
{
deltaX = -rect.Left;
}
else if (rect.Right < viewWidth)
{
deltaX = viewWidth - rect.Right;
}
}
PostTranslate (deltaX, deltaY);
ImageMatrix = GetImageViewMatrix ();
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Sogeti.Capstone.Api.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: StreamWriter
**
** <OWNER>gpaperin</OWNER>
**
**
** Purpose: For writing text to streams in a particular
** encoding.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
#if FEATURE_ASYNC_IO
using System.Threading.Tasks;
#endif
namespace System.IO
{
// This class implements a TextWriter for writing characters to a Stream.
// This is designed for character output in a particular Encoding,
// whereas the Stream class is designed for byte input and output.
//
[Serializable]
[ComVisible(true)]
public class StreamWriter : TextWriter
{
// For UTF-8, the values of 1K for the default buffer size and 4K for the
// file stream buffer size are reasonable & give very reasonable
// performance for in terms of construction time for the StreamWriter and
// write perf. Note that for UTF-8, we end up allocating a 4K byte buffer,
// which means we take advantage of adaptive buffering code.
// The performance using UnicodeEncoding is acceptable.
internal const int DefaultBufferSize = 1024; // char[]
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
#if FEATURE_ASYNC_IO
private const Int32 DontCopyOnWriteLineThreshold = 512;
#endif
// Bit bucket - Null has no backing store. Non closable.
public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true);
private Stream stream;
private Encoding encoding;
private Encoder encoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int charPos;
private int charLen;
private bool autoFlush;
private bool haveWrittenPreamble;
private bool closable;
#if MDA_SUPPORTED
[NonSerialized]
// For StreamWriterBufferedDataLost MDA
private MdaHelper mdaHelper;
#endif
#if FEATURE_ASYNC_IO
// We don't guarantee thread safety on StreamWriter, but we should at
// least prevent users from trying to write anything while an Async
// write from the same thread is in progress.
[NonSerialized]
private volatile Task _asyncWriteTask;
private void CheckAsyncTaskInProgress()
{
// We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety.
// We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress.
Task t = _asyncWriteTask;
if (t != null && !t.IsCompleted)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
}
#endif
// The high level goal is to be tolerant of encoding errors when we read and very strict
// when we write. Hence, default StreamWriter encoding will throw on encoding error.
// Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character
// D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the
// internal StreamWriter's state to be irrecoverable as it would have buffered the
// illegal chars and any subsequent call to Flush() would hit the encoding error again.
// Even Close() will hit the exception as it would try to flush the unwritten data.
// Maybe we can add a DiscardBufferedData() method to get out of such situation (like
// StreamReader though for different reason). Either way, the buffered data will be lost!
private static volatile Encoding _UTF8NoBOM;
internal static Encoding UTF8NoBOM {
[FriendAccessAllowed]
get {
if (_UTF8NoBOM == null) {
// No need for double lock - we just want to avoid extra
// allocations in the common case.
UTF8Encoding noBOM = new UTF8Encoding(false, true);
Thread.MemoryBarrier();
_UTF8NoBOM = noBOM;
}
return _UTF8NoBOM;
}
}
internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time
}
public StreamWriter(Stream stream)
: this(stream, UTF8NoBOM, DefaultBufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding)
: this(stream, encoding, DefaultBufferSize, false) {
}
// Creates a new StreamWriter for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
//
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
: this(stream, encoding, bufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
: base(null) // Ask for CurrentCulture all the time
{
if (stream == null || encoding == null)
throw new ArgumentNullException((stream == null ? "stream" : "encoding"));
if (!stream.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Init(stream, encoding, bufferSize, leaveOpen);
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path)
: this(path, false, UTF8NoBOM, DefaultBufferSize) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path, bool append)
: this(path, append, UTF8NoBOM, DefaultBufferSize) {
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path, bool append, Encoding encoding)
: this(path, append, encoding, DefaultBufferSize) {
}
[System.Security.SecuritySafeCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) {
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost)
: base(null)
{ // Ask for CurrentCulture all the time
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Stream stream = CreateFile(path, append, checkHost);
Init(stream, encoding, bufferSize, false);
}
[System.Security.SecuritySafeCritical]
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
this.stream = streamArg;
this.encoding = encodingArg;
this.encoder = encoding.GetEncoder();
if (bufferSize < MinBufferSize) bufferSize = MinBufferSize;
charBuffer = new char[bufferSize];
byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)];
charLen = bufferSize;
// If we're appending to a Stream that already has data, don't write
// the preamble.
if (stream.CanSeek && stream.Position > 0)
haveWrittenPreamble = true;
closable = !shouldLeaveOpen;
#if MDA_SUPPORTED
if (Mda.StreamWriterBufferedDataLost.Enabled) {
String callstack = null;
if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
callstack = Environment.GetStackTrace(null, false);
mdaHelper = new MdaHelper(this, callstack);
}
#endif
}
[System.Security.SecurityCritical]
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private static Stream CreateFile(String path, bool append, bool checkHost) {
FileMode mode = append? FileMode.Append: FileMode.Create;
FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
return f;
}
public override void Close() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing) {
try {
// We need to flush any buffered data if we are being closed/disposed.
// Also, we never close the handles for stdout & friends. So we can safely
// write any buffered data to those streams even during finalization, which
// is generally the right thing to do.
if (stream != null) {
// Note: flush on the underlying stream can throw (ex., low disk space)
if (disposing || (LeaveOpen && stream is __ConsoleStream))
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
Flush(true, true);
#if MDA_SUPPORTED
// Disable buffered data loss mda
if (mdaHelper != null)
GC.SuppressFinalize(mdaHelper);
#endif
}
}
}
finally {
// Dispose of our resources if this StreamWriter is closable.
// Note: Console.Out and other such non closable streamwriters should be left alone
if (!LeaveOpen && stream != null) {
try {
// Attempt to close the stream even if there was an IO error from Flushing.
// Note that Stream.Close() can potentially throw here (may or may not be
// due to the same Flush error). In this case, we still need to ensure
// cleaning up internal resources, hence the finally block.
if (disposing)
stream.Close();
}
finally {
stream = null;
byteBuffer = null;
charBuffer = null;
encoding = null;
encoder = null;
charLen = 0;
base.Dispose(disposing);
}
}
}
}
public override void Flush()
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
Flush(true, true);
}
private void Flush(bool flushStream, bool flushEncoder)
{
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
// Perf boost for Flush on non-dirty writers.
if (charPos==0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8))
return;
if (!haveWrittenPreamble) {
haveWrittenPreamble = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
stream.Write(preamble, 0, preamble.Length);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
charPos = 0;
if (count > 0)
stream.Write(byteBuffer, 0, count);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
stream.Flush();
}
public virtual bool AutoFlush {
get { return autoFlush; }
set
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
autoFlush = value;
if (value) Flush(true, false);
}
}
public virtual Stream BaseStream {
get { return stream; }
}
internal bool LeaveOpen {
get { return !closable; }
}
internal bool HaveWrittenPreamble {
set { haveWrittenPreamble= value; }
}
public override Encoding Encoding {
get { return encoding; }
}
public override void Write(char value)
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
if (charPos == charLen) Flush(false, false);
charBuffer[charPos] = value;
charPos++;
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer)
{
// This may be faster than the one with the index & count since it
// has to do less argument checking.
if (buffer==null)
return;
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
int index = 0;
int count = buffer.Length;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a ---- in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(String value)
{
if (value != null)
{
#if FEATURE_ASYNC_IO
CheckAsyncTaskInProgress();
#endif
int count = value.Length;
int index = 0;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
}
#if FEATURE_ASYNC_IO
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = value;
charPos++;
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (value != null)
{
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
else
{
return Task.CompletedTask;
}
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, String value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(value != null);
int count = value.Length;
int index = 0;
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(count == 0 || (count > 0 && buffer != null));
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count));
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync();
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task FlushAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overriden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.FlushAsync();
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = FlushAsyncInternal(true, true, charBuffer, charPos);
_asyncWriteTask = task;
return task;
}
private Int32 CharPos_Prop {
set { this.charPos = value; }
}
private bool HaveWrittenPreamble_Prop {
set { this.haveWrittenPreamble = value; }
}
private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
Char[] sCharBuffer, Int32 sCharPos) {
// Perf boost for Flush on non-dirty writers.
if (sCharPos == 0 && !flushStream && !flushEncoder)
return Task.CompletedTask;
Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble,
this.encoding, this.encoder, this.byteBuffer, this.stream);
this.charPos = 0;
return flushTask;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble,
Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
{
if (!haveWrittenPreamble)
{
_this.HaveWrittenPreamble_Prop = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
if (count > 0)
await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
await stream.FlushAsync().ConfigureAwait(false);
}
#endregion
#endif //FEATURE_ASYNC_IO
#if MDA_SUPPORTED
// StreamWriterBufferedDataLost MDA
// Instead of adding a finalizer to StreamWriter for detecting buffered data loss
// (ie, when the user forgets to call Close/Flush on the StreamWriter), we will
// have a separate object with normal finalization semantics that maintains a
// back pointer to this StreamWriter and alerts about any data loss
private sealed class MdaHelper
{
private StreamWriter streamWriter;
private String allocatedCallstack; // captures the callstack when this streamwriter was allocated
internal MdaHelper(StreamWriter sw, String cs)
{
streamWriter = sw;
allocatedCallstack = cs;
}
// Finalizer
~MdaHelper()
{
// Make sure people closed this StreamWriter, exclude StreamWriter::Null.
if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) {
String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>";
String callStack = allocatedCallstack;
if (callStack == null)
callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack);
Mda.StreamWriterBufferedDataLost.ReportError(message);
}
}
} // class MdaHelper
#endif // MDA_SUPPORTED
} // class StreamWriter
} // namespace
| |
// This file is part of the C5 Generic Collection Library for C# and CLI
// See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details.
using NUnit.Framework;
using System;
using System.Linq;
using SCG = System.Collections.Generic;
namespace C5.Tests.hashtable.dictionary
{
using DictionaryIntToInt = HashDictionary<int, int>;
[TestFixture]
public class GenericTesters
{
[Test]
public void TestEvents()
{
DictionaryIntToInt factory() { return new DictionaryIntToInt(TenEqualityComparer.Default); }
new C5.Tests.Templates.Events.DictionaryTester<DictionaryIntToInt>().Test(factory);
}
}
internal static class Factory
{
public static IDictionary<K, V> New<K, V>() { return new HashDictionary<K, V>(); }
}
[TestFixture]
public class Formatting
{
private IDictionary<int, int> coll;
private IFormatProvider rad16;
[SetUp]
public void Init()
{
Debug.UseDeterministicHashing = true;
coll = Factory.New<int, int>();
rad16 = new RadixFormatProvider(16);
}
[TearDown]
public void Dispose()
{
Debug.UseDeterministicHashing = false;
coll = null;
rad16 = null;
}
[Test]
public void Format()
{
Assert.AreEqual("{ }", coll.ToString());
coll.Add(23, 67); coll.Add(45, 89);
Assert.AreEqual("{ [45, 89], [23, 67] }", coll.ToString());
Assert.AreEqual("{ [2D, 59], [17, 43] }", coll.ToString(null, rad16));
Assert.AreEqual("{ [45, 89], ... }", coll.ToString("L14", null));
Assert.AreEqual("{ [2D, 59], ... }", coll.ToString("L14", rad16));
}
}
[TestFixture]
public class HashDict
{
private HashDictionary<string, string> dict;
[SetUp]
public void Init()
{
dict = new HashDictionary<string, string>();
//dict = TreeDictionary<string,string>.MakeNaturalO<string,string>();
}
[Test]
public void NullEqualityComparerinConstructor1()
{
Assert.Throws<NullReferenceException>(() => new HashDictionary<int, int>(null));
}
[Test]
public void NullEqualityComparerinConstructor2()
{
Assert.Throws<NullReferenceException>(() => new HashDictionary<int, int>(5, 0.5, null));
}
[Test]
public void Choose()
{
dict.Add("ER", "FOO");
Assert.AreEqual(new System.Collections.Generic.KeyValuePair<string, string>("ER", "FOO"), dict.Choose());
}
[Test]
public void BadChoose()
{
Assert.Throws<NoSuchItemException>(() => dict.Choose());
}
[TearDown]
public void Dispose()
{
dict = null;
}
[Test]
public void Initial()
{
bool res;
Assert.IsFalse(dict.IsReadOnly);
Assert.AreEqual(0, dict.Count, "new dict should be empty");
dict.Add("A", "B");
Assert.AreEqual(1, dict.Count, "bad count");
Assert.AreEqual("B", dict["A"], "Wrong value for dict[A]");
dict.Add("C", "D");
Assert.AreEqual(2, dict.Count, "bad count");
Assert.AreEqual("B", dict["A"], "Wrong value");
Assert.AreEqual("D", dict["C"], "Wrong value");
res = dict.Remove("A");
Assert.IsTrue(res, "bad return value from Remove(A)");
Assert.AreEqual(1, dict.Count, "bad count");
Assert.AreEqual("D", dict["C"], "Wrong value of dict[C]");
res = dict.Remove("Z");
Assert.IsFalse(res, "bad return value from Remove(Z)");
Assert.AreEqual(1, dict.Count, "bad count");
Assert.AreEqual("D", dict["C"], "Wrong value of dict[C] (2)");
}
[Test]
public void Contains()
{
dict.Add("C", "D");
Assert.IsTrue(dict.Contains("C"));
Assert.IsFalse(dict.Contains("D"));
}
[Test]
public void IllegalAdd()
{
dict.Add("A", "B");
var exception = Assert.Throws<DuplicateNotAllowedException>(() => dict.Add("A", "B"));
Assert.AreEqual("Key being added: 'A'", exception.Message);
}
[Test]
public void GettingNonExisting()
{
Assert.Throws<NoSuchItemException>(() => Console.WriteLine(dict["R"]));
}
[Test]
public void Setter()
{
dict["R"] = "UYGUY";
Assert.AreEqual("UYGUY", dict["R"]);
dict["R"] = "UIII";
Assert.AreEqual("UIII", dict["R"]);
dict["S"] = "VVV";
Assert.AreEqual("UIII", dict["R"]);
Assert.AreEqual("VVV", dict["S"]);
//dict.dump();
}
[Test]
public void CombinedOps()
{
dict["R"] = "UIII";
dict["S"] = "VVV";
dict["T"] = "XYZ";
Assert.IsTrue(dict.Remove("S", out string s));
Assert.AreEqual("VVV", s);
Assert.IsFalse(dict.Contains("S"));
Assert.IsFalse(dict.Remove("A", out _));
//
string t = "T", a = "A";
Assert.IsTrue(dict.Find(ref t, out s));
Assert.AreEqual("XYZ", s);
Assert.IsFalse(dict.Find(ref a, out _));
//
Assert.IsTrue(dict.Update("R", "UHU"));
Assert.AreEqual("UHU", dict["R"]);
Assert.IsFalse(dict.Update("A", "W"));
Assert.IsFalse(dict.Contains("A"));
//
s = "KKK";
Assert.IsFalse(dict.FindOrAdd("B", ref s));
Assert.AreEqual("KKK", dict["B"]);
Assert.IsTrue(dict.FindOrAdd("T", ref s));
Assert.AreEqual("XYZ", s);
//
s = "LLL";
Assert.IsTrue(dict.UpdateOrAdd("R", s));
Assert.AreEqual("LLL", dict["R"]);
s = "MMM";
Assert.IsFalse(dict.UpdateOrAdd("C", s));
Assert.AreEqual("MMM", dict["C"]);
// bug20071112 fixed 2008-02-03
s = "NNN";
Assert.IsTrue(dict.UpdateOrAdd("R", s, out string old));
Assert.AreEqual("NNN", dict["R"]);
Assert.AreEqual("LLL", old);
s = "OOO";
Assert.IsFalse(dict.UpdateOrAdd("D", s, out _));
Assert.AreEqual("OOO", dict["D"]);
// Unclear which of these is correct:
// Assert.AreEqual(null, old);
// Assert.AreEqual("OOO", old);
}
[Test]
public void DeepBucket()
{
HashDictionary<int, int> dict2 = new HashDictionary<int, int>();
for (int i = 0; i < 5; i++)
{
dict2[16 * i] = 5 * i;
}
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(5 * i, dict2[16 * i]);
}
for (int i = 0; i < 5; i++)
{
dict2[16 * i] = 7 * i + 1;
}
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(7 * i + 1, dict2[16 * i]);
}
Assert.IsTrue(dict.Check());
}
}
[TestFixture]
public class Enumerators
{
private HashDictionary<string, string> _dict;
[SetUp]
public void Init()
{
_dict = new HashDictionary<string, string>
{
["S"] = "A",
["T"] = "B",
["R"] = "C"
};
}
[TearDown]
public void Dispose()
{
_dict = null;
}
[Test]
public void Keys()
{
var keys = _dict.Keys.ToArray();
Assert.AreEqual(3, keys.Length);
Assert.IsTrue(keys.Contains("R"));
Assert.IsTrue(keys.Contains("S"));
Assert.IsTrue(keys.Contains("T"));
}
[Test]
public void Values()
{
var values = _dict.Values.ToArray();
Assert.AreEqual(3, values.Length);
Assert.IsTrue(values.Contains("A"));
Assert.IsTrue(values.Contains("B"));
Assert.IsTrue(values.Contains("C"));
}
[Test]
public void Fun()
{
Assert.AreEqual("B", _dict.Func("T"));
}
[Test]
public void NormalUse()
{
var pairs = _dict.ToDictionary(pair => pair.Key, pair => pair.Value);
Assert.AreEqual(3, pairs.Count);
Assert.IsTrue(pairs.Contains(new SCG.KeyValuePair<string, string>("R", "C")));
Assert.IsTrue(pairs.Contains(new SCG.KeyValuePair<string, string>("S", "A")));
Assert.IsTrue(pairs.Contains(new SCG.KeyValuePair<string, string>("T", "B")));
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
#pragma warning disable 1591
namespace WebsitePanel.LocalizationToolkit {
/// <summary>
///Represents a strongly typed in-memory cache of data.
///</summary>
[global::System.Serializable()]
[global::System.ComponentModel.DesignerCategoryAttribute("code")]
[global::System.ComponentModel.ToolboxItem(true)]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedDataSetSchema")]
[global::System.Xml.Serialization.XmlRootAttribute("Resources")]
[global::System.ComponentModel.Design.HelpKeywordAttribute("vs.data.DataSet")]
public partial class Resources : global::System.Data.DataSet {
private ResourceDataTable tableResource;
private global::System.Data.SchemaSerializationMode _schemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public Resources() {
this.BeginInit();
this.InitClass();
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
base.Relations.CollectionChanged += schemaChangedHandler;
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected Resources(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context, false) {
if ((this.IsBinarySerialized(info, context) == true)) {
this.InitVars(false);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler1 = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
this.Tables.CollectionChanged += schemaChangedHandler1;
this.Relations.CollectionChanged += schemaChangedHandler1;
return;
}
string strSchema = ((string)(info.GetValue("XmlSchema", typeof(string))));
if ((this.DetermineSchemaSerializationMode(info, context) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
if ((ds.Tables["Resource"] != null)) {
base.Tables.Add(new ResourceDataTable(ds.Tables["Resource"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXmlSchema(new global::System.Xml.XmlTextReader(new global::System.IO.StringReader(strSchema)));
}
this.GetSerializationData(info, context);
global::System.ComponentModel.CollectionChangeEventHandler schemaChangedHandler = new global::System.ComponentModel.CollectionChangeEventHandler(this.SchemaChanged);
base.Tables.CollectionChanged += schemaChangedHandler;
this.Relations.CollectionChanged += schemaChangedHandler;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
[global::System.ComponentModel.DesignerSerializationVisibility(global::System.ComponentModel.DesignerSerializationVisibility.Content)]
public ResourceDataTable Resource {
get {
return this.tableResource;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.BrowsableAttribute(true)]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Visible)]
public override global::System.Data.SchemaSerializationMode SchemaSerializationMode {
get {
return this._schemaSerializationMode;
}
set {
this._schemaSerializationMode = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataTableCollection Tables {
get {
return base.Tables;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.DesignerSerializationVisibilityAttribute(global::System.ComponentModel.DesignerSerializationVisibility.Hidden)]
public new global::System.Data.DataRelationCollection Relations {
get {
return base.Relations;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void InitializeDerivedDataSet() {
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public override global::System.Data.DataSet Clone() {
Resources cln = ((Resources)(base.Clone()));
cln.InitVars();
cln.SchemaSerializationMode = this.SchemaSerializationMode;
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override bool ShouldSerializeTables() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override bool ShouldSerializeRelations() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void ReadXmlSerializable(global::System.Xml.XmlReader reader) {
if ((this.DetermineSchemaSerializationMode(reader) == global::System.Data.SchemaSerializationMode.IncludeSchema)) {
this.Reset();
global::System.Data.DataSet ds = new global::System.Data.DataSet();
ds.ReadXml(reader);
if ((ds.Tables["Resource"] != null)) {
base.Tables.Add(new ResourceDataTable(ds.Tables["Resource"]));
}
this.DataSetName = ds.DataSetName;
this.Prefix = ds.Prefix;
this.Namespace = ds.Namespace;
this.Locale = ds.Locale;
this.CaseSensitive = ds.CaseSensitive;
this.EnforceConstraints = ds.EnforceConstraints;
this.Merge(ds, false, global::System.Data.MissingSchemaAction.Add);
this.InitVars();
}
else {
this.ReadXml(reader);
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Xml.Schema.XmlSchema GetSchemaSerializable() {
global::System.IO.MemoryStream stream = new global::System.IO.MemoryStream();
this.WriteXmlSchema(new global::System.Xml.XmlTextWriter(stream, null));
stream.Position = 0;
return global::System.Xml.Schema.XmlSchema.Read(new global::System.Xml.XmlTextReader(stream), null);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal void InitVars() {
this.InitVars(true);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal void InitVars(bool initTable) {
this.tableResource = ((ResourceDataTable)(base.Tables["Resource"]));
if ((initTable == true)) {
if ((this.tableResource != null)) {
this.tableResource.InitVars();
}
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitClass() {
this.DataSetName = "Resources";
this.Prefix = "";
this.Namespace = "http://tempuri.org/Resources.xsd";
this.Locale = new global::System.Globalization.CultureInfo("en-US");
this.EnforceConstraints = true;
this.SchemaSerializationMode = global::System.Data.SchemaSerializationMode.IncludeSchema;
this.tableResource = new ResourceDataTable();
base.Tables.Add(this.tableResource);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private bool ShouldSerializeResource() {
return false;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void SchemaChanged(object sender, global::System.ComponentModel.CollectionChangeEventArgs e) {
if ((e.Action == global::System.ComponentModel.CollectionChangeAction.Remove)) {
this.InitVars();
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
Resources ds = new Resources();
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
any.Namespace = ds.Namespace;
sequence.Items.Add(any);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public delegate void ResourceRowChangeEventHandler(object sender, ResourceRowChangeEvent e);
/// <summary>
///Represents the strongly named DataTable class.
///</summary>
[global::System.Serializable()]
[global::System.Xml.Serialization.XmlSchemaProviderAttribute("GetTypedTableSchema")]
public partial class ResourceDataTable : global::System.Data.DataTable, global::System.Collections.IEnumerable {
private global::System.Data.DataColumn columnFile;
private global::System.Data.DataColumn columnKey;
private global::System.Data.DataColumn columnDefaultValue;
private global::System.Data.DataColumn columnValue;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ResourceDataTable() {
this.TableName = "Resource";
this.BeginInit();
this.InitClass();
this.EndInit();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal ResourceDataTable(global::System.Data.DataTable table) {
this.TableName = table.TableName;
if ((table.CaseSensitive != table.DataSet.CaseSensitive)) {
this.CaseSensitive = table.CaseSensitive;
}
if ((table.Locale.ToString() != table.DataSet.Locale.ToString())) {
this.Locale = table.Locale;
}
if ((table.Namespace != table.DataSet.Namespace)) {
this.Namespace = table.Namespace;
}
this.Prefix = table.Prefix;
this.MinimumCapacity = table.MinimumCapacity;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected ResourceDataTable(global::System.Runtime.Serialization.SerializationInfo info, global::System.Runtime.Serialization.StreamingContext context) :
base(info, context) {
this.InitVars();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn FileColumn {
get {
return this.columnFile;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn KeyColumn {
get {
return this.columnKey;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn DefaultValueColumn {
get {
return this.columnDefaultValue;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataColumn ValueColumn {
get {
return this.columnValue;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
[global::System.ComponentModel.Browsable(false)]
public int Count {
get {
return this.Rows.Count;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ResourceRow this[int index] {
get {
return ((ResourceRow)(this.Rows[index]));
}
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ResourceRowChangeEventHandler ResourceRowChanging;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ResourceRowChangeEventHandler ResourceRowChanged;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ResourceRowChangeEventHandler ResourceRowDeleting;
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public event ResourceRowChangeEventHandler ResourceRowDeleted;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void AddResourceRow(ResourceRow row) {
this.Rows.Add(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ResourceRow AddResourceRow(string File, string Key, string DefaultValue, string Value) {
ResourceRow rowResourceRow = ((ResourceRow)(this.NewRow()));
object[] columnValuesArray = new object[] {
File,
Key,
DefaultValue,
Value};
rowResourceRow.ItemArray = columnValuesArray;
this.Rows.Add(rowResourceRow);
return rowResourceRow;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public virtual global::System.Collections.IEnumerator GetEnumerator() {
return this.Rows.GetEnumerator();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public override global::System.Data.DataTable Clone() {
ResourceDataTable cln = ((ResourceDataTable)(base.Clone()));
cln.InitVars();
return cln;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Data.DataTable CreateInstance() {
return new ResourceDataTable();
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal void InitVars() {
this.columnFile = base.Columns["File"];
this.columnKey = base.Columns["Key"];
this.columnDefaultValue = base.Columns["DefaultValue"];
this.columnValue = base.Columns["Value"];
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
private void InitClass() {
this.columnFile = new global::System.Data.DataColumn("File", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnFile);
this.columnKey = new global::System.Data.DataColumn("Key", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnKey);
this.columnDefaultValue = new global::System.Data.DataColumn("DefaultValue", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnDefaultValue);
this.columnValue = new global::System.Data.DataColumn("Value", typeof(string), null, global::System.Data.MappingType.Element);
base.Columns.Add(this.columnValue);
this.Locale = new global::System.Globalization.CultureInfo("en-US");
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ResourceRow NewResourceRow() {
return ((ResourceRow)(this.NewRow()));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Data.DataRow NewRowFromBuilder(global::System.Data.DataRowBuilder builder) {
return new ResourceRow(builder);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override global::System.Type GetRowType() {
return typeof(ResourceRow);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowChanged(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanged(e);
if ((this.ResourceRowChanged != null)) {
this.ResourceRowChanged(this, new ResourceRowChangeEvent(((ResourceRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowChanging(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowChanging(e);
if ((this.ResourceRowChanging != null)) {
this.ResourceRowChanging(this, new ResourceRowChangeEvent(((ResourceRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowDeleted(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleted(e);
if ((this.ResourceRowDeleted != null)) {
this.ResourceRowDeleted(this, new ResourceRowChangeEvent(((ResourceRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
protected override void OnRowDeleting(global::System.Data.DataRowChangeEventArgs e) {
base.OnRowDeleting(e);
if ((this.ResourceRowDeleting != null)) {
this.ResourceRowDeleting(this, new ResourceRowChangeEvent(((ResourceRow)(e.Row)), e.Action));
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void RemoveResourceRow(ResourceRow row) {
this.Rows.Remove(row);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
Resources ds = new Resources();
global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
any1.Namespace = "http://www.w3.org/2001/XMLSchema";
any1.MinOccurs = new decimal(0);
any1.MaxOccurs = decimal.MaxValue;
any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any1);
global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
any2.MinOccurs = new decimal(1);
any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
sequence.Items.Add(any2);
global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute1.Name = "namespace";
attribute1.FixedValue = ds.Namespace;
type.Attributes.Add(attribute1);
global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
attribute2.Name = "tableTypeName";
attribute2.FixedValue = "ResourceDataTable";
type.Attributes.Add(attribute2);
type.Particle = sequence;
global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
if (xs.Contains(dsSchema.TargetNamespace)) {
global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
try {
global::System.Xml.Schema.XmlSchema schema = null;
dsSchema.Write(s1);
for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
s2.SetLength(0);
schema.Write(s2);
if ((s1.Length == s2.Length)) {
s1.Position = 0;
s2.Position = 0;
for (; ((s1.Position != s1.Length)
&& (s1.ReadByte() == s2.ReadByte())); ) {
;
}
if ((s1.Position == s1.Length)) {
return type;
}
}
}
}
finally {
if ((s1 != null)) {
s1.Close();
}
if ((s2 != null)) {
s2.Close();
}
}
}
xs.Add(dsSchema);
return type;
}
}
/// <summary>
///Represents strongly named DataRow class.
///</summary>
public partial class ResourceRow : global::System.Data.DataRow {
private ResourceDataTable tableResource;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
internal ResourceRow(global::System.Data.DataRowBuilder rb) :
base(rb) {
this.tableResource = ((ResourceDataTable)(this.Table));
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public string File {
get {
try {
return ((string)(this[this.tableResource.FileColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'File\' in table \'Resource\' is DBNull.", e);
}
}
set {
this[this.tableResource.FileColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public string Key {
get {
try {
return ((string)(this[this.tableResource.KeyColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'Key\' in table \'Resource\' is DBNull.", e);
}
}
set {
this[this.tableResource.KeyColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public string DefaultValue {
get {
try {
return ((string)(this[this.tableResource.DefaultValueColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'DefaultValue\' in table \'Resource\' is DBNull.", e);
}
}
set {
this[this.tableResource.DefaultValueColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public string Value {
get {
try {
return ((string)(this[this.tableResource.ValueColumn]));
}
catch (global::System.InvalidCastException e) {
throw new global::System.Data.StrongTypingException("The value for column \'Value\' in table \'Resource\' is DBNull.", e);
}
}
set {
this[this.tableResource.ValueColumn] = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsFileNull() {
return this.IsNull(this.tableResource.FileColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetFileNull() {
this[this.tableResource.FileColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsKeyNull() {
return this.IsNull(this.tableResource.KeyColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetKeyNull() {
this[this.tableResource.KeyColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsDefaultValueNull() {
return this.IsNull(this.tableResource.DefaultValueColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetDefaultValueNull() {
this[this.tableResource.DefaultValueColumn] = global::System.Convert.DBNull;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public bool IsValueNull() {
return this.IsNull(this.tableResource.ValueColumn);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public void SetValueNull() {
this[this.tableResource.ValueColumn] = global::System.Convert.DBNull;
}
}
/// <summary>
///Row event argument class
///</summary>
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public class ResourceRowChangeEvent : global::System.EventArgs {
private ResourceRow eventRow;
private global::System.Data.DataRowAction eventAction;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ResourceRowChangeEvent(ResourceRow row, global::System.Data.DataRowAction action) {
this.eventRow = row;
this.eventAction = action;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public ResourceRow Row {
get {
return this.eventRow;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Design.TypedDataSetGenerator", "4.0.0.0")]
public global::System.Data.DataRowAction Action {
get {
return this.eventAction;
}
}
}
}
}
#pragma warning restore 1591
| |
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Graph.RBAC
{
using Microsoft.Azure;
using Microsoft.Azure.Graph;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// ServicePrincipalsOperations operations.
/// </summary>
public partial interface IServicePrincipalsOperations
{
/// <summary>
/// Creates a service principal in the directory.
/// </summary>
/// <param name='parameters'>
/// Parameters to create a service principal.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ServicePrincipal>> CreateWithHttpMessagesAsync(ServicePrincipalCreateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of service principals from the current tenant.
/// </summary>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ServicePrincipal>>> ListWithHttpMessagesAsync(ODataQuery<ServicePrincipal> odataQuery = default(ODataQuery<ServicePrincipal>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a service principal from the directory.
/// </summary>
/// <param name='objectId'>
/// The object ID of the service principal to delete.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string objectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets service principal information from the directory.
/// </summary>
/// <param name='objectId'>
/// The object ID of the service principal to get.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ServicePrincipal>> GetWithHttpMessagesAsync(string objectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the keyCredentials associated with the specified service
/// principal.
/// </summary>
/// <param name='objectId'>
/// The object ID of the service principal for which to get
/// keyCredentials.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<KeyCredential>>> ListKeyCredentialsWithHttpMessagesAsync(string objectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update the keyCredentials associated with a service principal.
/// </summary>
/// <param name='objectId'>
/// The object ID for which to get service principal information.
/// </param>
/// <param name='parameters'>
/// Parameters to update the keyCredentials of an existing service
/// principal.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdateKeyCredentialsWithHttpMessagesAsync(string objectId, KeyCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the passwordCredentials associated with a service principal.
/// </summary>
/// <param name='objectId'>
/// The object ID of the service principal.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IEnumerable<PasswordCredential>>> ListPasswordCredentialsWithHttpMessagesAsync(string objectId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates the passwordCredentials associated with a service
/// principal.
/// </summary>
/// <param name='objectId'>
/// The object ID of the service principal.
/// </param>
/// <param name='parameters'>
/// Parameters to update the passwordCredentials of an existing service
/// principal.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdatePasswordCredentialsWithHttpMessagesAsync(string objectId, PasswordCredentialsUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets a list of service principals from the current tenant.
/// </summary>
/// <param name='nextLink'>
/// Next link for the list operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="GraphErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<ServicePrincipal>>> ListNextWithHttpMessagesAsync(string nextLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015 FUJIWARA, Yusuke
//
// 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 -- License Terms --
#if UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
#if !CORLIB_ONLY
using System.ComponentModel;
#endif // !CORLIB_ONLY
using System.Diagnostics;
using System.Linq;
namespace MsgPack.Serialization
{
/// <summary>
/// <para>
/// <strong>This is intened to MsgPack for CLI internal use. Do not use this type from application directly.</strong>
/// </para>
/// <para>
/// A provider parameter to support polymorphism.
/// </para>
/// </summary>
#if !CORLIB_ONLY
[EditorBrowsable( EditorBrowsableState.Never )]
#endif // !CORLIB_ONLY
[DebuggerDisplay("{DebugString}")]
public sealed partial class PolymorphismSchema
{
/// <summary>
/// Gets the type of the serialization target.
/// </summary>
/// <value>
/// The type of the serialization target. This value can be <c>null</c>.
/// </value>
internal Type TargetType { get; private set; }
/// <summary>
/// Gets the type of the polymorphism.
/// </summary>
/// <value>
/// The type of the polymorphism.
/// </value>
internal PolymorphismType PolymorphismType { get; private set; }
private readonly ReadOnlyDictionary<byte, Type> _codeTypeMapping;
/// <summary>
/// Gets the code type mapping which maps between ext-type codes and .NET <see cref="Type"/>s.
/// </summary>
/// <value>
/// The code type mapping which maps between ext-type codes and .NET <see cref="Type"/>s.
/// </value>
internal IDictionary<byte, Type> CodeTypeMapping { get { return this._codeTypeMapping; } }
internal bool UseDefault { get { return this.PolymorphismType == PolymorphismType.None; } }
internal bool UseTypeEmbedding { get { return this.PolymorphismType == PolymorphismType.RuntimeType; } }
internal PolymorphismSchemaChildrenType ChildrenType { get; private set; }
private readonly ReadOnlyCollection<PolymorphismSchema> _children;
/// <summary>
/// Gets the schema for child items of the serialization target collection/tuple.
/// </summary>
/// <value>
/// The schema for child items of the serialization target collection/tuple.
/// </value>
internal IList<PolymorphismSchema> ChildSchemaList
{
get { return this._children; }
}
/// <summary>
/// Gets the schema for collection items of the serialization target collection.
/// </summary>
/// <value>
/// The schema for collection items of the serialization target collection.
/// </value>
internal PolymorphismSchema ItemSchema
{
get
{
switch ( this.ChildrenType )
{
case PolymorphismSchemaChildrenType.None:
{
return null;
}
case PolymorphismSchemaChildrenType.CollectionItems:
{
return this._children.FirstOrDefault();
}
case PolymorphismSchemaChildrenType.DictionaryKeyValues:
{
return this._children.Skip( 1 ).FirstOrDefault();
}
default:
{
throw new NotSupportedException();
}
}
}
}
/// <summary>
/// Gets the schema for dictionary keys of the serialization target collection.
/// </summary>
/// <value>
/// The schema for collection items of the serialization target collection.
/// </value>
internal PolymorphismSchema KeySchema
{
get
{
switch ( this.ChildrenType )
{
case PolymorphismSchemaChildrenType.None:
{
return null;
}
case PolymorphismSchemaChildrenType.DictionaryKeyValues:
{
return this._children.FirstOrDefault();
}
default:
{
throw new NotSupportedException();
}
}
}
}
#if NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY
private sealed class ReadOnlyDictionary<TKey, TValue> : IDictionary<TKey, TValue>
{
private readonly IDictionary<TKey, TValue> _underlying;
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return this._underlying.Keys; }
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return this._underlying.Values; }
}
TValue IDictionary<TKey, TValue>.this[ TKey key ]
{
get { return this._underlying[ key ]; }
set
{
throw new NotSupportedException();
}
}
int ICollection<KeyValuePair<TKey, TValue>>.Count
{
get { return this._underlying.Count; }
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return true; }
}
public ReadOnlyDictionary( IDictionary<TKey, TValue> underlying )
{
this._underlying = underlying;
}
bool IDictionary<TKey, TValue>.ContainsKey( TKey key )
{
return this._underlying.ContainsKey( key );
}
bool IDictionary<TKey, TValue>.TryGetValue( TKey key, out TValue value )
{
return this._underlying.TryGetValue( key, out value );
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains( KeyValuePair<TKey, TValue> item )
{
return this._underlying.Contains( item );
}
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo( KeyValuePair<TKey, TValue>[] array, int arrayIndex )
{
this._underlying.CopyTo( array, arrayIndex );
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this._underlying.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this._underlying.GetEnumerator();
}
void IDictionary<TKey, TValue>.Add( TKey key, TValue value )
{
throw new NotSupportedException();
}
bool IDictionary<TKey, TValue>.Remove( TKey key )
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.Add( KeyValuePair<TKey, TValue> item )
{
throw new NotSupportedException();
}
void ICollection<KeyValuePair<TKey, TValue>>.Clear()
{
throw new NotSupportedException();
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove( KeyValuePair<TKey, TValue> item )
{
throw new NotSupportedException();
}
}
#endif // NETFX_35 || NETFX_40 || SILVERLIGHT || UNITY
}
}
| |
using System;
using MyGeneration.dOOdads;
namespace MyGeneration.dOOdads.Tests.Firebird
{
/// <summary>
/// Description of RefreshDatabase.
/// </summary>
public class UnitTestBase
{
static UnitTestBase()
{
}
public static void RefreshDatabase()
{
AggregateTest testData = new AggregateTest();
testData.ConnectionStringConfig = "FirebirdConnection";
testData.LoadAll();
testData.DeleteAll();
testData.Save();
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "David";
testData.s_LastName = "Doe";
testData.s_Age = "16";
testData.s_HireDate = "2000-02-16 00:00:00";
testData.s_Salary = "34.71";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "1";
testData.s_FirstName = "Sarah";
testData.s_LastName = "McDonald";
testData.s_Age = "28";
testData.s_HireDate = "1999-03-25 00:00:00";
testData.s_Salary = "11.06";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "David";
testData.s_LastName = "Vincent";
testData.s_Age = "43";
testData.s_HireDate = "2000-10-17 00:00:00";
testData.s_Salary = "10.27";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "2";
testData.s_FirstName = "Fred";
testData.s_LastName = "Smith";
testData.s_Age = "15";
testData.s_HireDate = "1999-03-15 00:00:00";
testData.s_Salary = "15.15";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "Sally";
testData.s_LastName = "Johnson";
testData.s_Age = "30";
testData.s_HireDate = "2000-10-07 00:00:00";
testData.s_Salary = "14.36";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "5";
testData.s_FirstName = "Jane";
testData.s_LastName = "Rapaport";
testData.s_Age = "44";
testData.s_HireDate = "2002-05-02 00:00:00";
testData.s_Salary = "13.56";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "4";
testData.s_FirstName = "Paul";
testData.s_LastName = "Gellar";
testData.s_Age = "16";
testData.s_HireDate = "2000-09-27 00:00:00";
testData.s_Salary = "18.44";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "2";
testData.s_FirstName = "John";
testData.s_LastName = "Jones";
testData.s_Age = "31";
testData.s_HireDate = "2002-04-22 00:00:00";
testData.s_Salary = "17.65";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "Michelle";
testData.s_LastName = "Johnson";
testData.s_Age = "45";
testData.s_HireDate = "2003-11-14 00:00:00";
testData.s_Salary = "16.86";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "2";
testData.s_FirstName = "David";
testData.s_LastName = "Costner";
testData.s_Age = "17";
testData.s_HireDate = "2002-04-11 00:00:00";
testData.s_Salary = "21.74";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "4";
testData.s_FirstName = "William";
testData.s_LastName = "Gellar";
testData.s_Age = "32";
testData.s_HireDate = "2003-11-04 00:00:00";
testData.s_Salary = "20.94";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "Sally";
testData.s_LastName = "Rapaport";
testData.s_Age = "39";
testData.s_HireDate = "2002-04-01 00:00:00";
testData.s_Salary = "25.82";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "5";
testData.s_FirstName = "Jane";
testData.s_LastName = "Vincent";
testData.s_Age = "18";
testData.s_HireDate = "2003-10-25 00:00:00";
testData.s_Salary = "25.03";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "2";
testData.s_FirstName = "Fred";
testData.s_LastName = "Costner";
testData.s_Age = "33";
testData.s_HireDate = "1998-05-20 00:00:00";
testData.s_Salary = "24.24";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "1";
testData.s_FirstName = "John";
testData.s_LastName = "Johnson";
testData.s_Age = "40";
testData.s_HireDate = "2003-10-15 00:00:00";
testData.s_Salary = "29.12";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "Michelle";
testData.s_LastName = "Rapaport";
testData.s_Age = "19";
testData.s_HireDate = "1998-05-10 00:00:00";
testData.s_Salary = "28.32";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "4";
testData.s_FirstName = "Sarah";
testData.s_LastName = "Doe";
testData.s_Age = "34";
testData.s_HireDate = "1999-12-03 00:00:00";
testData.s_Salary = "27.53";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "4";
testData.s_FirstName = "William";
testData.s_LastName = "Jones";
testData.s_Age = "41";
testData.s_HireDate = "1998-04-30 00:00:00";
testData.s_Salary = "32.41";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "1";
testData.s_FirstName = "Sarah";
testData.s_LastName = "McDonald";
testData.s_Age = "21";
testData.s_HireDate = "1999-11-23 00:00:00";
testData.s_Salary = "31.62";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "4";
testData.s_FirstName = "Jane";
testData.s_LastName = "Costner";
testData.s_Age = "28";
testData.s_HireDate = "1998-04-20 00:00:00";
testData.s_Salary = "36.50";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "2";
testData.s_FirstName = "Fred";
testData.s_LastName = "Douglas";
testData.s_Age = "42";
testData.s_HireDate = "1999-11-13 00:00:00";
testData.s_Salary = "35.71";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "Paul";
testData.s_LastName = "Jones";
testData.s_Age = "22";
testData.s_HireDate = "2001-06-07 00:00:00";
testData.s_Salary = "34.91";
testData.s_IsActive = "0";
testData.AddNew();
testData.s_DepartmentID = "3";
testData.s_FirstName = "Michelle";
testData.s_LastName = "Doe";
testData.s_Age = "29";
testData.s_HireDate = "1999-11-03 00:00:00";
testData.s_Salary = "39.79";
testData.s_IsActive ="1";
testData.AddNew();
testData.s_DepartmentID = "4";
testData.s_FirstName = "Paul";
testData.s_LastName = "Costner";
testData.s_Age = "43";
testData.s_HireDate = "2001-05-28 00:00:00";
testData.s_Salary = "39.00";
testData.s_IsActive ="1";
testData.AddNew();
testData.AddNew();
testData.AddNew();
testData.AddNew();
testData.AddNew();
testData.AddNew();
testData.s_DepartmentID = "0";
testData.s_FirstName = "";
testData.s_LastName = "";
testData.s_Age = "0";
testData.s_Salary = "0";
testData.Save();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001;
using System;
using System.Reflection;
public class MyClass
{
public int Field = 0;
}
public struct MyStruct
{
public int Number;
}
public enum MyEnum
{
First = 1,
Second = 2,
Third = 3
}
public class MemberClass<T>
{
[ThreadStatic]
public static int Status;
public bool? this[string p1, float p2, short[] p3]
{
get
{
MemberClass<T>.Status = 1;
return null;
}
set
{
MemberClass<T>.Status = 2;
}
}
public byte this[dynamic[] p1, ulong[] p2, dynamic p3]
{
get
{
MemberClass<T>.Status = 1;
return (byte)3;
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic this[MyClass p1, char? p2, MyEnum[] p3]
{
get
{
MemberClass<T>.Status = 1;
return p1;
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic[] this[MyClass p1, MyStruct? p2, MyEnum[] p3]
{
get
{
MemberClass<T>.Status = 1;
return new dynamic[]
{
p1, p2
}
;
}
set
{
MemberClass<T>.Status = 2;
}
}
public double[] this[float p1]
{
get
{
MemberClass<T>.Status = 1;
return new double[]
{
1.4, double.Epsilon, double.NaN
}
;
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic this[int?[] p1]
{
get
{
MemberClass<T>.Status = 1;
return p1;
}
set
{
MemberClass<T>.Status = 2;
}
}
public MyClass[] this[MyEnum p1]
{
get
{
MemberClass<T>.Status = 1;
return new MyClass[]
{
null, new MyClass()
{
Field = 3
}
}
;
}
set
{
MemberClass<T>.Status = 2;
}
}
public T this[string p1]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
public MyClass this[string p1, T p2]
{
get
{
MemberClass<T>.Status = 1;
return new MyClass();
}
set
{
MemberClass<T>.Status = 2;
}
}
public dynamic this[T p1]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
public T this[dynamic p1, T p2]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
public T this[T p1, short p2, dynamic p3, string p4]
{
get
{
MemberClass<T>.Status = 1;
return default(T);
}
set
{
MemberClass<T>.Status = 2;
}
}
}
public class MemberClassMultipleParams<T, U, V>
{
public static int Status;
public T this[V v, U u]
{
get
{
MemberClassMultipleParams<T, U, V>.Status = 1;
return default(T);
}
set
{
MemberClassMultipleParams<T, U, V>.Status = 2;
}
}
}
public class MemberClassWithClassConstraint<T>
where T : class
{
[ThreadStatic]
public static int Status;
public int this[int x]
{
get
{
MemberClassWithClassConstraint<T>.Status = 3;
return 1;
}
set
{
MemberClassWithClassConstraint<T>.Status = 4;
}
}
public T this[decimal dec, dynamic d]
{
get
{
MemberClassWithClassConstraint<T>.Status = 1;
return null;
}
set
{
MemberClassWithClassConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithNewConstraint<T>
where T : new()
{
[ThreadStatic]
public static int Status;
public dynamic this[T t]
{
get
{
MemberClassWithNewConstraint<T>.Status = 1;
return new T();
}
set
{
MemberClassWithNewConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithAnotherTypeConstraint<T, U>
where T : U
{
public static int Status;
public U this[dynamic d]
{
get
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 3;
return default(U);
}
set
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 4;
}
}
public dynamic this[int x, U u, dynamic d]
{
get
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 1;
return default(T);
}
set
{
MemberClassWithAnotherTypeConstraint<T, U>.Status = 2;
}
}
}
#region Negative tests - you should not be able to construct this with a dynamic object
public class C
{
}
public interface I
{
}
public class MemberClassWithUDClassConstraint<T>
where T : C, new()
{
public static int Status;
public C this[T t]
{
get
{
MemberClassWithUDClassConstraint<T>.Status = 1;
return new T();
}
set
{
MemberClassWithUDClassConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithStructConstraint<T>
where T : struct
{
public static int Status;
public dynamic this[int x]
{
get
{
MemberClassWithStructConstraint<T>.Status = 1;
return x;
}
set
{
MemberClassWithStructConstraint<T>.Status = 2;
}
}
}
public class MemberClassWithInterfaceConstraint<T>
where T : I
{
public static int Status;
public dynamic this[int x, T v]
{
get
{
MemberClassWithInterfaceConstraint<T>.Status = 1;
return default(T);
}
set
{
MemberClassWithInterfaceConstraint<T>.Status = 2;
}
}
}
#endregion
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001;
// <Title> Tests generic class indexer used in + operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string p1 = null;
int result = dy[string.Empty] + dy[p1] + 1;
if (result == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002;
// <Title> Tests generic class indexer used in implicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(15,20\).*CS0649</Expects>
//<Expects Status=warning>\(29,20\).*CS0649</Expects>
using System;
public class Test
{
public class InnerTest1
{
public int field;
public static implicit operator InnerTest2(InnerTest1 t1)
{
MemberClass<InnerTest1> mc = new MemberClass<InnerTest1>();
dynamic dy = mc;
InnerTest1 p2 = t1;
return dy[dy, p2];
}
}
public class InnerTest2
{
public int field;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
InnerTest1 t1 = new InnerTest1();
InnerTest2 result1 = t1; //implicit
return (result1 == null && MemberClass<InnerTest1>.Status == 1) ? 0 : 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003;
// <Title> Tests generic class indexer used in implicit operator.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
public class InnerTest1
{
public byte field;
public static explicit operator InnerTest1(byte t1)
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
dynamic[] p1 = null;
ulong[] p2 = null;
dynamic p3 = null;
dy[p1, p2, p3] = (byte)10;
return new InnerTest1()
{
field = dy[p1, p2, p3]
}
;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
byte b = 1;
InnerTest1 result = (InnerTest1)b;
if (result.field == 3 && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005;
// <Title> Tests generic class indexer used in using block and using expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.IO;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
var mc = new MemberClass<string>();
dynamic dy = mc;
var mc2 = new MemberClass<bool>();
dynamic dy2 = mc2;
string result = null;
using (MemoryStream sm = new MemoryStream())
{
using (StreamWriter sw = new StreamWriter(sm))
{
sw.Write((string)(dy[string.Empty] ?? "Test"));
sw.Flush();
sm.Position = 0;
using (StreamReader sr = new StreamReader(sm, (bool)dy2[false]))
{
result = sr.ReadToEnd();
}
}
}
if (result == "Test" && MemberClass<string>.Status == 1 && MemberClass<bool>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006;
// <Title> Tests generic class indexer used in the for-condition.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassMultipleParams<int, string, Test> mc = new MemberClassMultipleParams<int, string, Test>();
dynamic dy = mc;
string u = null;
Test v = null;
int index = 10;
for (int i = 10; i > dy[v, u]; i--)
{
index--;
}
//
int ret = M();
if (index == 0 && MemberClassMultipleParams<int, string, Test>.Status == 1)
return ret;
return 1;
}
private static int M()
{
MemberClassWithClassConstraint<Test> mc = new MemberClassWithClassConstraint<Test>();
dynamic dy = mc;
int index = 0;
for (int i = 0; i < 10; i = i + dy[i])
{
dy[i] = i;
index++;
}
if (index == 10 && MemberClassWithClassConstraint<Test>.Status == 3)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008;
// <Title> Tests generic class indexer used in the while/do expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string p1 = null;
float p2 = 1.23f;
short[] p3 = null;
int index = 0;
do
{
index++;
if (index == 10)
break;
}
while (dy[p1, p2, p3] ?? true);
if (index == 10 && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009;
// <Title> Tests generic class indexer used in switch expression.</Title>
// <Description> Won't fix: no dynamic in switch expression </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
bool isChecked = false;
switch ((int)dy["Test"])
{
case 0:
isChecked = true;
break;
default:
break;
}
if (isChecked && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010;
// <Title> Tests generic class indexer used in switch section statement list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string a = "Test";
MyClass p1 = new MyClass()
{
Field = 10
}
;
char? p2 = null;
MyEnum[] p3 = new MyEnum[]
{
MyEnum.Second
}
;
dynamic result = null;
switch (a)
{
case "Test":
dy[p1, p2, p3] = 10;
result = dy[p1, p2, p3];
break;
default:
break;
}
if (((MyClass)result).Field == 10)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011;
// <Title> Tests generic class indexer used in switch default section statement list.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClass<int> mc = new MemberClass<int>();
dynamic dy = mc;
string a = "Test1";
MyClass p1 = new MyClass()
{
Field = 10
}
;
MyStruct? p2 = new MyStruct()
{
Number = 11
}
;
MyEnum[] p3 = new MyEnum[10];
dynamic[] result = null;
switch (a)
{
case "Test":
break;
default:
result = dy[p1, p2, p3];
dy[p1, p2, p3] = new dynamic[10];
break;
}
if (result.Length != 2 && MemberClass<int>.Status != 2)
return 1;
if (((MyClass)result[0]).Field == 10 && ((MyStruct)result[1]).Number == 11)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass014.genclass014
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass014.genclass014;
// <Title> Tests generic class indexer used in try/catch/finally.</Title>
// <Description>
// try/catch/finally that uses an anonymous method and refer two dynamic parameters.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClass<int>();
dynamic result = -1;
try
{
Func<string, dynamic> func = delegate (string x)
{
throw new TimeoutException(dy[x].ToString());
}
;
result = func("Test");
return 1;
}
catch (TimeoutException e)
{
if (e.Message != "0")
return 1;
}
finally
{
result = dy[new int?[3]];
}
if (result.Length == 3 && result[0] == null && result[1] == null && result[2] == null && MemberClass<int>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass015.genclass015
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass015.genclass015;
// <Title> Tests generic class indexer used in iterator that calls to a lambda expression.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections;
public class Test
{
private static dynamic s_dy = new MemberClass<string>();
private static int s_num = 0;
[Fact(Skip = "870811")]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic t = new Test();
foreach (MyClass[] me in t.Increment())
{
if (MemberClass<string>.Status != 1 || me.Length != 2)
return 1;
}
return 0;
}
public IEnumerable Increment()
{
while (s_num++ < 4)
{
Func<MyEnum, MyClass[]> func = (MyEnum p1) => s_dy[p1];
yield return func((MyEnum)s_num);
}
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016;
// <Title> Tests generic class indexer used in object initializer inside a collection initializer.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Collections;
using System.Collections.Generic;
public class Test
{
private string _field = string.Empty;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
dynamic dy = new MemberClassWithClassConstraint<string>();
decimal dec = 123M;
List<Test> list = new List<Test>()
{
new Test()
{
_field = dy[dec, dy]
}
};
if (list.Count == 1 && list[0]._field == null && MemberClassWithClassConstraint<string>.Status == 1)
return 0;
else
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017;
// <Title> Tests generic class indexer used in anonymous type.</Title>
// <Description>
// anonymous type inside a query expression that introduces dynamic variables.
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
public class Test
{
private int _field;
public Test()
{
_field = 10;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
List<string> list = new List<string>()
{
"0", "4", null, "6", "4", "4", null
}
;
// string s = "test";
dynamic dy = new MemberClassWithAnotherTypeConstraint<string, string>();
dynamic dy2 = new MemberClassWithNewConstraint<Test>();
Test t = new Test()
{
_field = 1
}
;
var result = list.Where(p => p == dy[dy2]).Select(p => new
{
A = dy2[t],
B = dy[dy2]
}
).ToList();
if (result.Count == 2 && MemberClassWithAnotherTypeConstraint<string, string>.Status == 3 && MemberClassWithNewConstraint<Test>.Status == 1)
{
foreach (var m in result)
{
if (((Test)m.A)._field != 10 || m.B != null)
{
return 1;
}
}
return 0;
}
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018;
// <Title> Tests generic class indexer used in static generic method body.</Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
return TestMethod<Test>();
}
private static int TestMethod<T>()
{
MemberClassWithNewConstraint<MyClass> mc = new MemberClassWithNewConstraint<MyClass>();
dynamic dy = mc;
MyClass p1 = null;
dy[p1] = dy;
if (MemberClassWithNewConstraint<MyClass>.Status != 2)
return 1;
dynamic p2 = dy[p1];
if (p2.GetType() == typeof(MyClass) && MemberClassWithNewConstraint<MyClass>.Status == 1)
return 0;
return 1;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020;
// <Title> Tests generic class indexer used in static method body.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : C
{
private int _field;
public Test()
{
_field = 11;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassWithUDClassConstraint<Test> mc = new MemberClassWithUDClassConstraint<Test>();
dynamic dy = mc;
Test t = null;
dy[t] = new C();
if (MemberClassWithUDClassConstraint<Test>.Status != 2)
return 1;
t = new Test()
{
_field = 10
}
;
Test result = (Test)dy[t];
if (result._field != 11 || MemberClassWithUDClassConstraint<Test>.Status != 1)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021;
// <Title> Tests generic class indexer used in static method body.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassWithStructConstraint<char> mc = new MemberClassWithStructConstraint<char>();
dynamic dy = mc;
dy[int.MinValue] = new Test();
if (MemberClassWithStructConstraint<char>.Status != 2)
return 1;
dynamic result = dy[int.MaxValue];
if (result != int.MaxValue || MemberClassWithStructConstraint<char>.Status != 1)
return 1;
return 0;
}
}
//</Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022
{
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer;
using ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022;
// <Title> Tests generic class indexer used in static method body.</Title>
// <Description>
// Negative
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class Test : I
{
public class InnerTest : Test
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod());
}
public static int MainMethod()
{
MemberClassWithInterfaceConstraint<InnerTest> mc = new MemberClassWithInterfaceConstraint<InnerTest>();
dynamic dy = mc;
dy[int.MinValue, new InnerTest()] = new Test();
if (MemberClassWithInterfaceConstraint<InnerTest>.Status != 2)
return 1;
dynamic result = dy[int.MaxValue, null];
if (result != null || MemberClassWithInterfaceConstraint<InnerTest>.Status != 1)
return 1;
return 0;
}
}
//</Code>
}
| |
using XenAdmin.Controls.DataGridViewEx;
namespace XenAdmin.Wizards.PatchingWizard
{
partial class PatchingWizard_SelectPatchPage
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PatchingWizard_SelectPatchPage));
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle();
System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.automaticOptionLabel = new System.Windows.Forms.Label();
this.AutomaticRadioButton = new System.Windows.Forms.RadioButton();
this.RestoreDismUpdatesButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.fileNameTextBox = new System.Windows.Forms.TextBox();
this.BrowseButton = new System.Windows.Forms.Button();
this.selectFromDiskRadioButton = new System.Windows.Forms.RadioButton();
this.downloadUpdateRadioButton = new System.Windows.Forms.RadioButton();
this.label3 = new System.Windows.Forms.Label();
this.dataGridViewPatches = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx();
this.ColumnUpdate = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDescription = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDate = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.webPageColumn = new System.Windows.Forms.DataGridViewLinkColumn();
this.RefreshListButton = new System.Windows.Forms.Button();
this.tableLayoutPanel1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPatches)).BeginInit();
this.SuspendLayout();
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.automaticOptionLabel, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.AutomaticRadioButton, 0, 2);
this.tableLayoutPanel1.Controls.Add(this.RestoreDismUpdatesButton, 1, 5);
this.tableLayoutPanel1.Controls.Add(this.label2, 0, 7);
this.tableLayoutPanel1.Controls.Add(this.fileNameTextBox, 1, 7);
this.tableLayoutPanel1.Controls.Add(this.BrowseButton, 2, 7);
this.tableLayoutPanel1.Controls.Add(this.selectFromDiskRadioButton, 1, 6);
this.tableLayoutPanel1.Controls.Add(this.downloadUpdateRadioButton, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.label3, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.dataGridViewPatches, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.RefreshListButton, 0, 5);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// automaticOptionLabel
//
resources.ApplyResources(this.automaticOptionLabel, "automaticOptionLabel");
this.tableLayoutPanel1.SetColumnSpan(this.automaticOptionLabel, 3);
this.automaticOptionLabel.Name = "automaticOptionLabel";
//
// AutomaticRadioButton
//
resources.ApplyResources(this.AutomaticRadioButton, "AutomaticRadioButton");
this.tableLayoutPanel1.SetColumnSpan(this.AutomaticRadioButton, 3);
this.AutomaticRadioButton.Name = "AutomaticRadioButton";
this.AutomaticRadioButton.UseVisualStyleBackColor = true;
//
// RestoreDismUpdatesButton
//
resources.ApplyResources(this.RestoreDismUpdatesButton, "RestoreDismUpdatesButton");
this.RestoreDismUpdatesButton.Name = "RestoreDismUpdatesButton";
this.RestoreDismUpdatesButton.UseVisualStyleBackColor = true;
this.RestoreDismUpdatesButton.Click += new System.EventHandler(this.RestoreDismUpdatesButton_Click);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// fileNameTextBox
//
resources.ApplyResources(this.fileNameTextBox, "fileNameTextBox");
this.fileNameTextBox.Name = "fileNameTextBox";
this.fileNameTextBox.TextChanged += new System.EventHandler(this.fileNameTextBox_TextChanged);
this.fileNameTextBox.Enter += new System.EventHandler(this.fileNameTextBox_Enter);
//
// BrowseButton
//
resources.ApplyResources(this.BrowseButton, "BrowseButton");
this.BrowseButton.Name = "BrowseButton";
this.BrowseButton.UseVisualStyleBackColor = true;
this.BrowseButton.Click += new System.EventHandler(this.BrowseButton_Click);
//
// selectFromDiskRadioButton
//
resources.ApplyResources(this.selectFromDiskRadioButton, "selectFromDiskRadioButton");
this.tableLayoutPanel1.SetColumnSpan(this.selectFromDiskRadioButton, 4);
this.selectFromDiskRadioButton.Name = "selectFromDiskRadioButton";
this.selectFromDiskRadioButton.UseVisualStyleBackColor = true;
this.selectFromDiskRadioButton.CheckedChanged += new System.EventHandler(this.selectFromDiskRadioButton_CheckedChanged);
//
// downloadUpdateRadioButton
//
resources.ApplyResources(this.downloadUpdateRadioButton, "downloadUpdateRadioButton");
this.downloadUpdateRadioButton.Checked = true;
this.tableLayoutPanel1.SetColumnSpan(this.downloadUpdateRadioButton, 3);
this.downloadUpdateRadioButton.Name = "downloadUpdateRadioButton";
this.downloadUpdateRadioButton.TabStop = true;
this.downloadUpdateRadioButton.UseVisualStyleBackColor = true;
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.tableLayoutPanel1.SetColumnSpan(this.label3, 3);
this.label3.Name = "label3";
//
// dataGridViewPatches
//
this.dataGridViewPatches.AllowUserToResizeColumns = false;
this.dataGridViewPatches.AutoSizeRowsMode = System.Windows.Forms.DataGridViewAutoSizeRowsMode.AllCells;
this.dataGridViewPatches.BackgroundColor = System.Drawing.SystemColors.Window;
this.dataGridViewPatches.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.Raised;
this.dataGridViewPatches.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridViewPatches.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnUpdate,
this.ColumnDescription,
this.ColumnDate,
this.webPageColumn});
this.tableLayoutPanel1.SetColumnSpan(this.dataGridViewPatches, 3);
resources.ApplyResources(this.dataGridViewPatches, "dataGridViewPatches");
this.dataGridViewPatches.Name = "dataGridViewPatches";
this.dataGridViewPatches.ReadOnly = true;
dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft;
dataGridViewCellStyle4.BackColor = System.Drawing.SystemColors.Control;
dataGridViewCellStyle4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
dataGridViewCellStyle4.ForeColor = System.Drawing.SystemColors.WindowText;
dataGridViewCellStyle4.SelectionBackColor = System.Drawing.SystemColors.Highlight;
dataGridViewCellStyle4.SelectionForeColor = System.Drawing.SystemColors.HighlightText;
dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.dataGridViewPatches.RowHeadersDefaultCellStyle = dataGridViewCellStyle4;
dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewPatches.RowsDefaultCellStyle = dataGridViewCellStyle5;
this.dataGridViewPatches.RowTemplate.Resizable = System.Windows.Forms.DataGridViewTriState.True;
this.dataGridViewPatches.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridViewPatches_CellContentClick);
this.dataGridViewPatches.CellMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridViewPatches_CellMouseClick);
this.dataGridViewPatches.ColumnHeaderMouseClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridViewPatches_ColumnHeaderMouseClick);
this.dataGridViewPatches.SelectionChanged += new System.EventHandler(this.dataGridViewPatches_SelectionChanged);
this.dataGridViewPatches.SortCompare += new System.Windows.Forms.DataGridViewSortCompareEventHandler(this.dataGridViewPatches_SortCompare);
this.dataGridViewPatches.Enter += new System.EventHandler(this.dataGridViewPatches_Enter);
//
// ColumnUpdate
//
this.ColumnUpdate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.DisplayedCells;
dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft;
dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnUpdate.DefaultCellStyle = dataGridViewCellStyle1;
this.ColumnUpdate.FillWeight = 76.67365F;
resources.ApplyResources(this.ColumnUpdate, "ColumnUpdate");
this.ColumnUpdate.Name = "ColumnUpdate";
this.ColumnUpdate.ReadOnly = true;
//
// ColumnDescription
//
this.ColumnDescription.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft;
dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnDescription.DefaultCellStyle = dataGridViewCellStyle2;
this.ColumnDescription.FillWeight = 172.4619F;
resources.ApplyResources(this.ColumnDescription, "ColumnDescription");
this.ColumnDescription.Name = "ColumnDescription";
this.ColumnDescription.ReadOnly = true;
//
// ColumnDate
//
this.ColumnDate.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft;
dataGridViewCellStyle3.WrapMode = System.Windows.Forms.DataGridViewTriState.False;
this.ColumnDate.DefaultCellStyle = dataGridViewCellStyle3;
this.ColumnDate.FillWeight = 80F;
resources.ApplyResources(this.ColumnDate, "ColumnDate");
this.ColumnDate.Name = "ColumnDate";
this.ColumnDate.ReadOnly = true;
//
// webPageColumn
//
this.webPageColumn.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None;
this.webPageColumn.FillWeight = 60F;
resources.ApplyResources(this.webPageColumn, "webPageColumn");
this.webPageColumn.Name = "webPageColumn";
this.webPageColumn.ReadOnly = true;
this.webPageColumn.Resizable = System.Windows.Forms.DataGridViewTriState.True;
//
// RefreshListButton
//
resources.ApplyResources(this.RefreshListButton, "RefreshListButton");
this.RefreshListButton.Name = "RefreshListButton";
this.RefreshListButton.UseVisualStyleBackColor = true;
this.RefreshListButton.Click += new System.EventHandler(this.RefreshListButton_Click);
//
// PatchingWizard_SelectPatchPage
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "PatchingWizard_SelectPatchPage";
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dataGridViewPatches)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button BrowseButton;
private DataGridViewEx dataGridViewPatches;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox fileNameTextBox;
private System.Windows.Forms.RadioButton selectFromDiskRadioButton;
private System.Windows.Forms.Button RefreshListButton;
private System.Windows.Forms.RadioButton downloadUpdateRadioButton;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Button RestoreDismUpdatesButton;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnUpdate;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDescription;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDate;
private System.Windows.Forms.DataGridViewLinkColumn webPageColumn;
private System.Windows.Forms.Label automaticOptionLabel;
private System.Windows.Forms.RadioButton AutomaticRadioButton;
}
}
| |
// 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 gagvr = Google.Ads.GoogleAds.V9.Resources;
using gaxgrpc = Google.Api.Gax.Grpc;
using gr = Google.Rpc;
using grpccore = Grpc.Core;
using moq = Moq;
using st = System.Threading;
using stt = System.Threading.Tasks;
using NUnit.Framework;
using Google.Ads.GoogleAds.V9.Services;
namespace Google.Ads.GoogleAds.Tests.V9.Services
{
/// <summary>Generated unit tests.</summary>
public sealed class GeneratedCustomerLabelServiceClientTest
{
[Category("Autogenerated")][Test]
public void GetCustomerLabelRequestObject()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
GetCustomerLabelRequest request = new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
gagvr::CustomerLabel expectedResponse = new gagvr::CustomerLabel
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
CustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
mockGrpcClient.Setup(x => x.GetCustomerLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerLabel response = client.GetCustomerLabel(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerLabelRequestObjectAsync()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
GetCustomerLabelRequest request = new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
gagvr::CustomerLabel expectedResponse = new gagvr::CustomerLabel
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
CustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
mockGrpcClient.Setup(x => x.GetCustomerLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerLabel responseCallSettings = await client.GetCustomerLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerLabel responseCancellationToken = await client.GetCustomerLabelAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerLabel()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
GetCustomerLabelRequest request = new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
gagvr::CustomerLabel expectedResponse = new gagvr::CustomerLabel
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
CustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
mockGrpcClient.Setup(x => x.GetCustomerLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerLabel response = client.GetCustomerLabel(request.ResourceName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerLabelAsync()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
GetCustomerLabelRequest request = new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
gagvr::CustomerLabel expectedResponse = new gagvr::CustomerLabel
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
CustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
mockGrpcClient.Setup(x => x.GetCustomerLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerLabel responseCallSettings = await client.GetCustomerLabelAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerLabel responseCancellationToken = await client.GetCustomerLabelAsync(request.ResourceName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void GetCustomerLabelResourceNames()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
GetCustomerLabelRequest request = new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
gagvr::CustomerLabel expectedResponse = new gagvr::CustomerLabel
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
CustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
mockGrpcClient.Setup(x => x.GetCustomerLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerLabel response = client.GetCustomerLabel(request.ResourceNameAsCustomerLabelName);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task GetCustomerLabelResourceNamesAsync()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
GetCustomerLabelRequest request = new GetCustomerLabelRequest
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
gagvr::CustomerLabel expectedResponse = new gagvr::CustomerLabel
{
ResourceNameAsCustomerLabelName = gagvr::CustomerLabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
CustomerAsCustomerName = gagvr::CustomerName.FromCustomer("[CUSTOMER_ID]"),
LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"),
};
mockGrpcClient.Setup(x => x.GetCustomerLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::CustomerLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
gagvr::CustomerLabel responseCallSettings = await client.GetCustomerLabelAsync(request.ResourceNameAsCustomerLabelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
gagvr::CustomerLabel responseCancellationToken = await client.GetCustomerLabelAsync(request.ResourceNameAsCustomerLabelName, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerLabelsRequestObject()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
MutateCustomerLabelsRequest request = new MutateCustomerLabelsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerLabelOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateCustomerLabelsResponse expectedResponse = new MutateCustomerLabelsResponse
{
Results =
{
new MutateCustomerLabelResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerLabelsResponse response = client.MutateCustomerLabels(request);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerLabelsRequestObjectAsync()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
MutateCustomerLabelsRequest request = new MutateCustomerLabelsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerLabelOperation(),
},
PartialFailure = false,
ValidateOnly = true,
};
MutateCustomerLabelsResponse expectedResponse = new MutateCustomerLabelsResponse
{
Results =
{
new MutateCustomerLabelResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerLabelsResponse responseCallSettings = await client.MutateCustomerLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerLabelsResponse responseCancellationToken = await client.MutateCustomerLabelsAsync(request, st::CancellationToken.None);
Assert.AreEqual(expectedResponse, responseCancellationToken);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public void MutateCustomerLabels()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
MutateCustomerLabelsRequest request = new MutateCustomerLabelsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerLabelOperation(),
},
};
MutateCustomerLabelsResponse expectedResponse = new MutateCustomerLabelsResponse
{
Results =
{
new MutateCustomerLabelResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse);
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerLabelsResponse response = client.MutateCustomerLabels(request.CustomerId, request.Operations);
Assert.AreEqual(expectedResponse, response);
mockGrpcClient.VerifyAll();
}
[Category("Autogenerated")][Test]
public async stt::Task MutateCustomerLabelsAsync()
{
moq::Mock<CustomerLabelService.CustomerLabelServiceClient> mockGrpcClient = new moq::Mock<CustomerLabelService.CustomerLabelServiceClient>(moq::MockBehavior.Strict);
MutateCustomerLabelsRequest request = new MutateCustomerLabelsRequest
{
CustomerId = "customer_id3b3724cb",
Operations =
{
new CustomerLabelOperation(),
},
};
MutateCustomerLabelsResponse expectedResponse = new MutateCustomerLabelsResponse
{
Results =
{
new MutateCustomerLabelResult(),
},
PartialFailureError = new gr::Status(),
};
mockGrpcClient.Setup(x => x.MutateCustomerLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateCustomerLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null));
CustomerLabelServiceClient client = new CustomerLabelServiceClientImpl(mockGrpcClient.Object, null);
MutateCustomerLabelsResponse responseCallSettings = await client.MutateCustomerLabelsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));
Assert.AreEqual(expectedResponse, responseCallSettings);
MutateCustomerLabelsResponse responseCancellationToken = await client.MutateCustomerLabelsAsync(request.CustomerId, request.Operations, st::CancellationToken.None);
Assert.AreEqual(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.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.Serialization;
namespace System.Collections.Generic
{
[DebuggerTypeProxy(typeof(IDictionaryDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public class SortedDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary, IReadOnlyDictionary<TKey, TValue> where TKey : notnull
{
[NonSerialized]
private KeyCollection? _keys;
[NonSerialized]
private ValueCollection? _values;
private TreeSet<KeyValuePair<TKey, TValue>> _set; // Do not rename (binary serialization)
public SortedDictionary() : this((IComparer<TKey>?)null)
{
}
public SortedDictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null)
{
}
public SortedDictionary(IDictionary<TKey, TValue> dictionary, IComparer<TKey>? comparer)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
_set = new TreeSet<KeyValuePair<TKey, TValue>>(new KeyValuePairComparer(comparer));
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
{
_set.Add(pair);
}
}
public SortedDictionary(IComparer<TKey>? comparer)
{
_set = new TreeSet<KeyValuePair<TKey, TValue>>(new KeyValuePairComparer(comparer));
}
void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair)
{
_set.Add(keyValuePair);
}
bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair)
{
TreeSet<KeyValuePair<TKey, TValue>>.Node? node = _set.FindNode(keyValuePair);
if (node == null)
{
return false;
}
if (keyValuePair.Value == null)
{
return node.Item.Value == null;
}
else
{
return EqualityComparer<TValue>.Default.Equals(node.Item.Value, keyValuePair.Value);
}
}
bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair)
{
TreeSet<KeyValuePair<TKey, TValue>>.Node? node = _set.FindNode(keyValuePair);
if (node == null)
{
return false;
}
if (EqualityComparer<TValue>.Default.Equals(node.Item.Value, keyValuePair.Value))
{
_set.Remove(keyValuePair);
return true;
}
return false;
}
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get
{
return false;
}
}
public TValue this[TKey key]
{
get
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
TreeSet<KeyValuePair<TKey, TValue>>.Node? node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue)!));
if (node == null)
{
throw new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
}
return node.Item.Value;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
TreeSet<KeyValuePair<TKey, TValue>>.Node? node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue)!));
if (node == null)
{
_set.Add(new KeyValuePair<TKey, TValue>(key, value));
}
else
{
node.Item = new KeyValuePair<TKey, TValue>(node.Item.Key, value);
_set.UpdateVersion();
}
}
}
public int Count
{
get
{
return _set.Count;
}
}
public IComparer<TKey> Comparer
{
get
{
return ((KeyValuePairComparer)_set.Comparer).keyComparer;
}
}
public KeyCollection Keys
{
get
{
if (_keys == null) _keys = new KeyCollection(this);
return _keys;
}
}
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
IEnumerable<TKey> IReadOnlyDictionary<TKey, TValue>.Keys
{
get
{
return Keys;
}
}
public ValueCollection Values
{
get
{
if (_values == null) _values = new ValueCollection(this);
return _values;
}
}
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
IEnumerable<TValue> IReadOnlyDictionary<TKey, TValue>.Values
{
get
{
return Values;
}
}
public void Add(TKey key, TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
_set.Add(new KeyValuePair<TKey, TValue>(key, value));
}
public void Clear()
{
_set.Clear();
}
public bool ContainsKey(TKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _set.Contains(new KeyValuePair<TKey, TValue>(key, default(TValue)!));
}
public bool ContainsValue(TValue value)
{
bool found = false;
if (value == null)
{
_set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node)
{
if (node.Item.Value == null)
{
found = true;
return false; // stop the walk
}
return true;
});
}
else
{
EqualityComparer<TValue> valueComparer = EqualityComparer<TValue>.Default;
_set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node)
{
if (valueComparer.Equals(node.Item.Value, value))
{
found = true;
return false; // stop the walk
}
return true;
});
}
return found;
}
public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index)
{
_set.CopyTo(array, index);
}
public Enumerator GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
public bool Remove(TKey key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return _set.Remove(new KeyValuePair<TKey, TValue>(key, default(TValue)!));
}
public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
TreeSet<KeyValuePair<TKey, TValue>>.Node? node = _set.FindNode(new KeyValuePair<TKey, TValue>(key, default(TValue)!));
if (node == null)
{
value = default(TValue)!;
return false;
}
value = node.Item.Value;
return true;
}
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_set).CopyTo(array, index);
}
bool IDictionary.IsFixedSize
{
get { return false; }
}
bool IDictionary.IsReadOnly
{
get { return false; }
}
ICollection IDictionary.Keys
{
get { return (ICollection)Keys; }
}
ICollection IDictionary.Values
{
get { return (ICollection)Values; }
}
object? IDictionary.this[object key]
{
get
{
if (IsCompatibleKey(key))
{
TValue value;
if (TryGetValue((TKey)key, out value))
{
return value;
}
}
return null;
}
set
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null && !(default(TValue)! == null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
throw new ArgumentNullException(nameof(value));
try
{
TKey tempKey = (TKey)key;
try
{
this[tempKey] = (TValue)value!;
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
}
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
}
}
}
void IDictionary.Add(object key, object? value)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
if (value == null && !(default(TValue)! == null)) // TODO-NULLABLE: default(T) == null warning (https://github.com/dotnet/roslyn/issues/34757)
throw new ArgumentNullException(nameof(value));
try
{
TKey tempKey = (TKey)key;
try
{
Add(tempKey, (TValue)value!);
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, value, typeof(TValue)), nameof(value));
}
}
catch (InvalidCastException)
{
throw new ArgumentException(SR.Format(SR.Arg_WrongType, key, typeof(TKey)), nameof(key));
}
}
bool IDictionary.Contains(object key)
{
if (IsCompatibleKey(key))
{
return ContainsKey((TKey)key);
}
return false;
}
private static bool IsCompatibleKey(object key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
return (key is TKey);
}
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new Enumerator(this, Enumerator.DictEntry);
}
void IDictionary.Remove(object key)
{
if (IsCompatibleKey(key))
{
Remove((TKey)key);
}
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_set).SyncRoot; }
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(this, Enumerator.KeyValuePair);
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator
{
private TreeSet<KeyValuePair<TKey, TValue>>.Enumerator _treeEnum;
private int _getEnumeratorRetType; // What should Enumerator.Current return?
internal const int KeyValuePair = 1;
internal const int DictEntry = 2;
internal Enumerator(SortedDictionary<TKey, TValue> dictionary, int getEnumeratorRetType)
{
_treeEnum = dictionary._set.GetEnumerator();
_getEnumeratorRetType = getEnumeratorRetType;
}
public bool MoveNext()
{
return _treeEnum.MoveNext();
}
public void Dispose()
{
_treeEnum.Dispose();
}
public KeyValuePair<TKey, TValue> Current
{
get
{
return _treeEnum.Current;
}
}
internal bool NotStartedOrEnded
{
get
{
return _treeEnum.NotStartedOrEnded;
}
}
internal void Reset()
{
_treeEnum.Reset();
}
void IEnumerator.Reset()
{
_treeEnum.Reset();
}
object? IEnumerator.Current
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
if (_getEnumeratorRetType == DictEntry)
{
return new DictionaryEntry(Current.Key, Current.Value);
}
else
{
return new KeyValuePair<TKey, TValue>(Current.Key, Current.Value);
}
}
}
object IDictionaryEnumerator.Key
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current.Key;
}
}
object? IDictionaryEnumerator.Value
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current.Value;
}
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return new DictionaryEntry(Current.Key, Current.Value);
}
}
}
[DebuggerTypeProxy(typeof(DictionaryKeyCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class KeyCollection : ICollection<TKey>, ICollection, IReadOnlyCollection<TKey>
{
private SortedDictionary<TKey, TValue> _dictionary;
public KeyCollection(SortedDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator<TKey> IEnumerable<TKey>.GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(_dictionary);
}
public void CopyTo(TKey[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { array[index++] = node.Item.Key; return true; });
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _dictionary.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
TKey[]? keys = array as TKey[];
if (keys != null)
{
CopyTo(keys, index);
}
else
{
try
{
object[] objects = (object[])array;
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { objects[index++] = node.Item.Key; return true; });
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
public int Count
{
get { return _dictionary.Count; }
}
bool ICollection<TKey>.IsReadOnly
{
get { return true; }
}
void ICollection<TKey>.Add(TKey item)
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
void ICollection<TKey>.Clear()
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
bool ICollection<TKey>.Contains(TKey item)
{
return _dictionary.ContainsKey(item);
}
bool ICollection<TKey>.Remove(TKey item)
{
throw new NotSupportedException(SR.NotSupported_KeyCollectionSet);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dictionary).SyncRoot; }
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<TKey>, IEnumerator
{
private SortedDictionary<TKey, TValue>.Enumerator _dictEnum;
internal Enumerator(SortedDictionary<TKey, TValue> dictionary)
{
_dictEnum = dictionary.GetEnumerator();
}
public void Dispose()
{
_dictEnum.Dispose();
}
public bool MoveNext()
{
return _dictEnum.MoveNext();
}
public TKey Current
{
get
{
return _dictEnum.Current.Key;
}
}
object? IEnumerator.Current
{
get
{
if (_dictEnum.NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current;
}
}
void IEnumerator.Reset()
{
_dictEnum.Reset();
}
}
}
[DebuggerTypeProxy(typeof(DictionaryValueCollectionDebugView<,>))]
[DebuggerDisplay("Count = {Count}")]
public sealed class ValueCollection : ICollection<TValue>, ICollection, IReadOnlyCollection<TValue>
{
private SortedDictionary<TKey, TValue> _dictionary;
public ValueCollection(SortedDictionary<TKey, TValue> dictionary)
{
if (dictionary == null)
{
throw new ArgumentNullException(nameof(dictionary));
}
_dictionary = dictionary;
}
public Enumerator GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator<TValue> IEnumerable<TValue>.GetEnumerator()
{
return new Enumerator(_dictionary);
}
IEnumerator IEnumerable.GetEnumerator()
{
return new Enumerator(_dictionary);
}
public void CopyTo(TValue[] array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { array[index++] = node.Item.Value; return true; });
}
void ICollection.CopyTo(Array array, int index)
{
if (array == null)
{
throw new ArgumentNullException(nameof(array));
}
if (array.Rank != 1)
{
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
}
if (array.GetLowerBound(0) != 0)
{
throw new ArgumentException(SR.Arg_NonZeroLowerBound, nameof(array));
}
if (index < 0)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
}
if (array.Length - index < _dictionary.Count)
{
throw new ArgumentException(SR.Arg_ArrayPlusOffTooSmall);
}
TValue[]? values = array as TValue[];
if (values != null)
{
CopyTo(values, index);
}
else
{
try
{
object?[] objects = (object?[])array;
_dictionary._set.InOrderTreeWalk(delegate (TreeSet<KeyValuePair<TKey, TValue>>.Node node) { objects[index++] = node.Item.Value; return true; });
}
catch (ArrayTypeMismatchException)
{
throw new ArgumentException(SR.Argument_InvalidArrayType, nameof(array));
}
}
}
public int Count
{
get { return _dictionary.Count; }
}
bool ICollection<TValue>.IsReadOnly
{
get { return true; }
}
void ICollection<TValue>.Add(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
void ICollection<TValue>.Clear()
{
throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
bool ICollection<TValue>.Contains(TValue item)
{
return _dictionary.ContainsValue(item);
}
bool ICollection<TValue>.Remove(TValue item)
{
throw new NotSupportedException(SR.NotSupported_ValueCollectionSet);
}
bool ICollection.IsSynchronized
{
get { return false; }
}
object ICollection.SyncRoot
{
get { return ((ICollection)_dictionary).SyncRoot; }
}
[SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")]
public struct Enumerator : IEnumerator<TValue>, IEnumerator
{
private SortedDictionary<TKey, TValue>.Enumerator _dictEnum;
internal Enumerator(SortedDictionary<TKey, TValue> dictionary)
{
_dictEnum = dictionary.GetEnumerator();
}
public void Dispose()
{
_dictEnum.Dispose();
}
public bool MoveNext()
{
return _dictEnum.MoveNext();
}
public TValue Current
{
get
{
return _dictEnum.Current.Value;
}
}
object? IEnumerator.Current
{
get
{
if (_dictEnum.NotStartedOrEnded)
{
throw new InvalidOperationException(SR.InvalidOperation_EnumOpCantHappen);
}
return Current;
}
}
void IEnumerator.Reset()
{
_dictEnum.Reset();
}
}
}
[Serializable]
public sealed class KeyValuePairComparer : Comparer<KeyValuePair<TKey, TValue>>
{
internal IComparer<TKey> keyComparer; // Do not rename (binary serialization)
public KeyValuePairComparer(IComparer<TKey>? keyComparer)
{
if (keyComparer == null)
{
this.keyComparer = Comparer<TKey>.Default;
}
else
{
this.keyComparer = keyComparer;
}
}
public override int Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y)
{
return keyComparer.Compare(x.Key, y.Key);
}
}
}
/// <summary>
/// This class is intended as a helper for backwards compatibility with existing SortedDictionaries.
/// TreeSet has been converted into SortedSet{T}, which will be exposed publicly. SortedDictionaries
/// have the problem where they have already been serialized to disk as having a backing class named
/// TreeSet. To ensure that we can read back anything that has already been written to disk, we need to
/// make sure that we have a class named TreeSet that does everything the way it used to.
///
/// The only thing that makes it different from SortedSet is that it throws on duplicates
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class TreeSet<T> : SortedSet<T>
{
public TreeSet()
: base()
{ }
public TreeSet(IComparer<T>? comparer) : base(comparer) { }
private TreeSet(SerializationInfo siInfo, StreamingContext context) : base(siInfo, context) { }
internal override bool AddIfNotPresent(T item)
{
bool ret = base.AddIfNotPresent(item);
if (!ret)
{
throw new ArgumentException(SR.Format(SR.Argument_AddingDuplicate, item));
}
return ret;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Shared;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System;
using Microsoft.Build.Unittest;
using Xunit;
using Microsoft.Build.Framework;
using System.Linq;
namespace Microsoft.Build.UnitTests.Preprocessor
{
/// <summary>
/// Tests mainly for project preprocessing
/// </summary>
public class Preprocessor_Tests : IDisposable
{
private static string CurrentDirectoryXmlCommentFriendly => Directory.GetCurrentDirectory().Replace("--", "__");
public Preprocessor_Tests()
{
Setup();
}
/// <summary>
/// Clear out the cache
/// </summary>
private void Setup()
{
ProjectCollection.GlobalProjectCollection.UnloadAllProjects();
GC.Collect();
}
/// <summary>
/// Clear out the cache
/// </summary>
public void Dispose()
{
Setup();
}
/// <summary>
/// Basic project
/// </summary>
[Fact]
public void Single()
{
Project project = new Project();
project.SetProperty("p", "v1");
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// InitialTargets are concatenated, outermost to innermost
/// </summary>
[Fact]
public void InitialTargetsOuterAndInner()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.InitialTargets = "i1";
xml1.AddImport("p2");
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.InitialTargets = "i2";
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"" InitialTargets=""i1;i2"">
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// InitialTargets are concatenated, outermost to innermost
/// </summary>
[Fact]
public void InitialTargetsInnerOnly()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddImport("p2");
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.InitialTargets = "i2";
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"" InitialTargets=""i2"">
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// InitialTargets are concatenated, outermost to innermost
/// </summary>
[Fact]
public void InitialTargetsOuterOnly()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.InitialTargets = "i1";
xml1.AddImport("p2");
ProjectRootElement.Create("p2");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"" InitialTargets=""i1"">
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Basic empty project importing another
/// </summary>
[Fact]
public void TwoFirstEmpty()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddImport("p2");
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.AddProperty("p", "v2");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<PropertyGroup>
<p>v2</p>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// False import should not be followed
/// </summary>
[Fact]
public void FalseImport()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddProperty("p", "v1");
xml1.AddImport("p2").Condition = "false";
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.AddProperty("p", "v2");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--<Import Project=""p2"" Condition=""false"" />-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Basic project importing another empty one
/// </summary>
[Fact]
public void TwoSecondEmpty()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddProperty("p", "v");
xml1.AddImport("p2");
ProjectRootElement.Create("p2");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v</p>
</PropertyGroup>
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Basic project importing another
/// </summary>
[Fact]
public void TwoWithContent()
{
string one = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v0</p>
</PropertyGroup>
<Import Project=""p2""/>
<PropertyGroup>
<p>v2</p>
</PropertyGroup>
</Project>");
string two = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</Project>");
ProjectRootElement twoXml = ProjectRootElement.Create(XmlReader.Create(new StringReader(two)));
twoXml.FullPath = "p2";
Project project;
using (StringReader sr = new StringReader(one))
{
using (XmlReader xr = XmlTextReader.Create(sr))
{
project = new Project(xr);
}
}
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v0</p>
</PropertyGroup>
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
<PropertyGroup>
<p>v2</p>
</PropertyGroup>
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Basic project importing another one via an ImportGroup
/// </summary>
[Fact]
public void ImportGroup()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddProperty("p", "v1");
xml1.AddImportGroup().AddImport("p2");
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.AddProperty("p", "v2");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--<ImportGroup>-->
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<PropertyGroup>
<p>v2</p>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<!--</ImportGroup>-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Basic project importing another one via an ImportGroup with two imports inside it, and a condition on it
/// </summary>
[Fact]
public void ImportGroupDoubleChildPlusCondition()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddProperty("p", "v1");
ProjectImportGroupElement group = xml1.AddImportGroup();
group.Condition = "true";
group.AddImport("p2");
group.AddImport("p3");
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.AddProperty("p", "v2");
ProjectRootElement xml3 = ProjectRootElement.Create("p3");
xml3.AddProperty("p", "v3");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--<ImportGroup Condition=""true"">-->
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<PropertyGroup>
<p>v2</p>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<!--
============================================================================================================================================
<Import Project=""p3"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p3
============================================================================================================================================
-->
<PropertyGroup>
<p>v3</p>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<!--</ImportGroup>-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// First DefaultTargets encountered is used
/// </summary>
[Fact]
public void DefaultTargetsOuterAndInner()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddImport("p2");
xml1.AddImport("p3");
xml1.DefaultTargets = "d1";
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.DefaultTargets = "d2";
ProjectRootElement xml3 = ProjectRootElement.Create("p3");
xml3.DefaultTargets = "d3";
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"" DefaultTargets=""d1"">
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<!--
============================================================================================================================================
<Import Project=""p3"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p3
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// First DefaultTargets encountered is used
/// </summary>
[Fact]
public void DefaultTargetsInnerOnly()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddImport("p2");
xml1.AddImport("p3");
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.DefaultTargets = "d2";
ProjectRootElement xml3 = ProjectRootElement.Create("p3");
xml3.DefaultTargets = "d3";
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"" DefaultTargets=""d2"">
<!--
============================================================================================================================================
<Import Project=""p2"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p2
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<!--
============================================================================================================================================
<Import Project=""p3"">
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p3
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Basic project importing another one via an ImportGroup, but the ImportGroup condition is false
/// </summary>
[Fact]
public void ImportGroupFalseCondition()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
xml1.AddProperty("p", "v1");
xml1.AddImportGroup().AddImport("p2");
xml1.LastChild.Condition = "false";
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
xml2.AddProperty("p", "v2");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--<ImportGroup Condition=""false"">-->
<!--<Import Project=""p2"" />-->
<!--</ImportGroup>-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Import has a wildcard expression
/// </summary>
[Fact]
public void ImportWildcard()
{
string directory = null;
ProjectRootElement xml0, xml1 = null, xml2 = null, xml3 = null;
try
{
directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(directory);
xml0 = ProjectRootElement.Create("p1");
xml0.AddImport(directory + Path.DirectorySeparatorChar + "*.targets");
xml1 = ProjectRootElement.Create(directory + Path.DirectorySeparatorChar + "1.targets");
xml1.AddProperty("p", "v1");
xml1.Save();
xml2 = ProjectRootElement.Create(directory + Path.DirectorySeparatorChar + "2.targets");
xml2.AddProperty("p", "v2");
xml2.Save();
xml3 = ProjectRootElement.Create(directory + Path.DirectorySeparatorChar + "3.xxxxxx");
xml3.AddProperty("p", "v3");
xml3.Save();
Project project = new Project(xml0);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string directoryXmlCommentFriendly = directory.Replace("--", "__");
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<!--
============================================================================================================================================
<Import Project=""" + Path.Combine(directoryXmlCommentFriendly, "*.targets") + @""">
" + Path.Combine(directoryXmlCommentFriendly, "1.targets") + @"
============================================================================================================================================
-->
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
<!--
============================================================================================================================================
<Import Project=""" + Path.Combine(directoryXmlCommentFriendly, "*.targets") + @""">
" + Path.Combine(directoryXmlCommentFriendly, "2.targets") + @"
============================================================================================================================================
-->
<PropertyGroup>
<p>v2</p>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
" + CurrentDirectoryXmlCommentFriendly + Path.DirectorySeparatorChar + @"p1
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
finally
{
File.Delete(xml1.FullPath);
File.Delete(xml2.FullPath);
File.Delete(xml3.FullPath);
FileUtilities.DeleteWithoutTrailingBackslash(directory);
}
}
/// <summary>
/// CDATA node type cloned correctly
/// </summary>
[Fact]
public void CData()
{
Project project = new Project();
project.SetProperty("p", "<![CDATA[<sender>John Smith</sender>]]>");
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<PropertyGroup>
<p><![CDATA[<sender>John Smith</sender>]]></p>
</PropertyGroup>
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
/// <summary>
/// Metadata named "Project" should not confuse it..
/// </summary>
[Fact]
public void ProjectMetadata()
{
string content = ObjectModelHelpers.CleanupFileContents(@"
<Project DefaultTargets='Build' ToolsVersion='msbuilddefaulttoolsversion' xmlns='msbuildnamespace'>
<ItemGroup>
<ProjectReference Include='..\CLREXE\CLREXE.vcxproj'>
<Project>{3699f81b-2d03-46c5-abd7-e88a4c946f28}</Project>
</ProjectReference>
</ItemGroup>
</Project>");
ProjectRootElement xml = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
Project project = new Project(xml);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project DefaultTargets=""Build"" ToolsVersion=""msbuilddefaulttoolsversion"" xmlns=""msbuildnamespace"">
<ItemGroup>
<ProjectReference Include=""..\CLREXE\CLREXE.vcxproj"">
<Project>{3699f81b-2d03-46c5-abd7-e88a4c946f28}</Project>
</ProjectReference>
</ItemGroup>
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
[Fact]
public void SdkImportsAreInPreprocessedOutput()
{
using (TestEnvironment env = TestEnvironment.Create())
{
string testSdkDirectory = env.CreateFolder().Path;
var projectOptions = SdkUtilities.CreateProjectOptionsWithResolver(new SdkUtilities.FileBasedMockSdkResolver(new Dictionary<string, string>
{
{"MSBuildUnitTestSdk", testSdkDirectory}
}));
string sdkPropsPath = Path.Combine(testSdkDirectory, "Sdk.props");
string sdkTargetsPath = Path.Combine(testSdkDirectory, "Sdk.targets");
File.WriteAllText(sdkPropsPath, @"<Project>
<PropertyGroup>
<SdkPropsImported>true</SdkPropsImported>
</PropertyGroup>
</Project>");
File.WriteAllText(sdkTargetsPath, @"<Project>
<PropertyGroup>
<SdkTargetsImported>true</SdkTargetsImported>
</PropertyGroup>
</Project>");
string content = @"<Project Sdk='MSBuildUnitTestSdk'>
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</Project>";
Project project = Project.FromProjectRootElement(
ProjectRootElement.Create(XmlReader.Create(new StringReader(content))),
projectOptions);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
$@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project>
<!--
============================================================================================================================================
<Import Project=""Sdk.props"" Sdk=""MSBuildUnitTestSdk"">
This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk"".
{sdkPropsPath.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<SdkPropsImported>true</SdkPropsImported>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--
============================================================================================================================================
<Import Project=""Sdk.targets"" Sdk=""MSBuildUnitTestSdk"">
This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk"".
{sdkTargetsPath.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<SdkTargetsImported>true</SdkTargetsImported>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
}
[Fact]
public void SdkResolverItemsAndPropertiesAreInPreprocessedOutput()
{
using (TestEnvironment env = TestEnvironment.Create())
{
string testDirectory = env.CreateFolder().Path;
var propertiesToAdd = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{"PropertyFromSdkResolver", "ValueFromSdkResolver" }
};
var itemsToAdd = new Dictionary<string, SdkResultItem>(StringComparer.OrdinalIgnoreCase)
{
{ "ItemNameFromSdkResolver", new SdkResultItem( "ItemValueFromSdkResolver",
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ "MetadataName", "MetadataValue" }
})
}
};
var projectOptions = SdkUtilities.CreateProjectOptionsWithResolver(new SdkUtilities.ConfigurableMockSdkResolver(
new Build.BackEnd.SdkResolution.SdkResult(
new SdkReference("TestPropsAndItemsFromResolverSdk", null, null),
new [] { testDirectory},
version: null,
propertiesToAdd,
itemsToAdd,
warnings: null
)));
string content = @"<Project>
<Import Project='Import.props' Sdk='TestPropsAndItemsFromResolverSdk' />
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</Project>";
string importedPropsPath = Path.Combine(testDirectory, "Import.props");
File.WriteAllText(importedPropsPath, @"<Project>
<PropertyGroup>
<SdkPropsImported>true</SdkPropsImported>
</PropertyGroup>
</Project>");
string projectPath = Path.Combine(testDirectory, "TestProject.csproj");
File.WriteAllText(projectPath, content);
var project = Project.FromFile(projectPath, projectOptions);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string actual = writer.ToString();
// File names for the projects including the properties and items from the SDK resolvers are based on a hash of
// the values, so look up the filename here.
// Sample filename: projectPath + ".SdkResolver.-171948414.proj"
var virtualImport = project.Imports.First(i => i.ImportedProject.FullPath.StartsWith(projectPath + ".SdkResolver"));
string virtualProjectPath = virtualImport.ImportedProject.FullPath;
string expected = ObjectModelHelpers.CleanupFileContents(
$@"<?xml version=""1.0"" encoding=""utf-16""?>
<!--
============================================================================================================================================
{projectPath.Replace("--", "__")}
============================================================================================================================================
-->
<Project>
<!--
============================================================================================================================================
<Import Project=""Import.props"" Sdk=""TestPropsAndItemsFromResolverSdk"">
{virtualProjectPath.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<PropertyFromSdkResolver>ValueFromSdkResolver</PropertyFromSdkResolver>
</PropertyGroup>
<ItemGroup xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">
<ItemNameFromSdkResolver Include=""ItemValueFromSdkResolver"">
<MetadataName>MetadataValue</MetadataName>
</ItemNameFromSdkResolver>
</ItemGroup>
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
<!--
============================================================================================================================================
<Import Project=""Import.props"" Sdk=""TestPropsAndItemsFromResolverSdk"">
{importedPropsPath.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<SdkPropsImported>true</SdkPropsImported>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
{projectPath.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</Project>");
Helpers.VerifyAssertLineByLine(expected, actual);
}
}
[Fact]
public void ImportedProjectsSdkImportsAreInPreprocessedOutput()
{
using (TestEnvironment env = TestEnvironment.Create())
{
string sdk1 = env.CreateFolder().Path;
string sdk2 = env.CreateFolder().Path;
var projectOptions = SdkUtilities.CreateProjectOptionsWithResolver(new SdkUtilities.FileBasedMockSdkResolver(new Dictionary<string, string>
{
{"MSBuildUnitTestSdk1", sdk1},
{"MSBuildUnitTestSdk2", sdk2},
}));
string sdkPropsPath1 = Path.Combine(sdk1, "Sdk.props");
string sdkTargetsPath1 = Path.Combine(sdk1, "Sdk.targets");
File.WriteAllText(sdkPropsPath1, @"<Project>
<PropertyGroup>
<SdkProps1Imported>true</SdkProps1Imported>
</PropertyGroup>
</Project>");
File.WriteAllText(sdkTargetsPath1, @"<Project>
<PropertyGroup>
<SdkTargets1Imported>true</SdkTargets1Imported>
</PropertyGroup>
</Project>");
string sdkPropsPath2 = Path.Combine(sdk2, "Sdk.props");
string sdkTargetsPath2 = Path.Combine(sdk2, "Sdk.targets");
File.WriteAllText(sdkPropsPath2, @"<Project>
<PropertyGroup>
<SdkProps2Imported>true</SdkProps2Imported>
</PropertyGroup>
</Project>");
File.WriteAllText(sdkTargetsPath2, @"<Project>
<PropertyGroup>
<SdkTargets2Imported>true</SdkTargets2Imported>
</PropertyGroup>
</Project>");
TransientTestProjectWithFiles import = env.CreateTestProjectWithFiles(@"<Project Sdk='MSBuildUnitTestSdk2'>
<PropertyGroup>
<MyImportWasImported>true</MyImportWasImported>
</PropertyGroup>
</Project>");
string importPath = Path.GetFullPath(import.ProjectFile);
string content = $@"<Project Sdk='MSBuildUnitTestSdk1'>
<Import Project='{importPath}' />
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
</Project>";
Project project = Project.FromProjectRootElement(
ProjectRootElement.Create(XmlReader.Create(new StringReader(content))),
projectOptions);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
string expected = ObjectModelHelpers.CleanupFileContents(
$@"<?xml version=""1.0"" encoding=""utf-16""?>
<Project>
<!--
============================================================================================================================================
<Import Project=""Sdk.props"" Sdk=""MSBuildUnitTestSdk1"">
This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk1"".
{sdkPropsPath1.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<SdkProps1Imported>true</SdkProps1Imported>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
<!--
============================================================================================================================================
<Import Project=""{importPath.Replace("--", "__")}"">
{importPath.Replace("--", "__")}
============================================================================================================================================
-->
<!--
============================================================================================================================================
<Import Project=""Sdk.props"" Sdk=""MSBuildUnitTestSdk2"">
This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk2"".
{sdkPropsPath2.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<SdkProps2Imported>true</SdkProps2Imported>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
{importPath.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<MyImportWasImported>true</MyImportWasImported>
</PropertyGroup>
<!--
============================================================================================================================================
<Import Project=""Sdk.targets"" Sdk=""MSBuildUnitTestSdk2"">
This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk2"".
{sdkTargetsPath2.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<SdkTargets2Imported>true</SdkTargets2Imported>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
{importPath.Replace("--", "__")}
============================================================================================================================================
-->
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
<PropertyGroup>
<p>v1</p>
</PropertyGroup>
<!--
============================================================================================================================================
<Import Project=""Sdk.targets"" Sdk=""MSBuildUnitTestSdk1"">
This import was added implicitly because the Project element's Sdk attribute specified ""MSBuildUnitTestSdk1"".
{sdkTargetsPath1.Replace("--", "__")}
============================================================================================================================================
-->
<PropertyGroup>
<SdkTargets1Imported>true</SdkTargets1Imported>
</PropertyGroup>
<!--
============================================================================================================================================
</Import>
============================================================================================================================================
-->
</Project>");
Helpers.VerifyAssertLineByLine(expected, writer.ToString());
}
}
/// <summary>
/// Verifies that the Preprocessor works when the import graph contains unevaluated duplicates. This can occur if two projects in
/// two different folders both import "..\dir.props" or "$(Property)". Those values will evaluate to different paths at run time
/// but the preprocessor builds a map of the imports.
/// </summary>
[Fact]
public void DuplicateUnevaluatedImports()
{
ProjectRootElement xml1 = ProjectRootElement.Create("p1");
ProjectRootElement xml2 = ProjectRootElement.Create("p2");
ProjectRootElement.Create("p3");
xml1.AddProperty("Import", "p2");
xml2.AddProperty("Import", "p3");
// These imports are duplicates but for each project will evaluate to separate projects. We expect that to NOT break
// the preprocessor's internal mapping.
//
xml1.AddImport("$(Import)");
xml2.AddImport("$(Import)");
Project project = new Project(xml1);
StringWriter writer = new StringWriter();
project.SaveLogicalProject(writer);
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using Microsoft.SPOT.Platform.Test;
using System.Collections;
namespace Microsoft.SPOT.Platform.Tests
{
public class ArrayListTests : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests");
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
Log.Comment("Cleaning up after the tests");
}
//Test Case Calls
[TestMethod]
public MFTestResults AddAndGetSetItemTest()
{
try
{
ArrayList list = new ArrayList();
list.Add(TestObjects.u1);
list.Add(TestObjects.s1);
list.Add(TestObjects.u2);
list.Add(TestObjects.s2);
list.Add(TestObjects.u4);
list.Add(TestObjects.s4);
list.Add(TestObjects.u8);
list.Add(TestObjects.s8);
list.Add(TestObjects.f4);
list.Add(TestObjects.f8);
list.Add(TestObjects.c2);
list.Add(TestObjects.str);
list.Add(TestObjects.dt);
list.Add(TestObjects.ts);
list.Add(TestObjects.st);
list.Add(TestObjects.cl);
list.Add(TestObjects.o);
list.Add(TestObjects.nul);
list.Add(TestObjects.en);
Assert.AreEqual(TestObjects.u1, list[0]);
Assert.AreEqual(TestObjects.s1, list[1]);
Assert.AreEqual(TestObjects.u2, list[2]);
Assert.AreEqual(TestObjects.s2, list[3]);
Assert.AreEqual(TestObjects.u4, list[4]);
Assert.AreEqual(TestObjects.s4, list[5]);
Assert.AreEqual(TestObjects.u8, list[6]);
Assert.AreEqual(TestObjects.s8, list[7]);
Assert.AreEqual(TestObjects.f4, list[8]);
Assert.AreEqual(TestObjects.f8, list[9]);
Assert.AreEqual(TestObjects.c2, list[10]);
Assert.AreEqual(TestObjects.str, list[11]);
//Assert.AreEqual(TestObjects.dt, list[12]); // Throws CLR_E_WRONG_TYPE exception known bug# 18505
Assert.AreEqual(TestObjects.ts, list[13]);
Assert.AreEqual(TestObjects.st, list[14]);
Assert.AreEqual(TestObjects.cl, list[15]);
Assert.AreEqual(TestObjects.o, list[16]);
Assert.AreEqual(TestObjects.nul, list[17]);
Assert.AreEqual(TestObjects.en, list[18]);
Assert.AreEqual(19, list.Count, "ArrayList.Count is incorrect");
list[0] = list[18];
list[1] = list[17];
list[2] = list[16];
list[3] = list[15];
list[4] = list[14];
list[5] = list[13];
list[6] = list[12];
list[7] = list[11];
list[8] = list[10];
list[9] = TestObjects.f8;
list[10] = TestObjects.f4;
list[11] = TestObjects.s8;
list[12] = TestObjects.u8;
list[13] = TestObjects.s4;
list[14] = TestObjects.u4;
list[15] = TestObjects.s2;
list[16] = TestObjects.u2;
list[17] = TestObjects.s1;
list[18] = TestObjects.u1;
Assert.AreEqual(TestObjects.u1, list[18]);
Assert.AreEqual(TestObjects.s1, list[17]);
Assert.AreEqual(TestObjects.u2, list[16]);
Assert.AreEqual(TestObjects.s2, list[15]);
Assert.AreEqual(TestObjects.u4, list[14]);
Assert.AreEqual(TestObjects.s4, list[13]);
Assert.AreEqual(TestObjects.u8, list[12]);
Assert.AreEqual(TestObjects.s8, list[11]);
Assert.AreEqual(TestObjects.f4, list[10]);
Assert.AreEqual(TestObjects.f8, list[9]);
Assert.AreEqual(TestObjects.c2, list[8]);
Assert.AreEqual(TestObjects.str, list[7]);
//Assert.AreEqual(TestObjects.dt, list[6]); // Throws CLR_E_WRONG_TYPE exception known bug# 18505
Assert.AreEqual(TestObjects.ts, list[5]);
Assert.AreEqual(TestObjects.st, list[4]);
Assert.AreEqual(TestObjects.cl, list[3]);
Assert.AreEqual(TestObjects.o, list[2]);
Assert.AreEqual(TestObjects.nul, list[1]);
Assert.AreEqual(TestObjects.en, list[0]);
Assert.AreEqual(19, list.Count, "ArrayList.Count is incorrect");
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults AddNullTest()
{
try
{
ArrayList list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(null);
}
Assert.AreEqual(20, list.Count, "ArrayList.Count is incorrect");
for (int i = 0; i < 20; i++)
{
Assert.AreEqual(null, list[i]);
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults ClearTest()
{
try
{
ArrayList list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(i.ToString());
}
Assert.AreEqual(20, list.Count, "ArrayList.Count is incorrect");
list.Clear();
Assert.AreEqual(0, list.Count, "ArrayList.Count is incorrect");
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults InsertTest()
{
try
{
ArrayList list = new ArrayList();
for (int i = 1; i <= 10; i++)
{
if (i == 5) continue;
list.Add(i);
}
list.Insert(0, 0);
list.Insert(10, 11);
list.Insert(5, 5);
Assert.AreEqual(12, list.Count, "ArrayList.Count is incorrect");
for (int j = 0; j <= 11; j++)
{
Assert.AreEqual(j, list[j]);
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults RemoveAtTest1()
{
try
{
ArrayList list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(i);
}
list.RemoveAt(19);
list.RemoveAt(0);
list.RemoveAt(4);
Assert.AreEqual(17, list.Count, "ArrayList.Count is incorrect");
int k = 0;
for (int j = 0; j < 20; j++)
{
if (j == 0 || j == 5 || j == 19) continue;
Assert.AreEqual(j, list[k++]);
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults RemoveAtTest2()
{
try
{
ArrayList list = CreateFullList();
int count = list.Count;
for (int i = 0; i < count; i++)
{
list.RemoveAt(0);
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults SetCapacityTest()
{
try
{
ArrayList list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(i);
}
for (int i = 0; i < 15; i++)
{
list.RemoveAt(list.Count - 1);
}
Assert.AreEqual(5, list.Count, "ArrayList.Count is incorrect");
list.Capacity = 5;
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(i, list[i]);
}
list.Capacity = 20;
for (int i = 0; i < 5; i++)
{
Assert.AreEqual(i, list[i]);
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults EnumeratorTest()
{
try
{
ArrayList list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(i);
}
int j = 0;
foreach (int i in list)
{
Assert.AreEqual(j++, i);
}
list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(i.ToString());
}
j = 0;
foreach (String s in list)
{
Assert.AreEqual(j.ToString(), s);
j++;
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
[TestMethod]
public MFTestResults IListTest()
{
try
{
ArrayList list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(i);
}
IList ilist = (IList)list;
for (int i = 0; i < 20; i++)
{
Assert.Equals(i, ilist[i]);
}
list = new ArrayList();
for (int i = 0; i < 20; i++)
{
list.Add(i.ToString());
}
ilist = (IList)list;
for (int i = 0; i < 20; i++)
{
Assert.Equals(i.ToString(), ilist[i]);
}
}
catch (Exception e)
{
Log.Exception("Unexpected exception", e);
return MFTestResults.Fail;
}
return MFTestResults.Pass;
}
/// <summary>
/// Creates an array list that's at capacity
/// </summary>
/// <returns>an ArrayList that is at capacity</returns>
private ArrayList CreateFullList()
{
ArrayList list = new ArrayList();
int capacity = list.Capacity;
for (int i = 0; i < capacity; i++)
{
list.Add(i);
}
Assert.AreEqual(list.Capacity, list.Count);
return list;
}
}
}
| |
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Decorator.Data;
namespace Decorator.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
[Migration("00000000000000_CreateIdentitySchema")]
partial class CreateIdentitySchema
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.0.0-rc2-20901");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b =>
{
b.Property<string>("Id");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Name")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("RoleId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("ClaimType");
b.Property<string>("ClaimValue");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider");
b.Property<string>("ProviderKey");
b.Property<string>("ProviderDisplayName");
b.Property<string>("UserId")
.IsRequired();
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("RoleId");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.HasIndex("UserId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId");
b.Property<string>("LoginProvider");
b.Property<string>("Name");
b.Property<string>("Value");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Decorator.Models.ApplicationUser", b =>
{
b.Property<string>("Id");
b.Property<int>("AccessFailedCount");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken();
b.Property<string>("Email")
.HasAnnotation("MaxLength", 256);
b.Property<bool>("EmailConfirmed");
b.Property<bool>("LockoutEnabled");
b.Property<DateTimeOffset?>("LockoutEnd");
b.Property<string>("NormalizedEmail")
.HasAnnotation("MaxLength", 256);
b.Property<string>("NormalizedUserName")
.HasAnnotation("MaxLength", 256);
b.Property<string>("PasswordHash");
b.Property<string>("PhoneNumber");
b.Property<bool>("PhoneNumberConfirmed");
b.Property<string>("SecurityStamp");
b.Property<bool>("TwoFactorEnabled");
b.Property<string>("UserName")
.HasAnnotation("MaxLength", 256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b =>
{
b.HasOne("Decorator.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b =>
{
b.HasOne("Decorator.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole")
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("Decorator.Models.ApplicationUser")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade);
});
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Commands;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
internal abstract class AbstractSnippetCommandHandler :
ForegroundThreadAffinitizedObject,
ICommandHandler<TabKeyCommandArgs>,
ICommandHandler<BackTabKeyCommandArgs>,
ICommandHandler<ReturnKeyCommandArgs>,
ICommandHandler<EscapeKeyCommandArgs>,
ICommandHandler<InsertSnippetCommandArgs>
{
protected readonly IVsEditorAdaptersFactoryService EditorAdaptersFactoryService;
protected readonly SVsServiceProvider ServiceProvider;
public AbstractSnippetCommandHandler(IVsEditorAdaptersFactoryService editorAdaptersFactoryService, SVsServiceProvider serviceProvider)
{
this.EditorAdaptersFactoryService = editorAdaptersFactoryService;
this.ServiceProvider = serviceProvider;
}
protected abstract AbstractSnippetExpansionClient GetSnippetExpansionClient(ITextView textView, ITextBuffer subjectBuffer);
protected abstract bool IsSnippetExpansionContext(Document document, int startPosition, CancellationToken cancellationToken);
protected abstract void InvokeInsertionUI(ITextView textView, ITextBuffer subjectBuffer, Action nextHandler, bool surroundWith = false);
protected virtual bool TryInvokeSnippetPickerOnQuestionMark(ITextView textView, ITextBuffer textBuffer)
{
return false;
}
public void ExecuteCommand(TabKeyCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
nextHandler();
return;
}
AbstractSnippetExpansionClient snippetExpansionClient;
if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) &&
snippetExpansionClient.TryHandleTab())
{
return;
}
// Insert snippet/show picker only if we don't have a selection: the user probably wants to indent instead
if (args.TextView.Selection.IsEmpty)
{
if (TryHandleTypedSnippet(args.TextView, args.SubjectBuffer))
{
return;
}
if (TryInvokeSnippetPickerOnQuestionMark(args.TextView, args.SubjectBuffer))
{
return;
}
}
nextHandler();
}
public CommandState GetCommandState(TabKeyCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return nextHandler();
}
Workspace workspace;
if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace))
{
return nextHandler();
}
return CommandState.Available;
}
public void ExecuteCommand(ReturnKeyCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
nextHandler();
return;
}
AbstractSnippetExpansionClient snippetExpansionClient;
if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) &&
snippetExpansionClient.TryHandleReturn())
{
return;
}
nextHandler();
}
public CommandState GetCommandState(ReturnKeyCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return nextHandler();
}
Workspace workspace;
if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace))
{
return nextHandler();
}
return CommandState.Available;
}
public void ExecuteCommand(EscapeKeyCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
nextHandler();
return;
}
AbstractSnippetExpansionClient snippetExpansionClient;
if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) &&
snippetExpansionClient.TryHandleEscape())
{
return;
}
nextHandler();
}
public CommandState GetCommandState(EscapeKeyCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return nextHandler();
}
Workspace workspace;
if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace))
{
return nextHandler();
}
return CommandState.Available;
}
public void ExecuteCommand(BackTabKeyCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
nextHandler();
return;
}
AbstractSnippetExpansionClient snippetExpansionClient;
if (args.TextView.Properties.TryGetProperty(typeof(AbstractSnippetExpansionClient), out snippetExpansionClient) &&
snippetExpansionClient.TryHandleBackTab())
{
return;
}
nextHandler();
}
public CommandState GetCommandState(BackTabKeyCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return nextHandler();
}
Workspace workspace;
if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace))
{
return nextHandler();
}
return CommandState.Available;
}
public void ExecuteCommand(InsertSnippetCommandArgs args, Action nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
nextHandler();
return;
}
InvokeInsertionUI(args.TextView, args.SubjectBuffer, nextHandler);
}
public CommandState GetCommandState(InsertSnippetCommandArgs args, Func<CommandState> nextHandler)
{
AssertIsForeground();
if (!AreSnippetsEnabled(args))
{
return nextHandler();
}
Workspace workspace;
if (!Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace))
{
return nextHandler();
}
if (!workspace.CanApplyChange(ApplyChangesKind.ChangeDocument))
{
return nextHandler();
}
return CommandState.Available;
}
protected bool TryHandleTypedSnippet(ITextView textView, ITextBuffer subjectBuffer)
{
AssertIsForeground();
Document document = subjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return false;
}
var currentText = subjectBuffer.AsTextContainer().CurrentText;
var syntaxFactsService = document.Project.LanguageServices.GetService<ISyntaxFactsService>();
var endPositionInSubjectBuffer = textView.GetCaretPoint(subjectBuffer);
if (endPositionInSubjectBuffer == null)
{
return false;
}
var endPosition = endPositionInSubjectBuffer.Value.Position;
var startPosition = endPosition;
// Find the snippet shortcut
while (startPosition > 0)
{
char c = currentText[startPosition - 1];
if (!syntaxFactsService.IsIdentifierPartCharacter(c) && c != '#' && c != '~')
{
break;
}
startPosition--;
}
if (startPosition == endPosition)
{
return false;
}
if (!IsSnippetExpansionContext(document, startPosition, CancellationToken.None))
{
return false;
}
return GetSnippetExpansionClient(textView, subjectBuffer).TryInsertExpansion(startPosition, endPosition);
}
protected bool TryGetExpansionManager(out IVsExpansionManager expansionManager)
{
var textManager = (IVsTextManager2)ServiceProvider.GetService(typeof(SVsTextManager));
if (textManager == null)
{
expansionManager = null;
return false;
}
textManager.GetExpansionManager(out expansionManager);
return expansionManager != null;
}
protected static bool AreSnippetsEnabled(CommandArgs args)
{
Workspace workspace;
return args.SubjectBuffer.GetFeatureOnOffOption(InternalFeatureOnOffOptions.Snippets) &&
// TODO (https://github.com/dotnet/roslyn/issues/5107): enable in interactive
!(Workspace.TryGetWorkspace(args.SubjectBuffer.AsTextContainer(), out workspace) && workspace.Kind == WorkspaceKind.Interactive);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.MSBuild
{
public partial class MSBuildProjectLoader
{
private partial class Worker
{
private readonly struct ResolvedReferences
{
public ImmutableHashSet<ProjectReference> ProjectReferences { get; }
public ImmutableArray<MetadataReference> MetadataReferences { get; }
public ResolvedReferences(ImmutableHashSet<ProjectReference> projectReferences, ImmutableArray<MetadataReference> metadataReferences)
{
ProjectReferences = projectReferences;
MetadataReferences = metadataReferences;
}
}
/// <summary>
/// This type helps produces lists of metadata and project references. Initially, it contains a list of metadata references.
/// As project references are added, the metadata references that match those project references are removed.
/// </summary>
private class ResolvedReferencesBuilder
{
/// <summary>
/// The full list of <see cref="MetadataReference"/>s.
/// </summary>
private readonly ImmutableArray<MetadataReference> _metadataReferences;
/// <summary>
/// A map of every metadata reference file paths to a set of indices whether than file path
/// exists in the list. It is expected that there may be multiple metadata references for the
/// same file path in the case where multiple extern aliases are provided.
/// </summary>
private readonly ImmutableDictionary<string, HashSet<int>> _pathToIndicesMap;
/// <summary>
/// A set of indeces into <see cref="_metadataReferences"/> that are to be removed.
/// </summary>
private readonly HashSet<int> _indicesToRemove;
private readonly ImmutableHashSet<ProjectReference>.Builder _projectReferences;
public ResolvedReferencesBuilder(IEnumerable<MetadataReference> metadataReferences)
{
_metadataReferences = metadataReferences.ToImmutableArray();
_pathToIndicesMap = CreatePathToIndexMap(_metadataReferences);
_indicesToRemove = new HashSet<int>();
_projectReferences = ImmutableHashSet.CreateBuilder<ProjectReference>();
}
private static ImmutableDictionary<string, HashSet<int>> CreatePathToIndexMap(ImmutableArray<MetadataReference> metadataReferences)
{
var builder = ImmutableDictionary.CreateBuilder<string, HashSet<int>>(PathUtilities.Comparer);
for (var index = 0; index < metadataReferences.Length; index++)
{
var filePath = GetFilePath(metadataReferences[index]);
if (filePath != null)
{
builder.MultiAdd(filePath, index);
}
}
return builder.ToImmutable();
}
private static string? GetFilePath(MetadataReference metadataReference)
{
return metadataReference switch
{
PortableExecutableReference portableExecutableReference => portableExecutableReference.FilePath,
UnresolvedMetadataReference unresolvedMetadataReference => unresolvedMetadataReference.Reference,
_ => null,
};
}
public void AddProjectReference(ProjectReference projectReference)
{
_projectReferences.Add(projectReference);
}
public void SwapMetadataReferenceForProjectReference(ProjectReference projectReference, params string?[] possibleMetadataReferencePaths)
{
foreach (var path in possibleMetadataReferencePaths)
{
if (path != null)
{
Remove(path);
}
}
AddProjectReference(projectReference);
}
/// <summary>
/// Returns true if a metadata reference with the given file path is contained within this list.
/// </summary>
public bool Contains(string? filePath)
=> filePath != null
&& _pathToIndicesMap.ContainsKey(filePath);
/// <summary>
/// Removes the metadata reference with the given file path from this list.
/// </summary>
public void Remove(string filePath)
{
if (filePath != null && _pathToIndicesMap.TryGetValue(filePath, out var indices))
{
_indicesToRemove.AddRange(indices);
}
}
public ProjectInfo? SelectProjectInfoByOutput(IEnumerable<ProjectInfo> projectInfos)
{
foreach (var projectInfo in projectInfos)
{
var outputFilePath = projectInfo.OutputFilePath;
var outputRefFilePath = projectInfo.OutputRefFilePath;
if (outputFilePath != null &&
outputRefFilePath != null &&
(Contains(outputFilePath) || Contains(outputRefFilePath)))
{
return projectInfo;
}
}
return null;
}
public ImmutableArray<UnresolvedMetadataReference> GetUnresolvedMetadataReferences()
{
var builder = ImmutableArray.CreateBuilder<UnresolvedMetadataReference>();
foreach (var metadataReference in GetMetadataReferences())
{
if (metadataReference is UnresolvedMetadataReference unresolvedMetadataReference)
{
builder.Add(unresolvedMetadataReference);
}
}
return builder.ToImmutable();
}
private ImmutableArray<MetadataReference> GetMetadataReferences()
{
var builder = ImmutableArray.CreateBuilder<MetadataReference>();
// used to eliminate duplicates
var _ = PooledHashSet<MetadataReference>.GetInstance(out var set);
for (var index = 0; index < _metadataReferences.Length; index++)
{
var reference = _metadataReferences[index];
if (!_indicesToRemove.Contains(index) && set.Add(reference))
{
builder.Add(reference);
}
}
return builder.ToImmutable();
}
private ImmutableHashSet<ProjectReference> GetProjectReferences()
=> _projectReferences.ToImmutable();
public ResolvedReferences ToResolvedReferences()
=> new(GetProjectReferences(), GetMetadataReferences());
}
private async Task<ResolvedReferences> ResolveReferencesAsync(ProjectId id, ProjectFileInfo projectFileInfo, CommandLineArguments commandLineArgs, CancellationToken cancellationToken)
{
// First, gather all of the metadata references from the command-line arguments.
var resolvedMetadataReferences = commandLineArgs.ResolveMetadataReferences(
new WorkspaceMetadataFileReferenceResolver(
metadataService: GetWorkspaceService<IMetadataService>(),
pathResolver: new RelativePathResolver(commandLineArgs.ReferencePaths, commandLineArgs.BaseDirectory)));
var builder = new ResolvedReferencesBuilder(resolvedMetadataReferences);
var projectDirectory = Path.GetDirectoryName(projectFileInfo.FilePath);
RoslynDebug.AssertNotNull(projectDirectory);
// Next, iterate through all project references in the file and create project references.
foreach (var projectFileReference in projectFileInfo.ProjectReferences)
{
var aliases = projectFileReference.Aliases;
if (_pathResolver.TryGetAbsoluteProjectPath(projectFileReference.Path, baseDirectory: projectDirectory, _discoveredProjectOptions.OnPathFailure, out var projectReferencePath))
{
// The easiest case is to add a reference to a project we already know about.
if (TryAddReferenceToKnownProject(id, projectReferencePath, aliases, builder))
{
continue;
}
// If we don't know how to load a project (that is, it's not a language we support), we can still
// attempt to verify that its output exists on disk and is included in our set of metadata references.
// If it is, we'll just leave it in place.
if (!IsProjectLoadable(projectReferencePath) &&
await VerifyUnloadableProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
// If metadata is preferred, see if the project reference's output exists on disk and is included
// in our metadata references. If it is, don't create a project reference; we'll just use the metadata.
if (_preferMetadataForReferencesOfDiscoveredProjects &&
await VerifyProjectOutputExistsAsync(projectReferencePath, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
// Finally, we'll try to load and reference the project.
if (await TryLoadAndAddReferenceAsync(id, projectReferencePath, aliases, builder, cancellationToken).ConfigureAwait(false))
{
continue;
}
}
// We weren't able to handle this project reference, so add it without further processing.
var unknownProjectId = _projectMap.GetOrCreateProjectId(projectFileReference.Path);
var newProjectReference = CreateProjectReference(from: id, to: unknownProjectId, aliases);
builder.AddProjectReference(newProjectReference);
}
// Are there still any unresolved metadata references? If so, remove them and report diagnostics.
foreach (var unresolvedMetadataReference in builder.GetUnresolvedMetadataReferences())
{
var filePath = unresolvedMetadataReference.Reference;
builder.Remove(filePath);
_diagnosticReporter.Report(new ProjectDiagnostic(
WorkspaceDiagnosticKind.Warning,
string.Format(WorkspaceMSBuildResources.Unresolved_metadata_reference_removed_from_project_0, filePath),
id));
}
return builder.ToResolvedReferences();
}
private async Task<bool> TryLoadAndAddReferenceAsync(ProjectId id, string projectReferencePath, ImmutableArray<string> aliases, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
var projectReferenceInfos = await LoadProjectInfosFromPathAsync(projectReferencePath, _discoveredProjectOptions, cancellationToken).ConfigureAwait(false);
if (projectReferenceInfos.IsEmpty)
{
return false;
}
// Find the project reference info whose output we have a metadata reference for.
ProjectInfo? projectReferenceInfo = null;
foreach (var info in projectReferenceInfos)
{
var outputFilePath = info.OutputFilePath;
var outputRefFilePath = info.OutputRefFilePath;
if (outputFilePath != null &&
outputRefFilePath != null &&
(builder.Contains(outputFilePath) || builder.Contains(outputRefFilePath)))
{
projectReferenceInfo = info;
break;
}
}
if (projectReferenceInfo is null)
{
// We didn't find the project reference info that matches any of our metadata references.
// In this case, we'll go ahead and use the first project reference info that was found,
// but report a warning because this likely means that either a metadata reference path
// or a project output path is incorrect.
projectReferenceInfo = projectReferenceInfos[0];
_diagnosticReporter.Report(new ProjectDiagnostic(
WorkspaceDiagnosticKind.Warning,
string.Format(WorkspaceMSBuildResources.Found_project_reference_without_a_matching_metadata_reference_0, projectReferencePath),
id));
}
if (!ProjectReferenceExists(to: id, from: projectReferenceInfo))
{
var newProjectReference = CreateProjectReference(from: id, to: projectReferenceInfo.Id, aliases);
builder.SwapMetadataReferenceForProjectReference(newProjectReference, projectReferenceInfo.OutputRefFilePath, projectReferenceInfo.OutputFilePath);
}
else
{
// This project already has a reference on us. Don't introduce a circularity by referencing it.
// However, if the project's output doesn't exist on disk, we need to remove from our list of
// metadata references to avoid failures later. Essentially, the concern here is that the metadata
// reference is an UnresolvedMetadataReference, which will throw when we try to create a
// Compilation with it.
var outputRefFilePath = projectReferenceInfo.OutputRefFilePath;
if (outputRefFilePath != null && !File.Exists(outputRefFilePath))
{
builder.Remove(outputRefFilePath);
}
var outputFilePath = projectReferenceInfo.OutputFilePath;
if (outputFilePath != null && !File.Exists(outputFilePath))
{
builder.Remove(outputFilePath);
}
}
// Note that we return true even if we don't actually add a reference due to a circularity because,
// in that case, we've still handled everything.
return true;
}
private bool IsProjectLoadable(string projectPath)
=> _projectFileLoaderRegistry.TryGetLoaderFromProjectPath(projectPath, DiagnosticReportingMode.Ignore, out _);
private async Task<bool> VerifyUnloadableProjectOutputExistsAsync(string projectPath, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
var outputFilePath = await _buildManager.TryGetOutputFilePathAsync(projectPath, cancellationToken).ConfigureAwait(false);
return outputFilePath != null
&& builder.Contains(outputFilePath)
&& File.Exists(outputFilePath);
}
private async Task<bool> VerifyProjectOutputExistsAsync(string projectPath, ResolvedReferencesBuilder builder, CancellationToken cancellationToken)
{
// Note: Load the project, but don't report failures.
var projectFileInfos = await LoadProjectFileInfosAsync(projectPath, DiagnosticReportingOptions.IgnoreAll, cancellationToken).ConfigureAwait(false);
foreach (var projectFileInfo in projectFileInfos)
{
var outputFilePath = projectFileInfo.OutputFilePath;
var outputRefFilePath = projectFileInfo.OutputRefFilePath;
if ((builder.Contains(outputFilePath) && File.Exists(outputFilePath)) ||
(builder.Contains(outputRefFilePath) && File.Exists(outputRefFilePath)))
{
return true;
}
}
return false;
}
private ProjectReference CreateProjectReference(ProjectId from, ProjectId to, ImmutableArray<string> aliases)
{
var newReference = new ProjectReference(to, aliases);
_projectIdToProjectReferencesMap.MultiAdd(from, newReference);
return newReference;
}
private bool ProjectReferenceExists(ProjectId to, ProjectId from)
=> _projectIdToProjectReferencesMap.TryGetValue(from, out var references)
&& references.Contains(pr => pr.ProjectId == to);
private static bool ProjectReferenceExists(ProjectId to, ProjectInfo from)
=> from.ProjectReferences.Any(pr => pr.ProjectId == to);
private bool TryAddReferenceToKnownProject(
ProjectId id,
string projectReferencePath,
ImmutableArray<string> aliases,
ResolvedReferencesBuilder builder)
{
if (_projectMap.TryGetIdsByProjectPath(projectReferencePath, out var projectReferenceIds))
{
foreach (var projectReferenceId in projectReferenceIds)
{
// Don't add a reference if the project already has a reference on us. Otherwise, it will cause a circularity.
if (ProjectReferenceExists(to: id, from: projectReferenceId))
{
return false;
}
var outputRefFilePath = _projectMap.GetOutputRefFilePathById(projectReferenceId);
var outputFilePath = _projectMap.GetOutputFilePathById(projectReferenceId);
if (builder.Contains(outputRefFilePath) ||
builder.Contains(outputFilePath))
{
var newProjectReference = CreateProjectReference(from: id, to: projectReferenceId, aliases);
builder.SwapMetadataReferenceForProjectReference(newProjectReference, outputRefFilePath, outputFilePath);
return true;
}
}
}
return false;
}
}
}
}
| |
using System;
using System.Collections;
namespace Tutor.Production
{
/// <summary>
/// Summary description for ReWrite.
/// </summary>
public interface ProductionRule
{
string str();
}
public class ProAddition : ProductionRule
{
public ArrayList _Terms;
public ProAddition()
{
_Terms = new ArrayList();
}
public ProAddition(ProductionRule a)
{
_Terms = new ArrayList();
_Terms.Add(a);
}
public ProAddition(ProductionRule a, ProductionRule b)
{
_Terms = new ArrayList();
_Terms.Add(a);
_Terms.Add(b);
}
public ProAddition(ProductionRule [] A)
{
_Terms = new ArrayList();
foreach(ProductionRule E in A)
_Terms.Add(E);
}
public string str()
{
string interior = "";
bool first = true;
foreach(ProductionRule E in _Terms)
{
if(!first) interior += "+";
interior += E.str();
first = false;
}
return "(" +interior + ")";
}
}
public class ProMultiplication : ProductionRule
{
public ArrayList _Factors;
public ProMultiplication()
{
_Factors = new ArrayList();
}
public ProMultiplication(ProductionRule a)
{
_Factors = new ArrayList();
_Factors.Add(a);
}
public ProMultiplication(ProductionRule a, ProductionRule b)
{
_Factors = new ArrayList();
_Factors.Add(a);
_Factors.Add(b);
}
public ProMultiplication(ProductionRule [] A)
{
_Factors = new ArrayList();
foreach(ProductionRule E in A)
_Factors.Add(E);
}
public string str()
{
string interior = "";
bool first = true;
foreach(ProductionRule E in _Factors)
{
if(!first) interior += "*";
interior += E.str();
first = false;
}
return "(" + interior + ")";
}
}
public class ProValue : ProductionRule
{
public long Value;
public ProValue(long v)
{
Value = v;
}
public string str()
{
return "" + Value + "";
}
};
public class ProConstant : ProductionRule
{
public int Identifier;
public ProConstant(int Ident)
{
Identifier = Ident;
}
public string str()
{
return "<" + Identifier + ">";
}
}
public class ProDivide : ProductionRule
{
public ProductionRule Numerator;
public ProductionRule Denominator;
public ProDivide(ProductionRule n, ProductionRule d)
{
Numerator = n;
Denominator = d;
}
public string str()
{
return "(" + Numerator.str() + ")/(" + Denominator.str() + ")";
}
}
public class ProNegation : ProductionRule
{
public ProductionRule Term;
public ProNegation(ProductionRule t)
{
Term = t;
}
public string str()
{
return "-(" + Term.str() + ")";
}
}
public class ProAbsoluteValue : ProductionRule
{
public ProductionRule Term;
public ProAbsoluteValue(ProductionRule t)
{
Term = t;
}
public string str()
{
return "\\abs{" + Term.str() + "}";
}
}
public class ProEquality : ProductionRule
{
public ProductionRule Left;
public ProductionRule Right;
public ProEquality(ProductionRule l, ProductionRule r)
{
Left = l;
Right = r;
}
public string str()
{
return "(" + Left.str() + ")=(" + Right.str() + ")";
}
public int order() { return 1; }
public void cycle() {}
};
public class ProRoot : ProductionRule
{
public ProductionRule Term;
public ProductionRule Root;
public ProRoot(ProductionRule t, ProductionRule r)
{
Term = t;
Root = r;
}
public string str()
{
return "\\sqrt["+Root.str()+"](" + Term.str() + ")";
}
public int order() { return 1; }
public void cycle() {}
};
public class ProPower : ProductionRule
{
public ProductionRule Base;
public ProductionRule Power;
public ProPower(ProductionRule b, ProductionRule p)
{
Base = b;
Power = p;
}
public string str()
{
return "(" + Base.str() + ")^(" + Power.str() + ")";
}
}
public class ProTree : ProductionRule
{
public string Identifier;
public ProTree(string ident)
{
Identifier = ident;
}
public string str()
{
return "[" + Identifier + "]";
}
}
public class ProVariable : ProductionRule
{
public string Variable;
public ProVariable(string var)
{
Variable = var;
}
public string str()
{
return "" + Variable + "";
}
}
public class ProEval : ProductionRule
{
public ProductionRule Term;
public ProEval(ProductionRule t)
{
Term = t;
}
public string str()
{
return "eval(" + Term.str() + ")";
}
}
public class ProductionParser
{
public static ProductionRule Interpret(SimpleParser.SimpleParseTree SPL)
{
if(SPL.node.Equals("+"))
{
ProAddition add = new ProAddition();
foreach(SimpleParser.SimpleParseTree sub in SPL.children)
{
add._Terms.Add( Interpret(sub) );
}
return add;
}
if(SPL.node.Equals("*"))
{
ProMultiplication mult = new ProMultiplication();
foreach(SimpleParser.SimpleParseTree sub in SPL.children)
{
mult._Factors.Add( Interpret(sub) );
}
return mult;
}
if(SPL.node.Equals("var"))
{
return new ProVariable (((SimpleParser.SimpleParseTree) SPL.children[0] ) .node);
}
if(SPL.node.Equals("^"))
{
return new ProPower(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ));
}
if(SPL.node.Equals("-"))
{
return new ProNegation( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ) );
}
if(SPL.node.Equals("abs"))
{
return new ProAbsoluteValue( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ) );
}
if(SPL.node.Equals("/"))
{
return new ProDivide(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ));
}
if(SPL.node.Equals("root"))
{
return new ProRoot(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ));
}
if(SPL.node.Equals("="))
{
return new ProEquality(Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ), Interpret( ((SimpleParser.SimpleParseTree) SPL.children[1] ) ));
}
if(SPL.node.Equals("c"))
{
return new ProConstant( Int32.Parse(((SimpleParser.SimpleParseTree) SPL.children[0] ) .node) );
}
if(SPL.node.Equals("v"))
{
return new ProValue( Int32.Parse(((SimpleParser.SimpleParseTree) SPL.children[0] ) .node) );
}
if(SPL.node.Equals("eval"))
{
return new ProEval( Interpret( ((SimpleParser.SimpleParseTree) SPL.children[0] ) ) );
}
return new ProTree(SPL.node);
}
public static ProductionRule Parse(string source)
{
SimpleParser.SimpleLexer SL = new SimpleParser.SimpleLexer(source);
SimpleParser.SimpleParseTree SPL = SimpleParser.SimpleParseTree.Parse(SL);
return Interpret(SPL);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Amplified.CSharp.Extensions;
using Amplified.CSharp.Util;
using Xunit;
namespace Amplified.CSharp
{
// ReSharper disable once InconsistentNaming
[SuppressMessage("ReSharper", "CollectionNeverUpdated.Local")]
public class Enumerable__SingleOrNone
{
#region Guards
[Fact]
public void WhenSourceIsNull_ThrowsArgumentNullException()
{
IEnumerable<int> source = null;
Assert.Throws<ArgumentNullException>(() => source.SingleOrNone());
}
[Fact]
public void WithPredicate_WhenSourceIsNull_ThrowsArgumentNullException()
{
IEnumerable<int> source = null;
Assert.Throws<ArgumentNullException>(() => source.SingleOrNone(it => true));
}
[Fact]
public void WithPredicate_WhenPredicateIsNull_ThrowsArgumentNullException()
{
var source = Enumerable.Empty<int>();
Assert.Throws<ArgumentNullException>(() => source.SingleOrNone(null));
}
#endregion
#region Maybe<TSource> SingleOrNone<TSource>()
[Fact]
public void WhenEmpty_ReturnsNone()
{
var source = new HashSet<int>().AsEnumerable();
var result = source.SingleOrNone();
result.MustBeNone();
}
[Fact]
public void WhenOneElement_ReturnsSome()
{
var source = Enumerable.Range(1, 1);
var result = source.SingleOrNone();
var value = result.MustBeSome();
Assert.Equal(1, value);
}
[Fact]
public void WhenTwoElements_ThrowsException()
{
var source = Enumerable.Range(1, 2);
Assert.Throws<InvalidOperationException>(() => source.SingleOrNone());
}
[Fact]
public void WhenEmptyList_ReturnsNone()
{
var source = new List<int>().AsEnumerable();
var result = source.SingleOrNone();
result.MustBeNone();
}
[Fact]
public void WhenOneElementList_ReturnsSome()
{
var source = new List<int> { 1 }.AsEnumerable();
var result = source.SingleOrNone();
var value = result.MustBeSome();
Assert.Equal(1, value);
}
[Fact]
public void WhenTwoElementsList_ThrowsException()
{
var source = new List<int> {1, 2}.AsEnumerable();
Assert.Throws<InvalidOperationException>(() => source.SingleOrNone());
}
#endregion
#region Maybe<TSource> SingleOrNone<TSource>(Func<TSource, bool> predicate)
#region Empty
[Fact]
public void WithTruePredicate_WhenEmpty_ReturnsNone()
{
var source = new HashSet<int>().AsEnumerable();
var result = source.SingleOrNone(it => true);
result.MustBeNone();
}
[Fact]
public void WithFalsePredicate_WhenEmpty_ReturnsNone()
{
var source = new HashSet<int>().AsEnumerable();
var result = source.SingleOrNone(it => false);
result.MustBeNone();
}
[Fact]
public void WithPredicate_WhenEmpty_DoesNotInvokePredicate()
{
var rec = new Recorder();
var source = new HashSet<int>().AsEnumerable();
var result = source.SingleOrNone(rec.Record((int it) => false));
result.MustBeNone();
rec.MustHaveExactly(0.Invocations());
}
#endregion
#region One Element
[Fact]
public void WithTruePredicate_WhenOneElement_ReturnsSome()
{
var source = Enumerable.Range(0, 1);
var result = source.SingleOrNone(it => true);
result.MustBeSome();
}
[Fact]
public void WithFalsePredicate_WhenOneElement_ReturnsNone()
{
var source = Enumerable.Range(0, 1);
var result = source.SingleOrNone(it => false);
result.MustBeNone();
}
[Fact]
public void WithPredicate_WhenOneElement_DoesNotInvokePredicate()
{
var rec = new Recorder();
var source = Enumerable.Range(0, 1);
var result = source.SingleOrNone(rec.Record((int it) => true));
result.MustBeSome();
rec.MustHaveExactly(1.Invocations());
}
#endregion
#region Two Elements
[Fact]
public void WithTruePredicate_WhenTwoElements_ThrowsException()
{
var source = Enumerable.Range(0, 2);
Assert.Throws<InvalidOperationException>(() => source.SingleOrNone(it => true));
}
[Fact]
public void WithFalsePredicate_WhenTwoElements_ReturnsNone()
{
var source = Enumerable.Range(0, 2);
var result = source.SingleOrNone(it => false);
result.MustBeNone();
}
#endregion
#region Three Elements
[Fact]
public void WithPredicateMatchingFirst_WhenThreeElements_ReturnsSome()
{
var source = Enumerable.Range(0, 3);
var result = source.SingleOrNone(it => it == 0);
var value = result.MustBeSome();
Assert.Equal(0, value);
}
[Fact]
public void WithPredicateMatchingMiddle_WhenThreeElements_ReturnsSome()
{
var source = Enumerable.Range(0, 3);
var result = source.SingleOrNone(it => it == 1);
var value = result.MustBeSome();
Assert.Equal(1, value);
}
[Fact]
public void WithPredicateMatchingLast_WhenThreeElements_ReturnsSome()
{
var source = Enumerable.Range(0, 3);
var result = source.SingleOrNone(it => it == 2);
var value = result.MustBeSome();
Assert.Equal(2, value);
}
[Fact]
public void WithPredicate_WhenThreeElements_InvokesPredicateTwoTimes()
{
var rec = new Recorder();
var source = Enumerable.Range(0, 3);
Assert.Throws<InvalidOperationException>(() => source.SingleOrNone(rec.Record((int it) => true)));
rec.MustHaveExactly(2.Invocations());
}
#endregion
#endregion
}
}
| |
/*
*
* (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.Globalization;
using System.Linq;
using System.Threading;
using ASC.Common.Data;
using ASC.Common.Data.Sql;
using ASC.Common.Data.Sql.Expressions;
using ASC.Common.Logging;
using ASC.Core;
using ASC.Core.Billing;
using ASC.Core.Common.Billing;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Notify;
using ASC.Notify.Model;
using ASC.Notify.Patterns;
using ASC.Web.Core.Helpers;
using ASC.Web.Core.WhiteLabel;
using ASC.Web.Studio.PublicResources;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Studio.Core.Notify
{
public class StudioPeriodicNotify
{
public static void SendSaasLetters(INotifyClient client, string senderName, DateTime scheduleDate)
{
var log = LogManager.GetLogger("ASC.Notify");
var nowDate = scheduleDate.Date;
log.Info("Start SendSaasTariffLetters");
var activeTenants = CoreContext.TenantManager.GetTenants().ToList();
if (activeTenants.Count <= 0)
{
log.Info("End SendSaasTariffLetters");
return;
}
foreach (var tenant in activeTenants)
{
try
{
CoreContext.TenantManager.SetCurrentTenant(tenant.TenantId);
var tariff = CoreContext.PaymentManager.GetTariff(tenant.TenantId);
var quota = CoreContext.TenantManager.GetTenantQuota(tenant.TenantId);
var createdDate = tenant.CreatedDateTime.Date;
var dueDateIsNotMax = tariff.DueDate != DateTime.MaxValue;
var dueDate = tariff.DueDate.Date;
var delayDueDateIsNotMax = tariff.DelayDueDate != DateTime.MaxValue;
var delayDueDate = tariff.DelayDueDate.Date;
INotifyAction action = null;
var paymentMessage = true;
var toadmins = false;
var tousers = false;
var toowner = false;
var coupon = string.Empty;
Func<string> greenButtonText = () => string.Empty;
Func<string> blueButtonText = () => WebstudioNotifyPatternResource.ButtonRequestCallButton;
var greenButtonUrl = string.Empty;
Func<string> tableItemText1 = () => string.Empty;
Func<string> tableItemText2 = () => string.Empty;
Func<string> tableItemText3 = () => string.Empty;
Func<string> tableItemText4 = () => string.Empty;
Func<string> tableItemText5 = () => string.Empty;
Func<string> tableItemText6 = () => string.Empty;
Func<string> tableItemText7 = () => string.Empty;
var tableItemUrl1 = string.Empty;
var tableItemUrl2 = string.Empty;
var tableItemUrl3 = string.Empty;
var tableItemUrl4 = string.Empty;
var tableItemUrl5 = string.Empty;
var tableItemUrl6 = string.Empty;
var tableItemUrl7 = string.Empty;
var tableItemImg1 = string.Empty;
var tableItemImg2 = string.Empty;
var tableItemImg3 = string.Empty;
var tableItemImg4 = string.Empty;
var tableItemImg5 = string.Empty;
var tableItemImg6 = string.Empty;
var tableItemImg7 = string.Empty;
Func<string> tableItemComment1 = () => string.Empty;
Func<string> tableItemComment2 = () => string.Empty;
Func<string> tableItemComment3 = () => string.Empty;
Func<string> tableItemComment4 = () => string.Empty;
Func<string> tableItemComment5 = () => string.Empty;
Func<string> tableItemComment6 = () => string.Empty;
Func<string> tableItemComment7 = () => string.Empty;
Func<string> tableItemLearnMoreText1 = () => string.Empty;
Func<string> tableItemLearnMoreText2 = () => string.Empty;
Func<string> tableItemLearnMoreText3 = () => string.Empty;
Func<string> tableItemLearnMoreText4 = () => string.Empty;
Func<string> tableItemLearnMoreText5 = () => string.Empty;
Func<string> tableItemLearnMoreText6 = () => string.Empty;
Func<string> tableItemLearnMoreText7 = () => string.Empty;
var tableItemLearnMoreUrl1 = string.Empty;
var tableItemLearnMoreUrl2 = string.Empty;
var tableItemLearnMoreUrl3 = string.Empty;
var tableItemLearnMoreUrl4 = string.Empty;
var tableItemLearnMoreUrl5 = string.Empty;
var tableItemLearnMoreUrl6 = string.Empty;
var tableItemLearnMoreUrl7 = string.Empty;
if (quota.Free)
{
#region Free tariff every 2 months during 1 year
if (createdDate.AddMonths(2) == nowDate || createdDate.AddMonths(4) == nowDate || createdDate.AddMonths(6) == nowDate || createdDate.AddMonths(8) == nowDate || createdDate.AddMonths(10) == nowDate || createdDate.AddMonths(12) == nowDate)
{
action = Actions.SaasAdminPaymentWarningEvery2MonthsV115;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonUseDiscount;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx");
}
#endregion
}
else if (quota.Trial)
{
#region After registration letters
#region 1 days after registration to admins SAAS TRIAL
if (createdDate.AddDays(1) == nowDate)
{
action = Actions.SaasAdminModulesV115;
paymentMessage = false;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccessYouWebOffice;
greenButtonUrl = String.Format("{0}/", CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'));
}
#endregion
#region 4 days after registration to admins SAAS TRIAL
else if (createdDate.AddDays(4) == nowDate)
{
action = Actions.SaasAdminComfortTipsV115;
paymentMessage = false;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonUseDiscount;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx");
}
#endregion
#region 7 days after registration to admins and users SAAS TRIAL
else if (createdDate.AddDays(7) == nowDate)
{
action = Actions.SaasAdminUserDocsTipsV115;
paymentMessage = false;
toadmins = true;
tousers = true;
tableItemImg1 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-formatting-100.png");
tableItemText1 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_formatting_hdr;
tableItemComment1 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_formatting;
if (!CoreContext.Configuration.CustomMode)
{
tableItemLearnMoreUrl1 = StudioNotifyHelper.Helplink + "/onlyoffice-editors/index.aspx";
tableItemLearnMoreText1 = () => WebstudioNotifyPatternResource.LinkLearnMore;
}
tableItemImg2 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-share-100.png");
tableItemText2 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_share_hdr;
tableItemComment2 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_share;
tableItemImg3 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-coediting-100.png");
tableItemText3 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_coediting_hdr;
tableItemComment3 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_coediting;
tableItemImg4 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-review-100.png");
tableItemText4 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_review_hdr;
tableItemComment4 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_review;
tableItemImg5 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-modules-100.png");
tableItemText5 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_contentcontrols_hdr;
tableItemComment5 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_contentcontrols;
tableItemImg6 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-customize-100.png");
tableItemText6 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_spreadsheets_hdr;
tableItemComment6 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_spreadsheets;
tableItemImg7 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-attach-100.png");
tableItemText7 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_differences_hdr;
tableItemComment7 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_differences;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccessYouWebOffice;
greenButtonUrl = String.Format("{0}/Products/Files/", CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'));
}
#endregion
#region 14 days after registration to admins and users SAAS TRIAL
else if (createdDate.AddDays(14) == nowDate)
{
action = Actions.SaasAdminUserAppsTipsV115;
paymentMessage = false;
toadmins = true;
tousers = true;
}
#endregion
#endregion
#region Trial warning letters
#region 5 days before SAAS TRIAL ends to admins
else if (!CoreContext.Configuration.CustomMode && dueDateIsNotMax && dueDate.AddDays(-5) == nowDate)
{
toadmins = true;
action = Actions.SaasAdminTrialWarningBefore5V115;
coupon = "PortalCreation10%";
if (string.IsNullOrEmpty(coupon))
{
try
{
log.InfoFormat("start CreateCoupon to {0}", tenant.TenantAlias);
coupon = SetupInfo.IsSecretEmail(CoreContext.UserManager.GetUsers(tenant.OwnerId).Email)
? tenant.TenantAlias
: CouponManager.CreateCoupon();
log.InfoFormat("end CreateCoupon to {0} coupon = {1}", tenant.TenantAlias, coupon);
}
catch (AggregateException ae)
{
foreach (var ex in ae.InnerExceptions)
log.Error(ex);
}
catch (Exception ex)
{
log.Error(ex);
}
}
greenButtonText = () => WebstudioNotifyPatternResource.ButtonUseDiscount;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx");
}
#endregion
#region SAAS TRIAL expires today to admins
else if (dueDate == nowDate)
{
action = Actions.SaasAdminTrialWarningV115;
toadmins = true;
}
#endregion
#region 1 day after SAAS TRIAL expired to admins
if (dueDateIsNotMax && dueDate.AddDays(1) == nowDate)
{
action = Actions.SaasAdminTrialWarningAfter1V115;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonRenewNow;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx");
}
#endregion
#region 6 months after SAAS TRIAL expired
else if (dueDateIsNotMax && dueDate.AddMonths(6) == nowDate)
{
action = Actions.SaasAdminTrialWarningAfterHalfYearV115;
toowner = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonLeaveFeedback;
var owner = CoreContext.UserManager.GetUsers(tenant.OwnerId);
greenButtonUrl = SetupInfo.TeamlabSiteRedirect + "/remove-portal-feedback-form.aspx#" +
System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes("{\"firstname\":\"" + owner.FirstName +
"\",\"lastname\":\"" + owner.LastName +
"\",\"alias\":\"" + tenant.TenantAlias +
"\",\"email\":\"" + owner.Email + "\"}")));
}
else if (dueDateIsNotMax && dueDate.AddMonths(6).AddDays(7) <= nowDate)
{
CoreContext.TenantManager.RemoveTenant(tenant.TenantId, true);
if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
{
ApiSystemHelper.RemoveTenantFromCache(tenant.TenantAlias);
}
}
#endregion
#endregion
}
else if (tariff.State >= TariffState.Paid)
{
#region Payment warning letters
#region 6 months after SAAS PAID expired
if (tariff.State == TariffState.NotPaid && dueDateIsNotMax && dueDate.AddMonths(6) == nowDate)
{
action = Actions.SaasAdminTrialWarningAfterHalfYearV115;
toowner = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonLeaveFeedback;
var owner = CoreContext.UserManager.GetUsers(tenant.OwnerId);
greenButtonUrl = SetupInfo.TeamlabSiteRedirect + "/remove-portal-feedback-form.aspx#" +
System.Web.HttpUtility.UrlEncode(Convert.ToBase64String(
System.Text.Encoding.UTF8.GetBytes("{\"firstname\":\"" + owner.FirstName +
"\",\"lastname\":\"" + owner.LastName +
"\",\"alias\":\"" + tenant.TenantAlias +
"\",\"email\":\"" + owner.Email + "\"}")));
}
else if (tariff.State == TariffState.NotPaid && dueDateIsNotMax && dueDate.AddMonths(6).AddDays(7) <= nowDate)
{
CoreContext.TenantManager.RemoveTenant(tenant.TenantId, true);
if (!String.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
{
ApiSystemHelper.RemoveTenantFromCache(tenant.TenantAlias);
}
}
#endregion
#endregion
}
if (action == null) continue;
var users = toowner
? new List<UserInfo> { CoreContext.UserManager.GetUsers(tenant.OwnerId) }
: StudioNotifyHelper.GetRecipients(toadmins, tousers, false);
foreach (var u in users.Where(u => paymentMessage || StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify)))
{
var culture = string.IsNullOrEmpty(u.CultureName) ? tenant.GetCulture() : u.GetCulture();
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
var rquota = TenantExtra.GetRightQuota() ?? TenantQuota.Default;
client.SendNoticeToAsync(
action,
null,
new[] { StudioNotifyHelper.ToRecipient(u.ID) },
new[] { senderName },
null,
new TagValue(Tags.UserName, u.FirstName.HtmlEncode()),
new TagValue(Tags.PricingPage, CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx")),
new TagValue(Tags.ActiveUsers, CoreContext.UserManager.GetUsers().Count()),
new TagValue(Tags.Price, rquota.Price),
new TagValue(Tags.PricePeriod, rquota.Year3 ? UserControlsCommonResource.TariffPerYear3 : rquota.Year ? UserControlsCommonResource.TariffPerYear : UserControlsCommonResource.TariffPerMonth),
new TagValue(Tags.DueDate, dueDate.ToLongDateString()),
new TagValue(Tags.DelayDueDate, (delayDueDateIsNotMax ? delayDueDate : dueDate).ToLongDateString()),
TagValues.BlueButton(blueButtonText, "http://www.onlyoffice.com/call-back-form.aspx"),
TagValues.GreenButton(greenButtonText, greenButtonUrl),
TagValues.TableTop(),
TagValues.TableItem(1, tableItemText1, tableItemUrl1, tableItemImg1, tableItemComment1, tableItemLearnMoreText1, tableItemLearnMoreUrl1),
TagValues.TableItem(2, tableItemText2, tableItemUrl2, tableItemImg2, tableItemComment2, tableItemLearnMoreText2, tableItemLearnMoreUrl2),
TagValues.TableItem(3, tableItemText3, tableItemUrl3, tableItemImg3, tableItemComment3, tableItemLearnMoreText3, tableItemLearnMoreUrl3),
TagValues.TableItem(4, tableItemText4, tableItemUrl4, tableItemImg4, tableItemComment4, tableItemLearnMoreText4, tableItemLearnMoreUrl4),
TagValues.TableItem(5, tableItemText5, tableItemUrl5, tableItemImg5, tableItemComment5, tableItemLearnMoreText5, tableItemLearnMoreUrl5),
TagValues.TableItem(6, tableItemText6, tableItemUrl6, tableItemImg6, tableItemComment6, tableItemLearnMoreText6, tableItemLearnMoreUrl6),
TagValues.TableItem(7, tableItemText7, tableItemUrl7, tableItemImg7, tableItemComment7, tableItemLearnMoreText7, tableItemLearnMoreUrl7),
TagValues.TableBottom(),
new TagValue(CommonTags.Footer, u.IsAdmin() ? "common" : "social"),
new TagValue(Tags.Coupon, coupon));
}
}
catch (Exception err)
{
log.Error(err);
}
}
log.Info("End SendSaasTariffLetters");
}
public static void SendEnterpriseLetters(INotifyClient client, string senderName, DateTime scheduleDate)
{
var log = LogManager.GetLogger("ASC.Notify");
var nowDate = scheduleDate.Date;
const string dbid = "webstudio";
log.Info("Start SendTariffEnterpriseLetters");
var defaultRebranding = MailWhiteLabelSettings.Instance.IsDefault;
var activeTenants = CoreContext.TenantManager.GetTenants();
if (activeTenants.Count <= 0)
{
log.Info("End SendTariffEnterpriseLetters");
return;
}
foreach (var tenant in activeTenants)
{
try
{
CoreContext.TenantManager.SetCurrentTenant(tenant.TenantId);
var tariff = CoreContext.PaymentManager.GetTariff(tenant.TenantId);
var quota = CoreContext.TenantManager.GetTenantQuota(tenant.TenantId);
var createdDate = tenant.CreatedDateTime.Date;
var actualEndDate = (tariff.DueDate != DateTime.MaxValue ? tariff.DueDate : tariff.LicenseDate);
var dueDateIsNotMax = actualEndDate != DateTime.MaxValue;
var dueDate = actualEndDate.Date;
var delayDueDateIsNotMax = tariff.DelayDueDate != DateTime.MaxValue;
var delayDueDate = tariff.DelayDueDate.Date;
INotifyAction action = null;
var paymentMessage = true;
var toadmins = false;
var tousers = false;
Func<string> greenButtonText = () => string.Empty;
Func<string> blueButtonText = () => WebstudioNotifyPatternResource.ButtonRequestCallButton;
var greenButtonUrl = string.Empty;
Func<string> tableItemText1 = () => string.Empty;
Func<string> tableItemText2 = () => string.Empty;
Func<string> tableItemText3 = () => string.Empty;
Func<string> tableItemText4 = () => string.Empty;
Func<string> tableItemText5 = () => string.Empty;
Func<string> tableItemText6 = () => string.Empty;
Func<string> tableItemText7 = () => string.Empty;
var tableItemUrl1 = string.Empty;
var tableItemUrl2 = string.Empty;
var tableItemUrl3 = string.Empty;
var tableItemUrl4 = string.Empty;
var tableItemUrl5 = string.Empty;
var tableItemUrl6 = string.Empty;
var tableItemUrl7 = string.Empty;
var tableItemImg1 = string.Empty;
var tableItemImg2 = string.Empty;
var tableItemImg3 = string.Empty;
var tableItemImg4 = string.Empty;
var tableItemImg5 = string.Empty;
var tableItemImg6 = string.Empty;
var tableItemImg7 = string.Empty;
Func<string> tableItemComment1 = () => string.Empty;
Func<string> tableItemComment2 = () => string.Empty;
Func<string> tableItemComment3 = () => string.Empty;
Func<string> tableItemComment4 = () => string.Empty;
Func<string> tableItemComment5 = () => string.Empty;
Func<string> tableItemComment6 = () => string.Empty;
Func<string> tableItemComment7 = () => string.Empty;
Func<string> tableItemLearnMoreText1 = () => string.Empty;
Func<string> tableItemLearnMoreText2 = () => string.Empty;
Func<string> tableItemLearnMoreText3 = () => string.Empty;
Func<string> tableItemLearnMoreText4 = () => string.Empty;
Func<string> tableItemLearnMoreText5 = () => string.Empty;
Func<string> tableItemLearnMoreText6 = () => string.Empty;
Func<string> tableItemLearnMoreText7 = () => string.Empty;
var tableItemLearnMoreUrl1 = string.Empty;
var tableItemLearnMoreUrl2 = string.Empty;
var tableItemLearnMoreUrl3 = string.Empty;
var tableItemLearnMoreUrl4 = string.Empty;
var tableItemLearnMoreUrl5 = string.Empty;
var tableItemLearnMoreUrl6 = string.Empty;
var tableItemLearnMoreUrl7 = string.Empty;
if (quota.Trial && defaultRebranding)
{
#region After registration letters
#region 1 day after registration to admins ENTERPRISE TRIAL + defaultRebranding
if (createdDate.AddDays(1) == nowDate)
{
action = Actions.EnterpriseAdminCustomizePortalV10;
paymentMessage = false;
toadmins = true;
tableItemImg1 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-brand-100.png");
tableItemText1 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_brand_hdr;
tableItemComment1 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_brand;
tableItemImg2 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-regional-100.png");
tableItemText2 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_regional_hdr;
tableItemComment2 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_regional;
tableItemImg3 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-customize-100.png");
tableItemText3 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_customize_hdr;
tableItemComment3 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_customize;
tableItemImg4 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-modules-100.png");
tableItemText4 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_modules_hdr;
tableItemComment4 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_modules;
tableItemImg5 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-3rdparty-100.png");
tableItemText5 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_3rdparty_hdr;
tableItemComment5 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_3rdparty;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonConfigureRightNow;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetAdministration(ManagementType.General));
}
#endregion
#region 4 days after registration to admins ENTERPRISE TRIAL + only 1 user + defaultRebranding
else if (createdDate.AddDays(4) == nowDate && CoreContext.UserManager.GetUsers().Count() == 1)
{
action = Actions.EnterpriseAdminInviteTeammatesV10;
paymentMessage = false;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonInviteRightNow;
greenButtonUrl = String.Format("{0}/Products/People/", CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'));
}
#endregion
#region 5 days after registration to admins ENTERPRISE TRAIL + without activity in 1 or more days + defaultRebranding
else if (createdDate.AddDays(5) == nowDate)
{
List<DateTime> datesWithActivity;
var query = new SqlQuery("feed_aggregate")
.Select(new SqlExp("cast(created_date as date) as short_date"))
.Where("tenant", CoreContext.TenantManager.GetCurrentTenant().TenantId)
.Where(Exp.Le("created_date", nowDate.AddDays(-1)))
.GroupBy("short_date");
using (var db = DbManager.FromHttpContext(dbid))
{
datesWithActivity = db
.ExecuteList(query)
.ConvertAll(r => Convert.ToDateTime(r[0]));
}
if (datesWithActivity.Count < 5)
{
action = Actions.EnterpriseAdminWithoutActivityV10;
paymentMessage = false;
toadmins = true;
}
}
#endregion
#region 7 days after registration to admins and users ENTERPRISE TRIAL + defaultRebranding
else if (createdDate.AddDays(7) == nowDate)
{
action = Actions.EnterpriseAdminUserDocsTipsV10;
paymentMessage = false;
toadmins = true;
tousers = true;
tableItemImg1 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-formatting-100.png");
tableItemText1 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_formatting_hdr;
tableItemComment1 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_formatting;
if (!CoreContext.Configuration.CustomMode)
{
tableItemLearnMoreUrl1 = StudioNotifyHelper.Helplink + "/onlyoffice-editors/index.aspx";
tableItemLearnMoreText1 = () => WebstudioNotifyPatternResource.LinkLearnMore;
}
tableItemImg2 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-share-100.png");
tableItemText2 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_share_hdr;
tableItemComment2 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_share;
tableItemImg3 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-coediting-100.png");
tableItemText3 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_coediting_hdr;
tableItemComment3 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_coediting;
tableItemImg4 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-review-100.png");
tableItemText4 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_review_hdr;
tableItemComment4 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_review;
tableItemImg5 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-3rdparty-100.png");
tableItemText5 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_3rdparty_hdr;
tableItemComment5 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_3rdparty;
tableItemImg6 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-attach-100.png");
tableItemText6 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_attach_hdr;
tableItemComment6 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_attach;
tableItemImg7 = StudioNotifyHelper.GetNotificationImageUrl("tips-documents-apps-100.png");
tableItemText7 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_apps_hdr;
tableItemComment7 = () => WebstudioNotifyPatternResource.pattern_saas_admin_user_docs_tips_v115_item_apps;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonAccessYouWebOffice;
greenButtonUrl = String.Format("{0}/Products/Files/", CommonLinkUtility.GetFullAbsolutePath("~").TrimEnd('/'));
}
#endregion
#region 21 days after registration to admins and users ENTERPRISE TRIAL + defaultRebranding
else if (createdDate.AddDays(21) == nowDate)
{
action = Actions.EnterpriseAdminUserAppsTipsV10;
paymentMessage = false;
toadmins = true;
tousers = true;
}
#endregion
#endregion
#region Trial warning letters
#region 7 days before ENTERPRISE TRIAL ends to admins + defaultRebranding
else if (dueDateIsNotMax && dueDate.AddDays(-7) == nowDate)
{
action = Actions.EnterpriseAdminTrialWarningBefore7V10;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonSelectPricingPlans;
greenButtonUrl = "http://www.onlyoffice.com/enterprise-edition.aspx";
}
#endregion
#region ENTERPRISE TRIAL expires today to admins + defaultRebranding
else if (dueDate == nowDate)
{
action = Actions.EnterpriseAdminTrialWarningV10;
toadmins = true;
}
#endregion
#endregion
}
else if (quota.Trial && !defaultRebranding)
{
#region After registration letters
#region 1 day after registration to admins ENTERPRISE TRIAL + !defaultRebranding
if (createdDate.AddDays(1) == nowDate)
{
action = Actions.EnterpriseWhitelabelAdminCustomizePortalV10;
paymentMessage = false;
toadmins = true;
tableItemImg1 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-brand-100.png");
tableItemText1 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_brand_hdr;
tableItemComment1 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_brand;
tableItemImg2 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-regional-100.png");
tableItemText2 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_regional_hdr;
tableItemComment2 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_regional;
tableItemImg3 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-customize-100.png");
tableItemText3 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_customize_hdr;
tableItemComment3 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_customize;
tableItemImg4 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-modules-100.png");
tableItemText4 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_modules_hdr;
tableItemComment4 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_modules;
if (!CoreContext.Configuration.CustomMode)
{
tableItemImg5 = StudioNotifyHelper.GetNotificationImageUrl("tips-customize-3rdparty-100.png");
tableItemText5 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_3rdparty_hdr;
tableItemComment5 = () => WebstudioNotifyPatternResource.pattern_enterprise_admin_customize_portal_v10_item_3rdparty;
}
greenButtonText = () => WebstudioNotifyPatternResource.ButtonConfigureRightNow;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetAdministration(ManagementType.General));
}
#endregion
#endregion
}
else if (tariff.State == TariffState.Paid)
{
#region Payment warning letters
#region 7 days before ENTERPRISE PAID expired to admins
if (dueDateIsNotMax && dueDate.AddDays(-7) == nowDate)
{
action = defaultRebranding
? Actions.EnterpriseAdminPaymentWarningBefore7V10
: Actions.EnterpriseWhitelabelAdminPaymentWarningBefore7V10;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonSelectPricingPlans;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx");
}
#endregion
#region ENTERPRISE PAID expires today to admins
else if (dueDate == nowDate)
{
action = defaultRebranding
? Actions.EnterpriseAdminPaymentWarningV10
: Actions.EnterpriseWhitelabelAdminPaymentWarningV10;
toadmins = true;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonSelectPricingPlans;
greenButtonUrl = CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx");
}
#endregion
#endregion
}
if (action == null) continue;
var users = StudioNotifyHelper.GetRecipients(toadmins, tousers, false);
foreach (var u in users.Where(u => paymentMessage || StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify)))
{
var culture = string.IsNullOrEmpty(u.CultureName) ? tenant.GetCulture() : u.GetCulture();
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
var rquota = TenantExtra.GetRightQuota() ?? TenantQuota.Default;
client.SendNoticeToAsync(
action,
null,
new[] { StudioNotifyHelper.ToRecipient(u.ID) },
new[] { senderName },
null,
new TagValue(Tags.UserName, u.FirstName.HtmlEncode()),
new TagValue(Tags.PricingPage, CommonLinkUtility.GetFullAbsolutePath("~/Tariffs.aspx")),
new TagValue(Tags.ActiveUsers, CoreContext.UserManager.GetUsers().Count()),
new TagValue(Tags.Price, rquota.Price),
new TagValue(Tags.PricePeriod, rquota.Year3 ? UserControlsCommonResource.TariffPerYear3 : rquota.Year ? UserControlsCommonResource.TariffPerYear : UserControlsCommonResource.TariffPerMonth),
new TagValue(Tags.DueDate, dueDate.ToLongDateString()),
new TagValue(Tags.DelayDueDate, (delayDueDateIsNotMax ? delayDueDate : dueDate).ToLongDateString()),
TagValues.BlueButton(blueButtonText, "http://www.onlyoffice.com/call-back-form.aspx"),
TagValues.GreenButton(greenButtonText, greenButtonUrl),
TagValues.TableTop(),
TagValues.TableItem(1, tableItemText1, tableItemUrl1, tableItemImg1, tableItemComment1, tableItemLearnMoreText1, tableItemLearnMoreUrl1),
TagValues.TableItem(2, tableItemText2, tableItemUrl2, tableItemImg2, tableItemComment2, tableItemLearnMoreText2, tableItemLearnMoreUrl2),
TagValues.TableItem(3, tableItemText3, tableItemUrl3, tableItemImg3, tableItemComment3, tableItemLearnMoreText3, tableItemLearnMoreUrl3),
TagValues.TableItem(4, tableItemText4, tableItemUrl4, tableItemImg4, tableItemComment4, tableItemLearnMoreText4, tableItemLearnMoreUrl4),
TagValues.TableItem(5, tableItemText5, tableItemUrl5, tableItemImg5, tableItemComment5, tableItemLearnMoreText5, tableItemLearnMoreUrl5),
TagValues.TableItem(6, tableItemText6, tableItemUrl6, tableItemImg6, tableItemComment6, tableItemLearnMoreText6, tableItemLearnMoreUrl6),
TagValues.TableItem(7, tableItemText7, tableItemUrl7, tableItemImg7, tableItemComment7, tableItemLearnMoreText7, tableItemLearnMoreUrl7),
TagValues.TableBottom());
}
}
catch (Exception err)
{
log.Error(err);
}
}
log.Info("End SendTariffEnterpriseLetters");
}
public static void SendOpensourceLetters(INotifyClient client, string senderName, DateTime scheduleDate)
{
var log = LogManager.GetLogger("ASC.Notify");
var nowDate = scheduleDate.Date;
log.Info("Start SendOpensourceTariffLetters");
var activeTenants = CoreContext.TenantManager.GetTenants();
if (activeTenants.Count <= 0)
{
log.Info("End SendOpensourceTariffLetters");
return;
}
foreach (var tenant in activeTenants)
{
try
{
CoreContext.TenantManager.SetCurrentTenant(tenant.TenantId);
var createdDate = tenant.CreatedDateTime.Date;
#region After registration letters
#region 5 days after registration to admins and users
if (createdDate.AddDays(5) == nowDate)
{
var users = StudioNotifyHelper.GetRecipients(true, true, false);
foreach (var u in users.Where(u => StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify)))
{
var culture = string.IsNullOrEmpty(u.CultureName) ? tenant.GetCulture() : u.GetCulture();
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
client.SendNoticeToAsync(
u.IsAdmin() ? Actions.OpensourceAdminDocsTipsV11 : Actions.OpensourceUserDocsTipsV11,
null,
new[] { StudioNotifyHelper.ToRecipient(u.ID) },
new[] { senderName },
null,
new TagValue(Tags.UserName, u.DisplayUserName()),
new TagValue(CommonTags.Footer, "opensource"));
}
}
#endregion
#endregion
}
catch (Exception err)
{
log.Error(err);
}
}
log.Info("End SendOpensourceTariffLetters");
}
public static void SendPersonalLetters(INotifyClient client, string senderName, DateTime scheduleDate)
{
var log = LogManager.GetLogger("ASC.Notify");
log.Info("Start SendLettersPersonal...");
foreach (var tenant in CoreContext.TenantManager.GetTenants())
{
try
{
Func<string> greenButtonText = () => string.Empty;
var greenButtonUrl = string.Empty;
int sendCount = 0;
CoreContext.TenantManager.SetCurrentTenant(tenant.TenantId);
log.InfoFormat("Current tenant: {0}", tenant.TenantId);
var users = CoreContext.UserManager.GetUsers(EmployeeStatus.Active);
foreach (var user in users.Where(u => StudioNotifyHelper.IsSubscribedToNotify(u, Actions.PeriodicNotify)))
{
INotifyAction action;
SecurityContext.AuthenticateMe(CoreContext.Authentication.GetAccountByID(user.ID));
var culture = tenant.GetCulture();
if (!string.IsNullOrEmpty(user.CultureName))
{
try
{
culture = user.GetCulture();
}
catch (CultureNotFoundException exception)
{
log.Error(exception);
}
}
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = culture;
var dayAfterRegister = (int)scheduleDate.Date.Subtract(user.CreateDate.Date).TotalDays;
if (CoreContext.Configuration.CustomMode)
{
switch (dayAfterRegister)
{
case 7:
action = Actions.PersonalCustomModeAfterRegistration7;
break;
default:
continue;
}
}
else
{
switch (dayAfterRegister)
{
case 7:
action = Actions.PersonalAfterRegistration7;
break;
case 14:
action = Actions.PersonalAfterRegistration14;
break;
case 21:
action = Actions.PersonalAfterRegistration21;
break;
case 28:
action = Actions.PersonalAfterRegistration28;
greenButtonText = () => WebstudioNotifyPatternResource.ButtonStartFreeTrial;
greenButtonUrl = "https://www.onlyoffice.com/download-workspace.aspx";
break;
default:
continue;
}
}
if (action == null) continue;
log.InfoFormat(@"Send letter personal '{1}' to {0} culture {2}. tenant id: {3} user culture {4} create on {5} now date {6}",
user.Email, action.ID, culture, tenant.TenantId, user.GetCulture(), user.CreateDate, scheduleDate.Date);
sendCount++;
client.SendNoticeToAsync(
action,
null,
StudioNotifyHelper.RecipientFromEmail(user.Email, true),
new[] { senderName },
null,
TagValues.PersonalHeaderStart(),
TagValues.PersonalHeaderEnd(),
TagValues.GreenButton(greenButtonText, greenButtonUrl),
new TagValue(CommonTags.Footer, CoreContext.Configuration.CustomMode ? "personalCustomMode" : "personal"));
}
log.InfoFormat("Total send count: {0}", sendCount);
}
catch (Exception err)
{
log.Error(err);
}
}
log.Info("End SendLettersPersonal.");
}
public static bool ChangeSubscription(Guid userId)
{
var recipient = StudioNotifyHelper.ToRecipient(userId);
var isSubscribe = StudioNotifyHelper.IsSubscribedToNotify(recipient, Actions.PeriodicNotify);
StudioNotifyHelper.SubscribeToNotify(recipient, Actions.PeriodicNotify, !isSubscribe);
return !isSubscribe;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="dbmetadatafactory.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
// <owner current="true" primary="false">[....]</owner>
//------------------------------------------------------------------------------
namespace System.Data.ProviderBase {
using System;
using System.Collections;
using System.Data;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Xml;
using System.Xml.Schema;
internal class DbMetaDataFactory{ // V1.2.3300
private DataSet _metaDataCollectionsDataSet;
private string _normalizedServerVersion;
private string _serverVersionString;
// well known column names
private const string _collectionName = "CollectionName";
private const string _populationMechanism = "PopulationMechanism";
private const string _populationString = "PopulationString";
private const string _maximumVersion = "MaximumVersion";
private const string _minimumVersion = "MinimumVersion";
private const string _dataSourceProductVersionNormalized = "DataSourceProductVersionNormalized";
private const string _dataSourceProductVersion = "DataSourceProductVersion";
private const string _restrictionDefault = "RestrictionDefault";
private const string _restrictionNumber = "RestrictionNumber";
private const string _numberOfRestrictions = "NumberOfRestrictions";
private const string _restrictionName = "RestrictionName";
private const string _parameterName = "ParameterName";
// population mechanisms
private const string _dataTable = "DataTable";
private const string _sqlCommand = "SQLCommand";
private const string _prepareCollection = "PrepareCollection";
public DbMetaDataFactory(Stream xmlStream, string serverVersion, string normalizedServerVersion) {
ADP.CheckArgumentNull(xmlStream, "xmlStream");
ADP.CheckArgumentNull(serverVersion, "serverVersion");
ADP.CheckArgumentNull(normalizedServerVersion, "normalizedServerVersion");
LoadDataSetFromXml(xmlStream);
_serverVersionString = serverVersion;
_normalizedServerVersion = normalizedServerVersion;
}
protected DataSet CollectionDataSet {
get {
return _metaDataCollectionsDataSet;
}
}
protected string ServerVersion {
get {
return _serverVersionString;
}
}
protected string ServerVersionNormalized {
get {
return _normalizedServerVersion;
}
}
protected DataTable CloneAndFilterCollection(string collectionName, string[] hiddenColumnNames) {
DataTable sourceTable;
DataTable destinationTable;
DataColumn[] filteredSourceColumns;
DataColumnCollection destinationColumns;
DataRow newRow;
sourceTable = _metaDataCollectionsDataSet.Tables[collectionName];
if ((sourceTable == null) || (collectionName != sourceTable.TableName)) {
throw ADP.DataTableDoesNotExist(collectionName);
}
destinationTable = new DataTable(collectionName);
destinationTable.Locale = CultureInfo.InvariantCulture;
destinationColumns = destinationTable.Columns;
filteredSourceColumns = FilterColumns(sourceTable,hiddenColumnNames,destinationColumns);
foreach (DataRow row in sourceTable.Rows) {
if (SupportedByCurrentVersion(row) == true) {
newRow = destinationTable.NewRow();
for(int i = 0; i < destinationColumns.Count; i++) {
newRow[destinationColumns[i]] = row[filteredSourceColumns[i],DataRowVersion.Current];
}
destinationTable.Rows.Add(newRow);
newRow.AcceptChanges();
}
}
return destinationTable;
}
public void Dispose() {
Dispose(true);
}
virtual protected void Dispose(bool disposing) {
if (disposing) {
_normalizedServerVersion = null;
_serverVersionString = null;
_metaDataCollectionsDataSet.Dispose();
}
}
private DataTable ExecuteCommand(DataRow requestedCollectionRow, String[] restrictions, DbConnection connection){
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
DataColumn populationStringColumn = metaDataCollectionsTable.Columns[_populationString];
DataColumn numberOfRestrictionsColumn = metaDataCollectionsTable.Columns[_numberOfRestrictions];
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[_collectionName];
//DataColumn restrictionNameColumn = metaDataCollectionsTable.Columns[_restrictionName];
DataTable resultTable = null;
DbCommand command = null;
DataTable schemaTable = null;
Debug.Assert(requestedCollectionRow != null);
String sqlCommand = requestedCollectionRow[populationStringColumn,DataRowVersion.Current] as string;
int numberOfRestrictions = (int)requestedCollectionRow[numberOfRestrictionsColumn,DataRowVersion.Current] ;
String collectionName = requestedCollectionRow[collectionNameColumn,DataRowVersion.Current] as string;
if ((restrictions != null) && (restrictions.Length > numberOfRestrictions)) {
throw ADP.TooManyRestrictions(collectionName);
}
command = connection.CreateCommand();
command.CommandText = sqlCommand;
command.CommandTimeout = System.Math.Max(command.CommandTimeout,180);
for (int i = 0; i < numberOfRestrictions; i++) {
DbParameter restrictionParameter = command.CreateParameter();
if ((restrictions != null) && (restrictions.Length > i ) && (restrictions[i] != null)) {
restrictionParameter.Value = restrictions[i];
}
else {
// This is where we have to assign null to the value of the parameter.
restrictionParameter.Value = DBNull.Value;
}
restrictionParameter.ParameterName = GetParameterName(collectionName, i+1);
restrictionParameter.Direction = ParameterDirection.Input;
command.Parameters.Add(restrictionParameter);
}
DbDataReader reader = null;
try {
try {
reader = command.ExecuteReader();
}
catch (Exception e) {
if (!ADP.IsCatchableExceptionType(e)) {
throw;
}
throw ADP.QueryFailed(collectionName,e);
}
//
// Build a DataTable from the reader
resultTable = new DataTable(collectionName);
resultTable.Locale = CultureInfo.InvariantCulture;
schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows){
resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"] as Type);
}
object[] values = new object[resultTable.Columns.Count];
while (reader.Read()) {
reader.GetValues(values);
resultTable.Rows.Add(values);
}
}
finally {
if (reader != null) {
reader.Dispose();
reader = null;
}
}
return resultTable;
}
private DataColumn[] FilterColumns(DataTable sourceTable, string[] hiddenColumnNames, DataColumnCollection destinationColumns) {
DataColumn newDestinationColumn;
int currentColumn;
DataColumn[] filteredSourceColumns = null;
int columnCount = 0;
foreach (DataColumn sourceColumn in sourceTable.Columns){
if (IncludeThisColumn(sourceColumn,hiddenColumnNames) == true) {
columnCount++;
}
}
if (columnCount == 0) {
throw ADP.NoColumns();
}
currentColumn= 0;
filteredSourceColumns = new DataColumn[columnCount];
foreach(DataColumn sourceColumn in sourceTable.Columns){
if (IncludeThisColumn(sourceColumn,hiddenColumnNames) == true) {
newDestinationColumn = new DataColumn(sourceColumn.ColumnName,sourceColumn.DataType);
destinationColumns.Add(newDestinationColumn);
filteredSourceColumns[currentColumn] = sourceColumn;
currentColumn++;
}
}
return filteredSourceColumns;
}
internal DataRow FindMetaDataCollectionRow(string collectionName) {
bool versionFailure;
bool haveExactMatch;
bool haveMultipleInexactMatches;
string candidateCollectionName;
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
if (metaDataCollectionsTable == null) {
throw ADP.InvalidXml();
}
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
if ((null == collectionNameColumn) || (typeof(System.String) != collectionNameColumn.DataType)) {
throw ADP.InvalidXmlMissingColumn(DbMetaDataCollectionNames.MetaDataCollections, DbMetaDataColumnNames.CollectionName);
}
DataRow requestedCollectionRow = null;
String exactCollectionName = null;
// find the requested collection
versionFailure = false;
haveExactMatch = false;
haveMultipleInexactMatches = false;
foreach (DataRow row in metaDataCollectionsTable.Rows){
candidateCollectionName = row[collectionNameColumn,DataRowVersion.Current] as string;
if (ADP.IsEmpty(candidateCollectionName)) {
throw ADP.InvalidXmlInvalidValue(DbMetaDataCollectionNames.MetaDataCollections,DbMetaDataColumnNames.CollectionName);
}
if (ADP.CompareInsensitiveInvariant(candidateCollectionName, collectionName)){
if (SupportedByCurrentVersion(row) == false) {
versionFailure = true;
}
else{
if (collectionName == candidateCollectionName) {
if (haveExactMatch == true) {
throw ADP.CollectionNameIsNotUnique(collectionName);
}
requestedCollectionRow = row;
exactCollectionName = candidateCollectionName;
haveExactMatch = true;
}
else {
// have an inexact match - ok only if it is the only one
if (exactCollectionName != null) {
// can't fail here becasue we may still find an exact match
haveMultipleInexactMatches = true;
}
requestedCollectionRow = row;
exactCollectionName = candidateCollectionName;
}
}
}
}
if (requestedCollectionRow == null){
if (versionFailure == false) {
throw ADP.UndefinedCollection(collectionName);
}
else {
throw ADP.UnsupportedVersion(collectionName);
}
}
if ((haveExactMatch == false) && (haveMultipleInexactMatches == true)) {
throw ADP.AmbigousCollectionName(collectionName);
}
return requestedCollectionRow;
}
private void FixUpVersion(DataTable dataSourceInfoTable){
Debug.Assert(dataSourceInfoTable.TableName == DbMetaDataCollectionNames.DataSourceInformation);
DataColumn versionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersion];
DataColumn normalizedVersionColumn = dataSourceInfoTable.Columns[_dataSourceProductVersionNormalized];
if ((versionColumn == null) || (normalizedVersionColumn == null)) {
throw ADP.MissingDataSourceInformationColumn();
}
if (dataSourceInfoTable.Rows.Count != 1) {
throw ADP.IncorrectNumberOfDataSourceInformationRows();
}
DataRow dataSourceInfoRow = dataSourceInfoTable.Rows[0];
dataSourceInfoRow[versionColumn] = _serverVersionString;
dataSourceInfoRow[normalizedVersionColumn] = _normalizedServerVersion;
dataSourceInfoRow.AcceptChanges();
}
private string GetParameterName(string neededCollectionName, int neededRestrictionNumber) {
DataTable restrictionsTable = null;
DataColumnCollection restrictionColumns = null;
DataColumn collectionName = null;
DataColumn parameterName = null;
DataColumn restrictionName = null;
DataColumn restrictionNumber = null;;
string result = null;
restrictionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.Restrictions];
if (restrictionsTable != null) {
restrictionColumns = restrictionsTable.Columns;
if (restrictionColumns != null) {
collectionName = restrictionColumns[_collectionName];
parameterName = restrictionColumns[_parameterName];
restrictionName = restrictionColumns[_restrictionName];
restrictionNumber = restrictionColumns[_restrictionNumber];
}
}
if ((parameterName == null) ||(collectionName == null) || (restrictionName == null) || (restrictionNumber == null)) {
throw ADP.MissingRestrictionColumn();
}
foreach (DataRow restriction in restrictionsTable.Rows) {
if (((string)restriction[collectionName] == neededCollectionName) &&
((int)restriction[restrictionNumber] == neededRestrictionNumber) &&
(SupportedByCurrentVersion(restriction))) {
result = (string)restriction[parameterName];
break;
}
}
if (result == null) {
throw ADP.MissingRestrictionRow();
}
return result;
}
virtual public DataTable GetSchema(DbConnection connection, string collectionName, string[] restrictions) {
Debug.Assert (_metaDataCollectionsDataSet != null);
//
DataTable metaDataCollectionsTable = _metaDataCollectionsDataSet.Tables[DbMetaDataCollectionNames.MetaDataCollections];
DataColumn populationMechanismColumn = metaDataCollectionsTable.Columns[_populationMechanism];
DataColumn collectionNameColumn = metaDataCollectionsTable.Columns[DbMetaDataColumnNames.CollectionName];
DataRow requestedCollectionRow = null;
DataTable requestedSchema = null;
string[] hiddenColumns;
string exactCollectionName = null;
requestedCollectionRow = FindMetaDataCollectionRow(collectionName);
exactCollectionName = requestedCollectionRow[collectionNameColumn,DataRowVersion.Current] as string;
if (ADP.IsEmptyArray(restrictions) == false){
for (int i = 0; i < restrictions.Length; i++) {
if ((restrictions[i] != null) && (restrictions[i].Length > 4096)) {
// use a non-specific error because no new beta 2 error messages are allowed
//
throw ADP.NotSupported();
}
}
}
string populationMechanism = requestedCollectionRow[populationMechanismColumn,DataRowVersion.Current] as string;
switch (populationMechanism) {
case _dataTable:
if (exactCollectionName == DbMetaDataCollectionNames.MetaDataCollections) {
hiddenColumns = new string[2];
hiddenColumns[0] = _populationMechanism;
hiddenColumns[1] = _populationString;
}
else {
hiddenColumns = null;
}
// none of the datatable collections support restrictions
if (ADP.IsEmptyArray(restrictions) == false){
throw ADP.TooManyRestrictions(exactCollectionName);
}
requestedSchema = CloneAndFilterCollection(exactCollectionName,hiddenColumns);
//
// for the data source infomation table we need to fix up the version columns at run time
// since the version is determined at run time
if (exactCollectionName == DbMetaDataCollectionNames.DataSourceInformation) {
FixUpVersion(requestedSchema);
}
break;
case _sqlCommand:
requestedSchema = ExecuteCommand(requestedCollectionRow,restrictions,connection);
break;
case _prepareCollection:
requestedSchema = PrepareCollection(exactCollectionName,restrictions, connection);
break;
default:
throw ADP.UndefinedPopulationMechanism(populationMechanism);
}
return requestedSchema;
}
private bool IncludeThisColumn(DataColumn sourceColumn, string[] hiddenColumnNames) {
bool result = true;
string sourceColumnName = sourceColumn.ColumnName;
switch (sourceColumnName) {
case _minimumVersion:
case _maximumVersion:
result = false;
break;
default:
if (hiddenColumnNames == null) {
break;
}
for (int i = 0 ; i < hiddenColumnNames.Length; i++) {
if (hiddenColumnNames[i] == sourceColumnName){
result = false;
break;
}
}
break;
}
return result;
}
private void LoadDataSetFromXml(Stream XmlStream){
_metaDataCollectionsDataSet = new DataSet();
_metaDataCollectionsDataSet.Locale = System.Globalization.CultureInfo.InvariantCulture;
_metaDataCollectionsDataSet.ReadXml(XmlStream);
}
virtual protected DataTable PrepareCollection(String collectionName, String[] restrictions,DbConnection connection){
throw ADP.NotSupported();
}
private bool SupportedByCurrentVersion(DataRow requestedCollectionRow){
bool result = true;
DataColumnCollection tableColumns = requestedCollectionRow.Table.Columns;
DataColumn versionColumn;
Object version;
// check the minimum version first
versionColumn = tableColumns[_minimumVersion];
if (versionColumn != null) {
version = requestedCollectionRow[versionColumn];
if (version != null) {
if (version != DBNull.Value) {
if (0 > string.Compare( _normalizedServerVersion,(string)version, StringComparison.OrdinalIgnoreCase)){
result = false;
}
}
}
}
// if the minmum version was ok what about the maximum version
if (result == true) {
versionColumn = tableColumns[_maximumVersion];
if (versionColumn != null) {
version = requestedCollectionRow[versionColumn];
if (version != null) {
if (version != DBNull.Value) {
if (0 < string.Compare( _normalizedServerVersion,(string)version, StringComparison.OrdinalIgnoreCase)){
result = false;
}
}
}
}
}
return result;
}
}
}
| |
//
// Copyright (c) 2012-2015 Krueger Systems, 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.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
namespace SQLite
{
public partial class SQLiteAsyncConnection
{
SQLiteConnectionString _connectionString;
SQLiteOpenFlags _openFlags;
public SQLiteAsyncConnection(string databasePath, bool storeDateTimeAsTicks = true)
: this(databasePath, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, storeDateTimeAsTicks)
{
}
public SQLiteAsyncConnection(string databasePath, SQLiteOpenFlags openFlags, bool storeDateTimeAsTicks = true)
{
_openFlags = openFlags;
_connectionString = new SQLiteConnectionString(databasePath, storeDateTimeAsTicks);
}
SQLiteConnectionWithLock GetConnection ()
{
return SQLiteConnectionPool.Shared.GetConnection (_connectionString, _openFlags);
}
public Task<CreateTablesResult> CreateTableAsync<T> (CreateFlags createFlags = CreateFlags.None)
where T : new ()
{
return CreateTablesAsync (createFlags, typeof(T));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2> (CreateFlags createFlags = CreateFlags.None)
where T : new ()
where T2 : new ()
{
return CreateTablesAsync (createFlags, typeof (T), typeof (T2));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3> (CreateFlags createFlags = CreateFlags.None)
where T : new ()
where T2 : new ()
where T3 : new ()
{
return CreateTablesAsync (createFlags, typeof (T2), typeof (T3));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4> (CreateFlags createFlags = CreateFlags.None)
where T : new ()
where T2 : new ()
where T3 : new ()
where T4 : new ()
{
return CreateTablesAsync (createFlags, typeof (T2), typeof (T3), typeof (T4));
}
public Task<CreateTablesResult> CreateTablesAsync<T, T2, T3, T4, T5> (CreateFlags createFlags = CreateFlags.None)
where T : new ()
where T2 : new ()
where T3 : new ()
where T4 : new ()
where T5 : new ()
{
return CreateTablesAsync (createFlags, typeof (T), typeof (T2), typeof (T3), typeof (T4), typeof (T5));
}
public Task<CreateTablesResult> CreateTablesAsync (CreateFlags createFlags = CreateFlags.None, params Type[] types)
{
return Task.Factory.StartNew (() => {
CreateTablesResult result = new CreateTablesResult ();
var conn = GetConnection ();
using (conn.Lock ()) {
foreach (Type type in types) {
int aResult = conn.CreateTable (type, createFlags);
result.Results[type] = aResult;
}
}
return result;
});
}
public Task<int> DropTableAsync<T> ()
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.DropTable<T> ();
}
});
}
public Task<int> InsertAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Insert (item);
}
});
}
public Task<int> InsertOrReplaceAsync(object item)
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.InsertOrReplace(item);
}
});
}
public Task<int> UpdateAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Update (item);
}
});
}
public Task<int> DeleteAsync (object item)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Delete (item);
}
});
}
public Task<T> GetAsync<T>(object pk)
where T : new()
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Get<T>(pk);
}
});
}
public Task<T> FindAsync<T> (object pk)
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Find<T> (pk);
}
});
}
public Task<T> GetAsync<T> (Expression<Func<T, bool>> predicate)
where T : new()
{
return Task.Factory.StartNew(() =>
{
var conn = GetConnection();
using (conn.Lock())
{
return conn.Get<T> (predicate);
}
});
}
public Task<T> FindAsync<T> (Expression<Func<T, bool>> predicate)
where T : new ()
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Find<T> (predicate);
}
});
}
public Task<int> ExecuteAsync (string query, params object[] args)
{
return Task<int>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Execute (query, args);
}
});
}
public Task<int> InsertAllAsync (IEnumerable items)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.InsertAll (items);
}
});
}
public Task<int> UpdateAllAsync (IEnumerable items)
{
return Task.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.UpdateAll (items);
}
});
}
[Obsolete("Will cause a deadlock if any call in action ends up in a different thread. Use RunInTransactionAsync(Action<SQLiteConnection>) instead.")]
public Task RunInTransactionAsync (Action<SQLiteAsyncConnection> action)
{
return Task.Factory.StartNew (() => {
var conn = this.GetConnection ();
using (conn.Lock ()) {
conn.BeginTransaction ();
try {
action (this);
conn.Commit ();
}
catch (Exception) {
conn.Rollback ();
throw;
}
}
});
}
public Task RunInTransactionAsync(Action<SQLiteConnection> action)
{
return Task.Factory.StartNew(() =>
{
var conn = this.GetConnection();
using (conn.Lock())
{
conn.BeginTransaction();
try
{
action(conn);
conn.Commit();
}
catch (Exception)
{
conn.Rollback();
throw;
}
}
});
}
public AsyncTableQuery<T> Table<T> ()
where T : new ()
{
//
// This isn't async as the underlying connection doesn't go out to the database
// until the query is performed. The Async methods are on the query iteself.
//
var conn = GetConnection ();
return new AsyncTableQuery<T> (conn.Table<T> ());
}
public Task<T> ExecuteScalarAsync<T> (string sql, params object[] args)
{
return Task<T>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
var command = conn.CreateCommand (false, sql, args);
return command.ExecuteScalar<T> ();
}
});
}
public Task<List<T>> QueryAsync<T> (string sql, params object[] args)
where T : new ()
{
return Task<List<T>>.Factory.StartNew (() => {
var conn = GetConnection ();
using (conn.Lock ()) {
return conn.Query<T> (sql, args);
}
});
}
}
//
// TODO: Bind to AsyncConnection.GetConnection instead so that delayed
// execution can still work after a Pool.Reset.
//
public class AsyncTableQuery<T>
where T : new ()
{
TableQuery<T> _innerQuery;
public AsyncTableQuery (TableQuery<T> innerQuery)
{
_innerQuery = innerQuery;
}
public AsyncTableQuery<T> Where (Expression<Func<T, bool>> predExpr)
{
return new AsyncTableQuery<T> (_innerQuery.Where (predExpr));
}
public AsyncTableQuery<T> Skip (int n)
{
return new AsyncTableQuery<T> (_innerQuery.Skip (n));
}
public AsyncTableQuery<T> Take (int n)
{
return new AsyncTableQuery<T> (_innerQuery.Take (n));
}
public AsyncTableQuery<T> OrderBy<U> (Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T> (_innerQuery.OrderBy<U> (orderExpr));
}
public AsyncTableQuery<T> OrderByDescending<U> (Expression<Func<T, U>> orderExpr)
{
return new AsyncTableQuery<T> (_innerQuery.OrderByDescending<U> (orderExpr));
}
public Task<List<T>> ToListAsync ()
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.ToList ();
}
});
}
public Task<int> CountAsync ()
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.Count ();
}
});
}
public Task<T> ElementAtAsync (int index)
{
return Task.Factory.StartNew (() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.ElementAt (index);
}
});
}
public Task<T> FirstAsync ()
{
return Task<T>.Factory.StartNew(() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.First ();
}
});
}
public Task<T> FirstOrDefaultAsync ()
{
return Task<T>.Factory.StartNew(() => {
using (((SQLiteConnectionWithLock)_innerQuery.Connection).Lock ()) {
return _innerQuery.FirstOrDefault ();
}
});
}
}
public class CreateTablesResult
{
public Dictionary<Type, int> Results { get; private set; }
internal CreateTablesResult ()
{
this.Results = new Dictionary<Type, int> ();
}
}
class SQLiteConnectionPool
{
class Entry
{
public SQLiteConnectionString ConnectionString { get; private set; }
public SQLiteConnectionWithLock Connection { get; private set; }
public Entry (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags)
{
ConnectionString = connectionString;
Connection = new SQLiteConnectionWithLock (connectionString, openFlags);
}
public void OnApplicationSuspended ()
{
Connection.Dispose ();
Connection = null;
}
}
readonly Dictionary<string, Entry> _entries = new Dictionary<string, Entry> ();
readonly object _entriesLock = new object ();
static readonly SQLiteConnectionPool _shared = new SQLiteConnectionPool ();
/// <summary>
/// Gets the singleton instance of the connection tool.
/// </summary>
public static SQLiteConnectionPool Shared
{
get
{
return _shared;
}
}
public SQLiteConnectionWithLock GetConnection (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags)
{
lock (_entriesLock) {
Entry entry;
string key = connectionString.ConnectionString;
if (!_entries.TryGetValue (key, out entry)) {
entry = new Entry (connectionString, openFlags);
_entries[key] = entry;
}
return entry.Connection;
}
}
/// <summary>
/// Closes all connections managed by this pool.
/// </summary>
public void Reset ()
{
lock (_entriesLock) {
foreach (var entry in _entries.Values) {
entry.OnApplicationSuspended ();
}
_entries.Clear ();
}
}
/// <summary>
/// Call this method when the application is suspended.
/// </summary>
/// <remarks>Behaviour here is to close any open connections.</remarks>
public void ApplicationSuspended ()
{
Reset ();
}
}
class SQLiteConnectionWithLock : SQLiteConnection
{
readonly object _lockPoint = new object ();
public SQLiteConnectionWithLock (SQLiteConnectionString connectionString, SQLiteOpenFlags openFlags)
: base (connectionString.DatabasePath, openFlags, connectionString.StoreDateTimeAsTicks)
{
}
public IDisposable Lock ()
{
return new LockWrapper (_lockPoint);
}
private class LockWrapper : IDisposable
{
object _lockPoint;
public LockWrapper (object lockPoint)
{
_lockPoint = lockPoint;
Monitor.Enter (_lockPoint);
}
public void Dispose ()
{
Monitor.Exit (_lockPoint);
}
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.CallStack;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.ComponentInterfaces;
using Microsoft.VisualStudio.Debugger.Metadata;
using Microsoft.VisualStudio.Debugger.Symbols;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
using TypeCode = Microsoft.VisualStudio.Debugger.Metadata.TypeCode;
namespace Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation
{
public class DkmClrValue : DkmDataContainer
{
internal DkmClrValue(
object value,
object hostObjectValue,
DkmClrType type,
string alias,
IDkmClrFormatter formatter,
DkmEvaluationResultFlags evalFlags,
DkmClrValueFlags valueFlags,
DkmEvaluationResultCategory category = default(DkmEvaluationResultCategory),
DkmEvaluationResultAccessType access = default(DkmEvaluationResultAccessType),
ulong nativeComPointer = 0)
{
Debug.Assert(!type.GetLmrType().IsTypeVariables() || (valueFlags == DkmClrValueFlags.Synthetic));
Debug.Assert((alias == null) || evalFlags.Includes(DkmEvaluationResultFlags.HasObjectId));
// The "real" DkmClrValue will always have a value of zero for null pointers.
Debug.Assert(!type.GetLmrType().IsPointer || (value != null));
this.RawValue = value;
this.HostObjectValue = hostObjectValue;
this.Type = type;
_formatter = formatter;
this.Alias = alias;
this.EvalFlags = evalFlags;
this.ValueFlags = valueFlags;
this.Category = category;
this.Access = access;
this.NativeComPointer = nativeComPointer;
}
public readonly DkmEvaluationResultFlags EvalFlags;
public readonly DkmClrValueFlags ValueFlags;
public readonly DkmClrType Type;
public readonly DkmStackWalkFrame StackFrame;
public readonly DkmEvaluationResultCategory Category;
public readonly DkmEvaluationResultAccessType Access;
public readonly DkmEvaluationResultStorageType StorageType;
public readonly DkmEvaluationResultTypeModifierFlags TypeModifierFlags;
public readonly DkmDataAddress Address;
public readonly object HostObjectValue;
public readonly string Alias;
public readonly ulong NativeComPointer;
private readonly IDkmClrFormatter _formatter;
internal readonly object RawValue;
public void Close()
{
}
public DkmClrValue Dereference(DkmInspectionContext inspectionContext)
{
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
if (RawValue == null)
{
throw new InvalidOperationException("Cannot dereference invalid value");
}
var elementType = this.Type.GetLmrType().GetElementType();
var evalFlags = DkmEvaluationResultFlags.None;
var valueFlags = DkmClrValueFlags.None;
object value;
try
{
var intPtr = Environment.Is64BitProcess ? new IntPtr((long)RawValue) : new IntPtr((int)RawValue);
value = Dereference(intPtr, elementType);
}
catch (Exception e)
{
value = e;
evalFlags |= DkmEvaluationResultFlags.ExceptionThrown;
}
var valueType = new DkmClrType(this.Type.RuntimeInstance, (value == null || elementType.IsPointer) ? elementType : (TypeImpl)value.GetType());
return new DkmClrValue(
value,
value,
valueType,
alias: null,
formatter: _formatter,
evalFlags: evalFlags,
valueFlags: valueFlags,
category: DkmEvaluationResultCategory.Other,
access: DkmEvaluationResultAccessType.None);
}
public bool IsNull
{
get
{
if (this.IsError())
{
// Should not be checking value for Error. (Throw rather than
// assert since the property may be called during debugging.)
throw new InvalidOperationException();
}
var lmrType = Type.GetLmrType();
return ((RawValue == null) && !lmrType.IsValueType) || (lmrType.IsPointer && (Convert.ToInt64(RawValue) == 0));
}
}
internal static object GetHostObjectValue(Type lmrType, object rawValue)
{
// NOTE: This is just a "for testing purposes" approximation of what the real DkmClrValue.HostObjectValue
// will return. We will need to update this implementation to match the real behavior we add
// specialized support for additional types.
var typeCode = Metadata.Type.GetTypeCode(lmrType);
return (lmrType.IsPointer || lmrType.IsEnum || typeCode != TypeCode.DateTime || typeCode != TypeCode.Object)
? rawValue
: null;
}
public string GetValueString(DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers)
{
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
// The real version does some sort of dynamic dispatch that ultimately calls this method.
return _formatter.GetValueString(this, inspectionContext, formatSpecifiers);
}
public bool HasUnderlyingString(DkmInspectionContext inspectionContext)
{
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
return _formatter.HasUnderlyingString(this, inspectionContext);
}
public string GetUnderlyingString(DkmInspectionContext inspectionContext)
{
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
return _formatter.GetUnderlyingString(this, inspectionContext);
}
public string EvaluateToString(DkmInspectionContext inspectionContext)
{
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
// This is a rough approximation of the real functionality. Basically,
// if object.ToString is not overridden, we return null and it is the
// caller's responsibility to compute a string.
var type = this.Type.GetLmrType();
while (type != null)
{
if (type.IsObject() || type.IsValueType())
{
return null;
}
// We should check the signature and virtual-ness, but this is
// close enough for testing.
if (type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Any(m => m.Name == "ToString"))
{
break;
}
type = type.BaseType;
}
var rawValue = RawValue;
Debug.Assert(rawValue != null || this.Type.GetLmrType().IsVoid(), "In our mock system, this should only happen for void.");
return rawValue == null ? null : rawValue.ToString();
}
/// <remarks>
/// Very simple expression evaluation (may not support all syntax supported by Concord).
/// </remarks>
public void EvaluateDebuggerDisplayString(DkmWorkList workList, DkmInspectionContext inspectionContext, DkmClrType targetType, string formatString, DkmCompletionRoutine<DkmEvaluateDebuggerDisplayStringAsyncResult> completionRoutine)
{
Debug.Assert(!this.IsNull, "Not supported by VIL");
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
int openPos = -1;
int length = formatString.Length;
for (int i = 0; i < length; i++)
{
char ch = formatString[i];
if (ch == '{')
{
if (openPos >= 0)
{
throw new ArgumentException(string.Format("Nested braces in '{0}'", formatString));
}
openPos = i;
}
else if (ch == '}')
{
if (openPos < 0)
{
throw new ArgumentException(string.Format("Unmatched closing brace in '{0}'", formatString));
}
string name = formatString.Substring(openPos + 1, i - openPos - 1);
openPos = -1;
var formatSpecifiers = Formatter.NoFormatSpecifiers;
int commaIndex = name.IndexOf(',');
if (commaIndex >= 0)
{
var rawFormatSpecifiers = name.Substring(commaIndex + 1).Split(',');
var trimmedFormatSpecifiers = ArrayBuilder<string>.GetInstance(rawFormatSpecifiers.Length);
trimmedFormatSpecifiers.AddRange(rawFormatSpecifiers.Select(fs => fs.Trim()));
formatSpecifiers = trimmedFormatSpecifiers.ToImmutableAndFree();
foreach (var formatSpecifier in formatSpecifiers)
{
if (formatSpecifier == "nq")
{
inspectionContext = new DkmInspectionContext(_formatter, inspectionContext.EvaluationFlags | DkmEvaluationFlags.NoQuotes, inspectionContext.Radix, inspectionContext.RuntimeInstance);
}
// If we need to support additional format specifiers, add them here...
}
name = name.Substring(0, commaIndex);
}
var type = ((TypeImpl)this.Type.GetLmrType()).Type;
const System.Reflection.BindingFlags bindingFlags =
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.Static;
DkmClrValue exprValue;
var appDomain = this.Type.AppDomain;
var field = type.GetField(name, bindingFlags);
if (field != null)
{
var fieldValue = field.GetValue(RawValue);
exprValue = new DkmClrValue(
fieldValue,
fieldValue,
DkmClrType.Create(appDomain, (TypeImpl)((fieldValue == null) ? field.FieldType : fieldValue.GetType())),
alias: null,
formatter: _formatter,
evalFlags: GetEvaluationResultFlags(fieldValue),
valueFlags: DkmClrValueFlags.None);
}
else
{
var property = type.GetProperty(name, bindingFlags);
if (property != null)
{
var propertyValue = property.GetValue(RawValue);
exprValue = new DkmClrValue(
propertyValue,
propertyValue,
DkmClrType.Create(appDomain, (TypeImpl)((propertyValue == null) ? property.PropertyType : propertyValue.GetType())),
alias: null,
formatter: _formatter,
evalFlags: GetEvaluationResultFlags(propertyValue),
valueFlags: DkmClrValueFlags.None);
}
else
{
var openParenIndex = name.IndexOf('(');
if (openParenIndex >= 0)
{
name = name.Substring(0, openParenIndex);
}
var method = type.GetMethod(name, bindingFlags);
// The real implementation requires parens on method invocations, so
// we'll return error if there wasn't at least an open paren...
if ((openParenIndex >= 0) && method != null)
{
var methodValue = method.Invoke(RawValue, new object[] { });
exprValue = new DkmClrValue(
methodValue,
methodValue,
DkmClrType.Create(appDomain, (TypeImpl)((methodValue == null) ? method.ReturnType : methodValue.GetType())),
alias: null,
formatter: _formatter,
evalFlags: GetEvaluationResultFlags(methodValue),
valueFlags: DkmClrValueFlags.None);
}
else
{
var stringValue = "Problem evaluating expression";
var stringType = DkmClrType.Create(appDomain, (TypeImpl)typeof(string));
exprValue = new DkmClrValue(
stringValue,
stringValue,
stringType,
alias: null,
formatter: _formatter,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.Error);
}
}
}
builder.Append(exprValue.GetValueString(inspectionContext, formatSpecifiers)); // Re-enter the formatter.
}
else if (openPos < 0)
{
builder.Append(ch);
}
}
if (openPos >= 0)
{
throw new ArgumentException(string.Format("Unmatched open brace in '{0}'", formatString));
}
workList.AddWork(() => completionRoutine(new DkmEvaluateDebuggerDisplayStringAsyncResult(pooled.ToStringAndFree())));
}
public DkmClrValue GetMemberValue(string MemberName, int MemberType, string ParentTypeName, DkmInspectionContext InspectionContext)
{
if (InspectionContext == null)
{
throw new ArgumentNullException(nameof(InspectionContext));
}
if (this.IsError())
{
throw new InvalidOperationException();
}
var runtime = this.Type.RuntimeInstance;
var getMemberValue = runtime.GetMemberValue;
if (getMemberValue != null)
{
var memberValue = getMemberValue(this, MemberName);
if (memberValue != null)
{
return memberValue;
}
}
var declaringType = this.Type.GetLmrType();
if (ParentTypeName != null)
{
declaringType = GetAncestorType(declaringType, ParentTypeName);
Debug.Assert(declaringType != null);
}
// Special cases for nullables
if (declaringType.IsNullable())
{
if (MemberName == InternalWellKnownMemberNames.NullableHasValue)
{
// In our mock implementation, RawValue is null for null nullables,
// so we have to compute HasValue some other way.
var boolValue = RawValue != null;
var boolType = runtime.GetType((TypeImpl)typeof(bool));
return new DkmClrValue(
boolValue,
boolValue,
type: boolType,
alias: null,
formatter: _formatter,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.None,
category: DkmEvaluationResultCategory.Property,
access: DkmEvaluationResultAccessType.Public);
}
else if (MemberName == InternalWellKnownMemberNames.NullableValue)
{
// In our mock implementation, RawValue is of type T rather than
// Nullable<T> for nullables, so we'll just return that value
// (no need to unwrap by getting "value" field).
var valueType = runtime.GetType((TypeImpl)RawValue.GetType());
return new DkmClrValue(
RawValue,
RawValue,
type: valueType,
alias: null,
formatter: _formatter,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.None,
category: DkmEvaluationResultCategory.Property,
access: DkmEvaluationResultAccessType.Public);
}
}
Type declaredType;
object value;
var evalFlags = DkmEvaluationResultFlags.None;
var category = DkmEvaluationResultCategory.Other;
var access = DkmEvaluationResultAccessType.None;
const BindingFlags bindingFlags =
BindingFlags.DeclaredOnly |
BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.Public |
BindingFlags.NonPublic;
switch ((MemberTypes)MemberType)
{
case MemberTypes.Field:
var field = declaringType.GetField(MemberName, bindingFlags);
declaredType = field.FieldType;
category = DkmEvaluationResultCategory.Data;
access = GetFieldAccess(field);
if (field.Attributes.HasFlag(System.Reflection.FieldAttributes.Literal) || field.Attributes.HasFlag(System.Reflection.FieldAttributes.InitOnly))
{
evalFlags |= DkmEvaluationResultFlags.ReadOnly;
}
try
{
value = field.GetValue(RawValue);
}
catch (System.Reflection.TargetInvocationException e)
{
var exception = e.InnerException;
return new DkmClrValue(
exception,
exception,
type: runtime.GetType((TypeImpl)exception.GetType()),
alias: null,
formatter: _formatter,
evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown,
valueFlags: DkmClrValueFlags.None,
category: category,
access: access);
}
break;
case MemberTypes.Property:
var property = declaringType.GetProperty(MemberName, bindingFlags);
declaredType = property.PropertyType;
category = DkmEvaluationResultCategory.Property;
access = GetPropertyAccess(property);
if (property.GetSetMethod(nonPublic: true) == null)
{
evalFlags |= DkmEvaluationResultFlags.ReadOnly;
}
try
{
value = property.GetValue(RawValue, bindingFlags, null, null, null);
}
catch (System.Reflection.TargetInvocationException e)
{
var exception = e.InnerException;
return new DkmClrValue(
exception,
exception,
type: runtime.GetType((TypeImpl)exception.GetType()),
alias: null,
formatter: _formatter,
evalFlags: evalFlags | DkmEvaluationResultFlags.ExceptionThrown,
valueFlags: DkmClrValueFlags.None,
category: category,
access: access);
}
break;
default:
throw ExceptionUtilities.UnexpectedValue((MemberTypes)MemberType);
}
Type type;
if (value is System.Reflection.Pointer)
{
unsafe
{
if (Environment.Is64BitProcess)
{
value = (long)System.Reflection.Pointer.Unbox(value);
}
else
{
value = (int)System.Reflection.Pointer.Unbox(value);
}
}
type = declaredType;
}
else if (value == null || declaredType.IsNullable())
{
type = declaredType;
}
else
{
type = (TypeImpl)value.GetType();
}
return new DkmClrValue(
value,
value,
type: runtime.GetType(type),
alias: null,
formatter: _formatter,
evalFlags: evalFlags,
valueFlags: DkmClrValueFlags.None,
category: category,
access: access);
}
public DkmClrValue GetArrayElement(int[] indices, DkmInspectionContext inspectionContext)
{
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
var array = (System.Array)RawValue;
var element = array.GetValue(indices);
var type = DkmClrType.Create(this.Type.AppDomain, (TypeImpl)((element == null) ? array.GetType().GetElementType() : element.GetType()));
return new DkmClrValue(
element,
element,
type: type,
alias: null,
formatter: _formatter,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.None);
}
public ReadOnlyCollection<int> ArrayDimensions
{
get
{
var array = (Array)RawValue;
if (array == null)
{
return null;
}
int rank = array.Rank;
var builder = ArrayBuilder<int>.GetInstance(rank);
for (int i = 0; i < rank; i++)
{
builder.Add(array.GetUpperBound(i) - array.GetLowerBound(i) + 1);
}
return builder.ToImmutableAndFree();
}
}
public ReadOnlyCollection<int> ArrayLowerBounds
{
get
{
var array = (Array)RawValue;
if (array == null)
{
return null;
}
int rank = array.Rank;
var builder = ArrayBuilder<int>.GetInstance(rank);
for (int i = 0; i < rank; i++)
{
builder.Add(array.GetLowerBound(i));
}
return builder.ToImmutableAndFree();
}
}
public DkmClrValue InstantiateProxyType(DkmInspectionContext inspectionContext, DkmClrType proxyType)
{
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
var lmrType = proxyType.GetLmrType();
Debug.Assert(!lmrType.IsGenericTypeDefinition);
const BindingFlags bindingFlags =
BindingFlags.CreateInstance |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public;
var constructor = lmrType.GetConstructors(bindingFlags).Single();
var value = constructor.Invoke(bindingFlags, null, new[] { RawValue }, null);
return new DkmClrValue(
value,
value,
type: proxyType,
alias: null,
formatter: _formatter,
evalFlags: DkmEvaluationResultFlags.None,
valueFlags: DkmClrValueFlags.None);
}
private static readonly ReadOnlyCollection<DkmClrType> s_noArguments = ArrayBuilder<DkmClrType>.GetInstance(0).ToImmutableAndFree();
public DkmClrValue InstantiateDynamicViewProxy(DkmInspectionContext inspectionContext)
{
if (inspectionContext == null)
{
throw new ArgumentNullException("inspectionContext");
}
var module = new DkmClrModuleInstance(
this.Type.AppDomain.RuntimeInstance,
typeof(Microsoft.CSharp.RuntimeBinder.RuntimeBinderException).Assembly,
new DkmModule("Microsoft.CSharp.dll"));
var proxyType = module.ResolveTypeName(
"Microsoft.CSharp.RuntimeBinder.DynamicMetaObjectProviderDebugView",
s_noArguments);
return this.InstantiateProxyType(inspectionContext, proxyType);
}
public DkmClrValue InstantiateResultsViewProxy(DkmInspectionContext inspectionContext, DkmClrType enumerableType)
{
if (EvalFlags.Includes(DkmEvaluationResultFlags.ExceptionThrown))
{
throw new InvalidOperationException();
}
if (inspectionContext == null)
{
throw new ArgumentNullException(nameof(inspectionContext));
}
var appDomain = enumerableType.AppDomain;
var module = GetModule(appDomain, "System.Core.dll");
if (module == null)
{
return null;
}
var typeArgs = enumerableType.GenericArguments;
Debug.Assert(typeArgs.Count <= 1);
var proxyTypeName = (typeArgs.Count == 0) ?
"System.Linq.SystemCore_EnumerableDebugView" :
"System.Linq.SystemCore_EnumerableDebugView`1";
DkmClrType proxyType;
try
{
proxyType = module.ResolveTypeName(proxyTypeName, typeArgs);
}
catch (ArgumentException)
{
// ResolveTypeName throws ArgumentException if type is not found.
return null;
}
return this.InstantiateProxyType(inspectionContext, proxyType);
}
private static DkmClrModuleInstance GetModule(DkmClrAppDomain appDomain, string moduleName)
{
var modules = appDomain.GetClrModuleInstances();
foreach (var module in modules)
{
if (string.Equals(module.Name, moduleName, StringComparison.OrdinalIgnoreCase))
{
return module;
}
}
return null;
}
private static Type GetAncestorType(Type type, string ancestorTypeName)
{
if (type.FullName == ancestorTypeName)
{
return type;
}
// Search interfaces.
foreach (var @interface in type.GetInterfaces())
{
var ancestorType = GetAncestorType(@interface, ancestorTypeName);
if (ancestorType != null)
{
return ancestorType;
}
}
// Search base type.
var baseType = type.BaseType;
if (baseType != null)
{
return GetAncestorType(baseType, ancestorTypeName);
}
return null;
}
private static DkmEvaluationResultFlags GetEvaluationResultFlags(object value)
{
if (true.Equals(value))
{
return DkmEvaluationResultFlags.BooleanTrue;
}
else if (value is bool)
{
return DkmEvaluationResultFlags.Boolean;
}
else
{
return DkmEvaluationResultFlags.None;
}
}
private unsafe static object Dereference(IntPtr ptr, Type elementType)
{
// Only handling a subset of types currently.
switch (Metadata.Type.GetTypeCode(elementType))
{
case TypeCode.Int32:
return *(int*)ptr;
case TypeCode.Object:
if (ptr == IntPtr.Zero)
{
throw new InvalidOperationException("Dereferencing null");
}
var destinationType = elementType.IsPointer
? (Environment.Is64BitProcess ? typeof(long) : typeof(int))
: ((TypeImpl)elementType).Type;
return Marshal.PtrToStructure(ptr, destinationType);
default:
throw new InvalidOperationException();
}
}
private static DkmEvaluationResultAccessType GetFieldAccess(Microsoft.VisualStudio.Debugger.Metadata.FieldInfo field)
{
if (field.IsPrivate)
{
return DkmEvaluationResultAccessType.Private;
}
else if (field.IsFamily)
{
return DkmEvaluationResultAccessType.Protected;
}
else if (field.IsAssembly)
{
return DkmEvaluationResultAccessType.Internal;
}
else
{
return DkmEvaluationResultAccessType.Public;
}
}
private static DkmEvaluationResultAccessType GetPropertyAccess(Microsoft.VisualStudio.Debugger.Metadata.PropertyInfo property)
{
return GetMethodAccess(property.GetGetMethod(nonPublic: true));
}
private static DkmEvaluationResultAccessType GetMethodAccess(Microsoft.VisualStudio.Debugger.Metadata.MethodBase method)
{
if (method.IsPrivate)
{
return DkmEvaluationResultAccessType.Private;
}
else if (method.IsFamily)
{
return DkmEvaluationResultAccessType.Protected;
}
else if (method.IsAssembly)
{
return DkmEvaluationResultAccessType.Internal;
}
else
{
return DkmEvaluationResultAccessType.Public;
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
public class AnimationHierarchyEditor : EditorWindow {
private static int columnWidth = 300;
private Animator animatorObject;
private AnimationClip animationClip;
private ArrayList pathsKeys;
private Hashtable paths;
private Vector2 scrollPos = Vector2.zero;
[MenuItem("Window/Animation Hierarchy Editor")]
static void ShowWindow() {
EditorWindow.GetWindow<AnimationHierarchyEditor>();
}
void OnSelectionChange() {
if (Selection.activeObject is AnimationClip) {
animationClip = (AnimationClip)Selection.activeObject;
FillModel();
} else {
animationClip = null;
}
this.Repaint();
}
void OnGUI() {
if (Event.current.type == EventType.ValidateCommand) {
switch (Event.current.commandName) {
case "UndoRedoPerformed":
FillModel();
break;
}
}
if (animationClip != null) {
scrollPos = GUILayout.BeginScrollView(scrollPos, GUIStyle.none);
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Referenced Animator (Root):", GUILayout.Width(columnWidth));
animatorObject = ((Animator)EditorGUILayout.ObjectField(
animatorObject,
typeof(Animator),
true,
GUILayout.Width(columnWidth))
);
EditorGUILayout.EndHorizontal();
GUILayout.Space(20);
EditorGUILayout.BeginHorizontal();
GUILayout.Label("Reference path:", GUILayout.Width(columnWidth));
GUILayout.Label("Animated properties:", GUILayout.Width(columnWidth));
GUILayout.Label("Object:", GUILayout.Width(columnWidth));
EditorGUILayout.EndHorizontal();
if (paths != null) {
foreach (string path in pathsKeys) {
GUICreatePathItem(path);
}
}
GUILayout.Space(40);
GUILayout.EndScrollView();
} else {
GUILayout.Label("Please select an Animation Clip");
}
}
void GUICreatePathItem(string path) {
string newPath = "";
GameObject obj = FindObjectInRoot(path);
GameObject newObj;
ArrayList properties = (ArrayList)paths[path];
EditorGUILayout.BeginHorizontal();
newPath = EditorGUILayout.TextField(path, GUILayout.Width(columnWidth));
if (GUILayout.Button("Root")) {
newPath = "";
}
EditorGUILayout.LabelField(
properties != null ? properties.Count.ToString() : "0",
GUILayout.Width(columnWidth)
);
Color standardColor = GUI.color;
if (obj != null) {
GUI.color = Color.green;
} else {
GUI.color = Color.red;
}
newObj = (GameObject)EditorGUILayout.ObjectField(
obj,
typeof(GameObject),
true,
GUILayout.Width(columnWidth)
);
GUI.color = standardColor;
EditorGUILayout.EndHorizontal();
try {
if (obj != newObj) {
UpdatePath(path, ChildPath(newObj));
}
if (newPath != path) {
UpdatePath(path, newPath);
}
} catch (UnityException ex) {
Debug.LogError(ex.Message);
}
}
void OnInspectorUpdate() {
this.Repaint();
}
void FillModel() {
paths = new Hashtable();
pathsKeys = new ArrayList();
FillModelWithCurves(AnimationUtility.GetCurveBindings(animationClip));
FillModelWithCurves(AnimationUtility.GetObjectReferenceCurveBindings(animationClip));
}
private void FillModelWithCurves(EditorCurveBinding[] curves) {
foreach (EditorCurveBinding curveData in curves) {
string key = curveData.path;
if (paths.ContainsKey(key)) {
((ArrayList)paths[key]).Add(curveData);
} else {
ArrayList newProperties = new ArrayList();
newProperties.Add(curveData);
paths.Add(key, newProperties);
pathsKeys.Add(key);
}
}
}
void UpdatePath(string oldPath, string newPath) {
if (paths[newPath] != null) {
throw new UnityException("Path " + newPath + " already exists in that animation!");
}
Undo.RecordObject(animationClip, "Animation Hierarchy Change");
//recreating all curves one by one
//to maintain proper order in the editor -
//slower than just removing old curve
//and adding a corrected one, but it's more
//user-friendly
foreach (string path in pathsKeys) {
ArrayList curves = (ArrayList)paths[path];
for (int i = 0; i < curves.Count; i++) {
EditorCurveBinding binding = (EditorCurveBinding)curves[i];
AnimationCurve curve = AnimationUtility.GetEditorCurve(animationClip, binding);
ObjectReferenceKeyframe[] objectReferenceCurve = null;
if (curve != null) {
AnimationUtility.SetEditorCurve(animationClip, binding, null);
} else {
objectReferenceCurve = AnimationUtility.GetObjectReferenceCurve(animationClip, binding);
AnimationUtility.SetObjectReferenceCurve(animationClip, binding, null);
}
if (path == oldPath) {
binding.path = newPath;
}
if (curve != null) {
AnimationUtility.SetEditorCurve(animationClip, binding, curve);
} else {
AnimationUtility.SetObjectReferenceCurve(animationClip, binding, objectReferenceCurve);
}
}
}
FillModel();
this.Repaint();
}
GameObject FindObjectInRoot(string path) {
if (animatorObject == null) {
return null;
}
Transform child = animatorObject.transform.Find(path);
if (child != null) {
return child.gameObject;
} else {
return null;
}
}
string ChildPath(GameObject obj, bool sep = false) {
if (animatorObject == null) {
throw new UnityException("Please assign Referenced Animator (Root) first!");
}
if (obj == animatorObject.gameObject) {
return "";
} else {
if (obj.transform.parent == null) {
throw new UnityException("Object must belong to " + animatorObject.ToString() + "!");
} else {
return ChildPath(obj.transform.parent.gameObject, true) + obj.name + (sep ? "/" : "");
}
}
}
}
| |
using System;
using NUnit.Framework;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Crypto.Tests
{
/**
* Wrap Test based on RFC3211 test vectors
*/
[TestFixture]
public class Rfc3211WrapTest
: SimpleTest
{
// Note: These test data assume the Rfc3211WrapEngine will call SecureRandom.NextBytes
SecureRandom r1 = FixedSecureRandom.From(
new byte[]{ 0xC4, 0x36, 0xF5, 0x41 });
SecureRandom r2 = FixedSecureRandom.From(
new byte[]{ 0xFA, 0x06, 0x0A, 0x45 });
public override string Name
{
get { return "RFC3211Wrap"; }
}
private void doWrapTest(
int id,
IBlockCipher engine,
byte[] kek,
byte[] iv,
SecureRandom rand,
byte[] inBytes,
byte[] outBytes)
{
IWrapper wrapper = new Rfc3211WrapEngine(engine);
wrapper.Init(true, new ParametersWithRandom(
new ParametersWithIV(new KeyParameter(kek), iv), rand));
byte[] cText = wrapper.Wrap(inBytes, 0, inBytes.Length);
if (!AreEqual(cText, outBytes))
{
Fail("failed Wrap test " + id + " expected "
+ Hex.ToHexString(outBytes) + " got " + Hex.ToHexString(cText));
}
wrapper.Init(false, new ParametersWithIV(new KeyParameter(kek), iv));
byte[] pText = wrapper.Unwrap(outBytes, 0, outBytes.Length);
if (!AreEqual(pText, inBytes))
{
Fail("rfailed Unwrap test " + id + " expected "
+ Hex.ToHexString(inBytes) + " got " + Hex.ToHexString(pText));
}
}
private void doTestCorruption()
{
byte[] kek = Hex.Decode("D1DAA78615F287E6");
byte[] iv = Hex.Decode("EFE598EF21B33D6D");
IWrapper wrapper = new Rfc3211WrapEngine(new DesEngine());
wrapper.Init(false, new ParametersWithIV(new KeyParameter(kek), iv));
byte[] block = Hex.Decode("ff739D838C627C897323A2F8C436F541");
encryptBlock(kek, iv, block);
try
{
wrapper.Unwrap(block, 0, block.Length);
Fail("bad length not detected");
}
catch (InvalidCipherTextException e)
{
if (!e.Message.Equals("wrapped key corrupted"))
{
Fail("wrong exception on length");
}
}
block = Hex.Decode("08639D838C627C897323A2F8C436F541");
doTestChecksum(kek, iv, block, wrapper);
block = Hex.Decode("08736D838C627C897323A2F8C436F541");
doTestChecksum(kek, iv, block, wrapper);
block = Hex.Decode("08739D638C627C897323A2F8C436F541");
doTestChecksum(kek, iv, block, wrapper);
}
private void doTestChecksum(
byte[] kek,
byte[] iv,
byte[] block,
IWrapper wrapper)
{
encryptBlock(kek, iv, block);
try
{
wrapper.Unwrap(block, 0, block.Length);
Fail("bad checksum not detected");
}
catch (InvalidCipherTextException e)
{
if (!e.Message.Equals("wrapped key fails checksum"))
{
Fail("wrong exception");
}
}
}
private void encryptBlock(byte[] key, byte[] iv, byte[] cekBlock)
{
IBlockCipher engine = new CbcBlockCipher(new DesEngine());
engine.Init(true, new ParametersWithIV(new KeyParameter(key), iv));
for (int i = 0; i < cekBlock.Length; i += 8)
{
engine.ProcessBlock(cekBlock, i, cekBlock, i);
}
for (int i = 0; i < cekBlock.Length; i += 8)
{
engine.ProcessBlock(cekBlock, i, cekBlock, i);
}
}
public override void PerformTest()
{
doWrapTest(1, new DesEngine(), Hex.Decode("D1DAA78615F287E6"), Hex.Decode("EFE598EF21B33D6D"), r1, Hex.Decode("8C627C897323A2F8"), Hex.Decode("B81B2565EE373CA6DEDCA26A178B0C10"));
doWrapTest(2, new DesEdeEngine(), Hex.Decode("6A8970BF68C92CAEA84A8DF28510858607126380CC47AB2D"), Hex.Decode("BAF1CA7931213C4E"), r2,
Hex.Decode("8C637D887223A2F965B566EB014B0FA5D52300A3F7EA40FFFC577203C71BAF3B"),
Hex.Decode("C03C514ABDB9E2C5AAC038572B5E24553876B377AAFB82ECA5A9D73F8AB143D9EC74E6CAD7DB260C"));
doTestCorruption();
IWrapper wrapper = new Rfc3211WrapEngine(new DesEngine());
ParametersWithIV parameters = new ParametersWithIV(new KeyParameter(new byte[16]), new byte[16]);
byte[] buf = new byte[16];
try
{
wrapper.Init(true, parameters);
wrapper.Unwrap(buf, 0, buf.Length);
Fail("failed Unwrap state test.");
}
catch (InvalidOperationException)
{
// expected
}
catch (InvalidCipherTextException e)
{
Fail("unexpected exception: " + e, e);
}
try
{
wrapper.Init(false, parameters);
wrapper.Wrap(buf, 0, buf.Length);
Fail("failed Unwrap state test.");
}
catch (InvalidOperationException)
{
// expected
}
//
// short test
//
try
{
wrapper.Init(false, parameters);
wrapper.Unwrap(buf, 0, buf.Length / 2);
Fail("failed Unwrap short test.");
}
catch (InvalidCipherTextException)
{
// expected
}
}
public static void Main(
string[] args)
{
RunTest(new Rfc3211WrapTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
/* $Id$
*
* Project: Swicli.Library - Two Way Interface for .NET and MONO to SWI-Prolog
* Author: Douglas R. Miles
* E-mail: logicmoo@gmail.com
* WWW: http://www.logicmoo.com
* Copyright (C): 2010-2012 LogicMOO Developement
*
* 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.Diagnostics;
//using java.lang;
using org.jpl7;
using sun.reflect.misc;
#if USE_IKVM
using JavaClass = java.lang.Class;
using Type = System.Type;
using ClassLoader = java.lang.ClassLoader;
//using sun.reflect.misc;
//using IKVM.Internal;
using Hashtable = java.util.Hashtable;
using ikvm.runtime;
using java.net;
#else
using JClass = System.Type;
using Type = System.Type;
#endif
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using SbsSW.SwiPlCs;
using SbsSW.SwiPlCs.Callback;
using Exception = System.Exception;
using PlTerm = SbsSW.SwiPlCs.PlTerm;
using Process = java.lang.Process;
using String = System.String;
namespace Swicli.Library
{
public partial class PrologCLR
{
public static ScriptingClassLoader scriptingClassLoader = null;
#if USE_IKVM
public static bool cliAddPath(String url)
{
cliSetupIKVM();
scriptingClassLoader.AddPath(url);
return true;
}
public static bool cliAddClasspath(String url)
{
cliSetupIKVM();
scriptingClassLoader.AddClasspath(url);
return true;
}
private static bool IKVMSetupAlready = false;
public static void cliSetupIKVM()
{
if (IKVMSetupAlready) return;
IKVMSetupAlready = true;
if (!IsIKVMDir(IKVMHome)) IKVMHome = Environment.GetEnvironmentVariable("IKVM_BINDIR");
if (!IsIKVMDir(IKVMHome))
IKVMHome = new FileInfo(typeof (ikvm.runtime.Util).Assembly.Location).DirectoryName;
if (!IsIKVMDir(IKVMHome)) IKVMHome = Environment.CurrentDirectory;
Environment.SetEnvironmentVariable("IKVM_BINDIR", IKVMHome);
DirectoryInfo destination = new DirectoryInfo(IKVMHome);
DirectoryInfo source;
if (Embedded.Is64BitRuntime())
{
source = new DirectoryInfo(IKVMHome + "/x64-win64/");
}
else
{
source = new DirectoryInfo(IKVMHome + "/i386-win32/");
}
Embedded.ConsoleWriteLine("Source of swicli=" + source);
scriptingClassLoader = new ScriptingClassLoader(ClassLoader.getSystemClassLoader());
// if (source.Exists) CopyFiles(source, destination, true, "*.*", false);
}
public static void cliEnsureClasspath()
{
if (true) return;
String overloadClasspath = Environment.GetEnvironmentVariable("LOGICMOO_CLASSPATH");
if (overloadClasspath != null)
{
cliAddClasspath(overloadClasspath);
}
else
{
String javaClasspath = java.lang.System.getProperty("java.class.path");
cliAddClasspath(javaClasspath);
String javaEnvClasspath = Environment.GetEnvironmentVariable("CLASSPATH");
if (javaEnvClasspath != null && !javaEnvClasspath.Equals(javaClasspath))
{
cliAddClasspath(javaEnvClasspath);
}
}
}
private static
bool IsIKVMDir(string ikvmHome)
{
return File.Exists(ikvmHome + "/ikvm.exe");
}
#pragma warning disable 414, 3021
[CLSCompliant(false)]
public class ScriptingClassLoader : URLClassLoader
{
private readonly IList<ClassLoader> lc = new List<ClassLoader>();
// IList<AppDomainAssemblyClassLoader> AppDomainAssemblyClassLoaders = new List<AppDomainAssemblyClassLoader>();
// IList<AssemblyClassLoader> AssemblyClassLoaders = new List<AssemblyClassLoader>();
//IList<ClassPathAssemblyClassLoader> ClassPathAssemblyClassLoaders = new List<ClassPathAssemblyClassLoader>();
// IList<URLClassLoader> URLClassLoaders = new List<URLClassLoader>();
private IList<MethodUtil> MethodUtils = new List<MethodUtil>();
public ScriptingClassLoader(ClassLoader cl)
: base(new URL[0], cl)
{
//AddLoader(cl);
}
public void AddDirectory(string cl)
{
java.io.File f = new java.io.File(cl);
addURL(f.toURL());
}
public void AddClasspath(string cl)
{
String[] paths = cl.Split(';');
foreach (string path in paths)
{
AddPath(path);
}
}
public void AddPath(string path)
{
Embedded.ConsoleWriteLine("Adding path: '" + path + "'");
if (String.IsNullOrEmpty(path))
{
return;
}
if (Directory.Exists(path))
{
AddDirectory(path);
AddAssemblySearchPath(path);
}
else if (path.EndsWith(".abcl") || path.EndsWith(".jar") || path.EndsWith(".zip"))
{
AddJar(path);
}
else
{
try
{
AddAssembly(path);
}
catch (Exception e)
{
AddAssemblySearchPath(path);
}
}
}
public void AddJar(string cl)
{
java.io.File f = new java.io.File(cl);
if (f.exists())
{
String path = f.getPath();
int lastDot = path.LastIndexOf('.');
if (lastDot > 1)
{
String ext = path.Substring(lastDot + 1);
path = path.Substring(0, lastDot);
if (ext == "jar" && !path.Contains(@"appdapter"))
{
String compileTo = IKVMHome;
String newDll = path + ".dll";
if (File.Exists(newDll))
{
if (ResolveAssembly(Assembly.LoadFile(newDll)))
{
Embedded.ConsoleWriteLine("ResolveAssembly: " + newDll);
addURL(f.toURL());
return;
}
}
String commandArgs = "" + cl + " -out:" + newDll;
ProcessStartInfo cmdsi = new ProcessStartInfo(compileTo + "\\ikvmc.exe");
cmdsi.Arguments = commandArgs;
if(false) StartProcessNoActivate("...");
System.Diagnostics.Process cmd = System.Diagnostics.Process.Start(cmdsi);
cmd.WaitForExit();
if (File.Exists(newDll))
{
if (ResolveAssembly(Assembly.LoadFile(newDll)))
{
Embedded.ConsoleWriteLine("CompiledAssembly: " + newDll);
addURL(f.toURL());
return;
}
}
}
}
}
addURL(f.toURL());
}
public void AddAssembly(string cl)
{
AddLoader(new AssemblyClassLoader(PrologCLR.LoadAssemblyByFile(cl)));
}
public bool AddLoader(ClassLoader cl)
{
lock (lc)
{
if (cl == null) return false;
{
bool added = AddLoader(cl.getParent());
if (lc.Contains(cl)) return added;
lc.Insert(0, cl);
if (cl is MethodUtil)
{
MethodUtils.Add((MethodUtil) cl);
// added = true;
}
//added = true;
/*
if (cl is AppDomainAssemblyClassLoader)
{
// AppDomainAssemblyClassLoaders.Add((AppDomainAssemblyClassLoader)cl);
added = true;
}
if (cl is AssemblyClassLoader)
{
// AssemblyClassLoaders.Add((AssemblyClassLoader)cl);
added = true;
}
if (cl is ClassPathAssemblyClassLoader)
{
// ClassPathAssemblyClassLoaders.Add((ClassPathAssemblyClassLoader)cl);
added = true;
}
if (!added)
{
if (cl is MethodUtil)
{
MethodUtils.Add((MethodUtil)cl);
added = true;
}
else
if (cl is URLClassLoader)
{
// URLClassLoaders.Add((URLClassLoader)cl);
added = true;
}
}
*/
return true;
}
}
}
public static
void Check()
{
}
public string FindLibrary(string libname)
{
return base.findLibrary(libname);
}
public JavaClass LoadClass(string name, bool resolve)
{
return base.loadClass(name, resolve);
}
public JavaClass ResolveClass(JavaClass clz)
{
base.resolveClass(clz);
return clz;
}
public override JavaClass loadClass(string name)
{
if (true) return base.loadClass(name);
JavaClass c = base.loadClass(name, false);
if (c != null) ResolveClass(c);
return c;
}
protected override JavaClass findClass(string name)
{
if (true) return base.findClass(name);
ClassLoader was = java.lang.Thread.currentThread().getContextClassLoader();
try
{
// java.lang.Thread.currentThread().setContextClassLoader(this);
JavaClass t = findClass0(name);
if (t != null)
{
return t;
}
return t;
}
finally
{
java.lang.Thread.currentThread().setContextClassLoader(was);
}
}
protected JavaClass findClass0(string name)
{
java.lang.ClassNotFoundException cnfG = null;
lock (lc)
{
JavaClass t = null;
foreach (ClassLoader loader in lc)
{
try
{
t = loader.loadClass(name);
}
catch (java.lang.ClassNotFoundException cnf)
{
if (cnfG == null) cnfG = cnf;
}
if (t != null)
{
return t;
}
}
//if (cnfG == null)
return base.findClass(name);
//throw cnfG;
}
}
}
#pragma warning restore 414, 3021
private static void TestClassLoader()
{
//using java.lang;
//IKVM.Internal.BootstrapClassLoader()
ScriptingClassLoader cl = new ScriptingClassLoader(ClassLoader.getSystemClassLoader());
string s = "jpl.fli.term_t";
JavaClass c;
try
{
c = cl.loadClass(s);
}
catch (java.lang.ClassNotFoundException e)
{
}
catch (java.security.PrivilegedActionException e)
{
}
foreach (
var s1 in
new Type[]
{
1.GetType(), true.GetType(), "".GetType(), typeof (void), 'a'.GetType(), typeof (Type[]),
typeof (IComparable<Type>)
})
{
c = getFriendlyClassFromType(s1);
if (c != null)
{
ConsoleTrace("class: " + c + " from type " + s1.FullName);
continue;
}
ConsoleTrace("cant get " + s1.FullName);
}
foreach (var s1 in new JPL().GetType().Assembly.GetTypes())
{
c = getInstanceTypeFromClass(s1);
c = getFriendlyClassFromType(s1);
if (c != null)
{
//ConsoleTrace("" + c);
continue;
}
ConsoleTrace("cant get " + s1.FullName);
}
return;
}
private static string clasPathOf(JPL jpl1)
{
string s = null;
var cl = jpl1.getClass().getClassLoader();
if (cl != null)
{
var r = cl.getResource(".");
if (r != null)
{
s = r.getFile();
}
else
{
var a = jpl1.GetType().Assembly;
if (a != null)
{
s = a.Location;
}
}
}
return s;
}
#endif
// This is possible but only via pinvoke, which unfortunately requires about 70 lines of code:
[StructLayout(LayoutKind.Sequential)]
private struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[DllImport("kernel32.dll")]
private static extern bool CreateProcess(
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool CloseHandle(IntPtr hObject);
private const int STARTF_USESHOWWINDOW = 1;
private const int SW_SHOWNOACTIVATE = 4;
private const int SW_SHOWMINNOACTIVE = 7;
public static void StartProcessNoActivate(string cmdLine)
{
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
si.dwFlags = STARTF_USESHOWWINDOW;
si.wShowWindow = SW_SHOWMINNOACTIVE;
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
CreateProcess(null, cmdLine, IntPtr.Zero, IntPtr.Zero, true,
0, IntPtr.Zero, null, ref si, out pi);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Timers;
using LumiSoft.Net.SIP.Message;
namespace LumiSoft.Net.SIP.Stack
{
/// <summary>
/// Implements SIP transaction layer. Defined in RFC 3261.
/// Transaction layer manages client,server transactions and dialogs.
/// </summary>
public class SIP_TransactionLayer
{
private bool m_IsDisposed = false;
private SIP_Stack m_pStack = null;
private Dictionary<string,SIP_ClientTransaction> m_pClientTransactions = null;
private Dictionary<string,SIP_ServerTransaction> m_pServerTransactions = null;
private Dictionary<string,SIP_Dialog> m_pDialogs = null;
private Timer m_pTimer = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stack">Reference to SIP stack.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stack</b> is null reference.</exception>
internal SIP_TransactionLayer(SIP_Stack stack)
{
if(stack == null){
throw new ArgumentNullException("stack");
}
m_pStack = stack;
m_pClientTransactions = new Dictionary<string,SIP_ClientTransaction>();
m_pServerTransactions = new Dictionary<string,SIP_ServerTransaction>();
m_pDialogs = new Dictionary<string,SIP_Dialog>();
m_pTimer = new Timer(20000);
m_pTimer.AutoReset = true;
m_pTimer.Elapsed += new ElapsedEventHandler(m_pTimer_Elapsed);
}
#region method Dispose
/// <summary>
/// Cleans up any resources being used.
/// </summary>
internal void Dispose()
{
if(m_IsDisposed){
return;
}
if(m_pTimer != null){
m_pTimer.Dispose();
m_pTimer = null;
}
foreach(SIP_ClientTransaction tr in this.ClientTransactions){
try{
tr.Dispose();
}
catch{
}
}
foreach(SIP_ServerTransaction tr in this.ServerTransactions){
try{
tr.Dispose();
}
catch{
}
}
foreach(SIP_Dialog dialog in this.Dialogs){
try{
dialog.Dispose();
}
catch{
}
}
m_IsDisposed = true;
}
#endregion
#region Events Handling
#region method m_pTimer_Elapsed
private void m_pTimer_Elapsed(object sender,ElapsedEventArgs e)
{
foreach(SIP_Dialog dialog in this.Dialogs){
// Terminate early dialog after 5 minutes, normally there must be any, but just in case ... .
if(dialog.State == SIP_DialogState.Early){
if(dialog.CreateTime.AddMinutes(5) < DateTime.Now){
dialog.Terminate();
}
}
//
else if(dialog.State == SIP_DialogState.Confirmed){
// TODO:
}
}
}
#endregion
#endregion
#region method CreateClientTransaction
/// <summary>
/// Creates new client transaction.
/// </summary>
/// <param name="flow">SIP data flow which is used to send request.</param>
/// <param name="request">SIP request that transaction will handle.</param>
/// <param name="addVia">If true, transaction will add <b>Via:</b> header, otherwise it's user responsibility.</param>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception>
/// <returns>Returns created transaction.</returns>
public SIP_ClientTransaction CreateClientTransaction(SIP_Flow flow,SIP_Request request,bool addVia)
{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(flow == null){
throw new ArgumentNullException("flow");
}
if(request == null){
throw new ArgumentNullException("request");
}
// Add Via:
if(addVia){
SIP_t_ViaParm via = new SIP_t_ViaParm();
via.ProtocolName = "SIP";
via.ProtocolVersion = "2.0";
via.ProtocolTransport = flow.Transport;
via.SentBy = new HostEndPoint("transport_layer_will_replace_it",-1);
via.Branch = SIP_t_ViaParm.CreateBranch();
via.RPort = 0;
request.Via.AddToTop(via.ToStringValue());
}
lock(m_pClientTransactions){
SIP_ClientTransaction transaction = new SIP_ClientTransaction(m_pStack,flow,request);
m_pClientTransactions.Add(transaction.Key,transaction);
transaction.StateChanged += new EventHandler(delegate(object s,EventArgs e){
if(transaction.State == SIP_TransactionState.Terminated){
lock(m_pClientTransactions){
m_pClientTransactions.Remove(transaction.Key);
}
}
});
return transaction;
}
}
#endregion
#region method CreateServerTransaction
/// <summary>
/// Creates new SIP server transaction for specified request.
/// </summary>
/// <param name="flow">SIP data flow which is used to receive request.</param>
/// <param name="request">SIP request.</param>
/// <returns>Returns added server transaction.</returns>
/// <exception cref="ObjectDisposedException">Is raised when this class is Disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null reference.</exception>
public SIP_ServerTransaction CreateServerTransaction(SIP_Flow flow,SIP_Request request)
{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(flow == null){
throw new ArgumentNullException("flow");
}
if(request == null){
throw new ArgumentNullException("request");
}
lock(m_pServerTransactions){
SIP_ServerTransaction transaction = new SIP_ServerTransaction(m_pStack,flow,request);
m_pServerTransactions.Add(transaction.Key,transaction);
transaction.StateChanged += new EventHandler(delegate(object s,EventArgs e){
if(transaction.State == SIP_TransactionState.Terminated){
lock(m_pClientTransactions){
m_pServerTransactions.Remove(transaction.Key);
}
}
});
return transaction;
}
}
#endregion
#region method EnsureServerTransaction
/// <summary>
/// Ensures that specified request has matching server transaction. If server transaction doesn't exist,
/// it will be created, otherwise existing transaction will be returned.
/// </summary>
/// <param name="flow">SIP data flow which is used to receive request.</param>
/// <param name="request">SIP request.</param>
/// <returns>Returns matching transaction.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>flow</b> or <b>request</b> is null.</exception>
/// <exception cref="InvalidOperationException">Is raised when request.Method is ACK request.</exception>
public SIP_ServerTransaction EnsureServerTransaction(SIP_Flow flow,SIP_Request request)
{
if(flow == null){
throw new ArgumentNullException("flow");
}
if(request == null){
throw new ArgumentNullException("request");
}
if(request.RequestLine.Method == SIP_Methods.ACK){
throw new InvalidOperationException("ACK request is transaction less request, can't create transaction for it.");
}
/*
We use branch and sent-by as indexing key for transaction, the only special what we need to
do is to handle CANCEL, because it has same branch as transaction to be canceled.
For avoiding key collision, we add branch + '-' + 'sent-by' + CANCEL for cancel index key.
ACK has also same branch, but we won't do transaction for ACK, so it isn't problem.
*/
string key = request.Via.GetTopMostValue().Branch + '-' + request.Via.GetTopMostValue().SentBy;
if(request.RequestLine.Method == SIP_Methods.CANCEL){
key += "-CANCEL";
}
lock(m_pServerTransactions){
SIP_ServerTransaction retVal = null;
m_pServerTransactions.TryGetValue(key,out retVal);
// We don't have transaction, create it.
if(retVal == null){
retVal = CreateServerTransaction(flow,request);
}
return retVal;
}
}
#endregion
#region method MatchClientTransaction
/// <summary>
/// Matches SIP response to client transaction. If not matching transaction found, returns null.
/// </summary>
/// <param name="response">SIP response to match.</param>
internal SIP_ClientTransaction MatchClientTransaction(SIP_Response response)
{
/* RFC 3261 17.1.3 Matching Responses to Client Transactions.
1. If the response has the same value of the branch parameter in
the top Via header field as the branch parameter in the top
Via header field of the request that created the transaction.
2. If the method parameter in the CSeq header field matches the
method of the request that created the transaction. The
method is needed since a CANCEL request constitutes a
different transaction, but shares the same value of the branch
parameter.
*/
SIP_ClientTransaction retVal = null;
string transactionID = response.Via.GetTopMostValue().Branch + "-" + response.CSeq.RequestMethod;
lock(m_pClientTransactions){
m_pClientTransactions.TryGetValue(transactionID,out retVal);
}
return retVal;
}
#endregion
#region method MatchServerTransaction
/// <summary>
/// Matches SIP request to server transaction. If not matching transaction found, returns null.
/// </summary>
/// <param name="request">SIP request to match.</param>
/// <returns>Returns matching transaction or null if no match.</returns>
internal SIP_ServerTransaction MatchServerTransaction(SIP_Request request)
{
/* RFC 3261 17.2.3 Matching Requests to Server Transactions.
This matching rule applies to both INVITE and non-INVITE transactions.
1. the branch parameter in the request is equal to the one in the top Via header
field of the request that created the transaction, and
2. the sent-by value in the top Via of the request is equal to the
one in the request that created the transaction, and
3. the method of the request matches the one that created the transaction, except
for ACK, where the method of the request that created the transaction is INVITE.
Internal implementation notes:
Inernally we use branch + '-' + sent-by for non-CANCEL and for CANCEL
branch + '-' + sent-by + '-' CANCEL. This is because method matching is actually
needed for CANCEL only (CANCEL shares cancelable transaction branch ID).
*/
SIP_ServerTransaction retVal = null;
/*
We use branch and sent-by as indexing key for transaction, the only special what we need to
do is to handle CANCEL, because it has same branch as transaction to be canceled.
For avoiding key collision, we add branch + '-' + 'sent-by' + CANCEL for cancel index key.
ACK has also same branch, but we won't do transaction for ACK, so it isn't problem.
*/
string key = request.Via.GetTopMostValue().Branch + '-' + request.Via.GetTopMostValue().SentBy;
if(request.RequestLine.Method == SIP_Methods.CANCEL){
key += "-CANCEL";
}
lock(m_pServerTransactions){
m_pServerTransactions.TryGetValue(key,out retVal);
}
// Don't match ACK for terminated transaction, in that case ACK must be passed to "core".
if(retVal != null && request.RequestLine.Method == SIP_Methods.ACK && retVal.State == SIP_TransactionState.Terminated){
retVal = null;
}
return retVal;
}
#endregion
#region method MatchCancelToTransaction
/// <summary>
/// Matches CANCEL requst to SIP server non-CANCEL transaction. Returns null if no match.
/// </summary>
/// <param name="cancelRequest">SIP CANCEL request.</param>
/// <returns>Returns CANCEL matching server transaction or null if no match.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>cancelTransaction</b> is null.</exception>
/// <exception cref="ArgumentException">Is raised when <b>cancelTransaction</b> has invalid.</exception>
public SIP_ServerTransaction MatchCancelToTransaction(SIP_Request cancelRequest)
{
if(cancelRequest == null){
throw new ArgumentNullException("cancelRequest");
}
if(cancelRequest.RequestLine.Method != SIP_Methods.CANCEL){
throw new ArgumentException("Argument 'cancelRequest' is not SIP CANCEL request.");
}
SIP_ServerTransaction retVal = null;
// NOTE: There we don't add '-CANCEL' because we want to get CANCEL matching transaction, not CANCEL
// transaction itself.
string key = cancelRequest.Via.GetTopMostValue().Branch + '-' + cancelRequest.Via.GetTopMostValue().SentBy;
lock(m_pServerTransactions){
m_pServerTransactions.TryGetValue(key,out retVal);
}
return retVal;
}
#endregion
#region method GetOrCreateDialog
/// <summary>
/// Gets existing or creates new dialog.
/// </summary>
/// <param name="transaction">Owner transaction what forces to create dialog.</param>
/// <param name="response">Response what forces to create dialog.</param>
/// <returns>Returns dialog.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>transaction</b> or <b>response</b> is null.</exception>
public SIP_Dialog GetOrCreateDialog(SIP_Transaction transaction,SIP_Response response)
{
if(transaction == null){
throw new ArgumentNullException("transaction");
}
if(response == null){
throw new ArgumentNullException("response");
}
string dialogID = "";
if(transaction is SIP_ServerTransaction){
dialogID = response.CallID + "-" + response.To.Tag + "-" + response.From.Tag;
}
else{
dialogID = response.CallID + "-" + response.From.Tag + "-" + response.To.Tag;
}
lock(m_pDialogs){
SIP_Dialog dialog = null;
m_pDialogs.TryGetValue(dialogID,out dialog);
// Dialog doesn't exist, create it.
if(dialog == null){
if(response.CSeq.RequestMethod.ToUpper() == SIP_Methods.INVITE){
dialog = new SIP_Dialog_Invite();
dialog.Init(m_pStack,transaction,response);
dialog.StateChanged += delegate(object s,EventArgs a){
if(dialog.State == SIP_DialogState.Terminated){
m_pDialogs.Remove(dialog.ID);
}
};
m_pDialogs.Add(dialog.ID,dialog);
}
else{
throw new ArgumentException("Method '" + response.CSeq.RequestMethod + "' has no dialog handler.");
}
}
return dialog;
}
}
#endregion
#region method RemoveDialog
/// <summary>
/// Removes specified dialog from dialogs collection.
/// </summary>
/// <param name="dialog">SIP dialog to remove.</param>
internal void RemoveDialog(SIP_Dialog dialog)
{
lock(m_pDialogs){
m_pDialogs.Remove(dialog.ID);
}
}
#endregion
#region method MatchDialog
/// <summary>
/// Matches specified SIP request to SIP dialog. If no matching dialog found, returns null.
/// </summary>
/// <param name="request">SIP request.</param>
/// <returns>Returns matched SIP dialog or null in no match found.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>request</b> is null.</exception>
internal SIP_Dialog MatchDialog(SIP_Request request)
{
if(request == null){
throw new ArgumentNullException("request");
}
SIP_Dialog dialog = null;
try{
string callID = request.CallID;
string localTag = request.To.Tag;
string remoteTag = request.From.Tag;
if(callID != null && localTag != null && remoteTag != null){
string dialogID = callID + "-" + localTag + "-" + remoteTag;
lock(m_pDialogs){
m_pDialogs.TryGetValue(dialogID,out dialog);
}
}
}
catch{
}
return dialog;
}
/// <summary>
/// Matches specified SIP response to SIP dialog. If no matching dialog found, returns null.
/// </summary>
/// <param name="response">SIP response.</param>
/// <returns>Returns matched SIP dialog or null in no match found.</returns>
/// <exception cref="ArgumentNullException">Is raised when <b>response</b> is null.</exception>
internal SIP_Dialog MatchDialog(SIP_Response response)
{
if(response == null){
throw new ArgumentNullException("response");
}
SIP_Dialog dialog = null;
try{
string callID = response.CallID;
string fromTag = response.From.Tag;
string toTag = response.To.Tag;
if(callID != null && fromTag != null && toTag != null){
string dialogID = callID + "-" + fromTag + "-" + toTag;
lock(m_pDialogs){
m_pDialogs.TryGetValue(dialogID,out dialog);
}
}
}
catch{
}
return dialog;
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets all available client transactions. This method is thread-safe.
/// </summary>
public SIP_ClientTransaction[] ClientTransactions
{
get{
lock(m_pClientTransactions){
SIP_ClientTransaction[] retVal = new SIP_ClientTransaction[m_pClientTransactions.Values.Count];
m_pClientTransactions.Values.CopyTo(retVal,0);
return retVal;
}
}
}
/// <summary>
/// Gets all available server transactions. This method is thread-safe.
/// </summary>
public SIP_ServerTransaction[] ServerTransactions
{
get{
lock(m_pServerTransactions){
SIP_ServerTransaction[] retVal = new SIP_ServerTransaction[m_pServerTransactions.Values.Count];
m_pServerTransactions.Values.CopyTo(retVal,0);
return retVal;
}
}
}
/// <summary>
/// Gets active dialogs. This method is thread-safe.
/// </summary>
public SIP_Dialog[] Dialogs
{
get{
lock(m_pDialogs){
SIP_Dialog[] retVal = new SIP_Dialog[m_pDialogs.Values.Count];
m_pDialogs.Values.CopyTo(retVal,0);
return retVal;
}
}
}
#endregion
}
}
| |
/* ====================================================================
*/
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Xml;
using System.IO;
namespace Oranikle.ReportDesigner
{
/// <summary>
/// Summary description for TableRowCtl.
/// </summary>
internal class TableRowCtl : Oranikle.ReportDesigner.Base.BaseControl, IProperty
{
private XmlNode _TableRow;
private DesignXmlDraw _Draw;
// flags for controlling whether syntax changed for a particular property
private bool fHidden, fToggle, fHeight;
private System.Windows.Forms.GroupBox grpBoxVisibility;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private Oranikle.Studio.Controls.CustomTextControl tbHidden;
private Oranikle.Studio.Controls.StyledComboBox cbToggle;
private Oranikle.Studio.Controls.StyledButton bHidden;
private System.Windows.Forms.Label label1;
private Oranikle.Studio.Controls.CustomTextControl tbRowHeight;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
internal TableRowCtl(DesignXmlDraw dxDraw, XmlNode tr)
{
_TableRow = tr;
_Draw = dxDraw;
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// Initialize form using the style node values
InitValues(tr);
}
private void InitValues(XmlNode node)
{
// Handle Width definition
this.tbRowHeight.Text = _Draw.GetElementValue(node, "Height", "");
// Handle Visiblity definition
XmlNode visNode = _Draw.GetNamedChildNode(node, "Visibility");
if (visNode != null)
{
this.tbHidden.Text = _Draw.GetElementValue(visNode, "Hidden", "");
this.cbToggle.Text = _Draw.GetElementValue(visNode, "ToggleItem", "");
}
IEnumerable list = _Draw.GetReportItems("//Textbox");
if (list != null)
{
foreach (XmlNode tNode in list)
{
XmlAttribute name = tNode.Attributes["Name"];
if (name != null && name.Value != null && name.Value.Length > 0)
cbToggle.Items.Add(name.Value);
}
}
// nothing has changed now
fHeight = fHidden = fToggle = false;
}
/// <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 Component 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.grpBoxVisibility = new System.Windows.Forms.GroupBox();
this.bHidden = new Oranikle.Studio.Controls.StyledButton();
this.cbToggle = new Oranikle.Studio.Controls.StyledComboBox();
this.tbHidden = new Oranikle.Studio.Controls.CustomTextControl();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.tbRowHeight = new Oranikle.Studio.Controls.CustomTextControl();
this.grpBoxVisibility.SuspendLayout();
this.SuspendLayout();
//
// grpBoxVisibility
//
this.grpBoxVisibility.Controls.Add(this.bHidden);
this.grpBoxVisibility.Controls.Add(this.cbToggle);
this.grpBoxVisibility.Controls.Add(this.tbHidden);
this.grpBoxVisibility.Controls.Add(this.label3);
this.grpBoxVisibility.Controls.Add(this.label2);
this.grpBoxVisibility.Location = new System.Drawing.Point(8, 8);
this.grpBoxVisibility.Name = "grpBoxVisibility";
this.grpBoxVisibility.Size = new System.Drawing.Size(432, 80);
this.grpBoxVisibility.TabIndex = 1;
this.grpBoxVisibility.TabStop = false;
this.grpBoxVisibility.Text = "Visibility";
//
// bHidden
//
this.bHidden.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(245)))), ((int)(((byte)(245)))), ((int)(((byte)(245)))));
this.bHidden.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(225)))), ((int)(((byte)(225)))), ((int)(((byte)(225)))));
this.bHidden.BackFillMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.bHidden.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(200)))), ((int)(((byte)(200)))), ((int)(((byte)(200)))));
this.bHidden.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.bHidden.Font = new System.Drawing.Font("Arial", 8.25F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.bHidden.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.bHidden.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bHidden.Location = new System.Drawing.Point(400, 23);
this.bHidden.Name = "bHidden";
this.bHidden.OverriddenSize = null;
this.bHidden.Size = new System.Drawing.Size(22, 21);
this.bHidden.TabIndex = 1;
this.bHidden.Tag = "visibility";
this.bHidden.Text = "fx";
this.bHidden.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.bHidden.UseVisualStyleBackColor = true;
this.bHidden.Click += new System.EventHandler(this.bExpr_Click);
//
// cbToggle
//
this.cbToggle.AutoAdjustItemHeight = false;
this.cbToggle.BorderColor = System.Drawing.Color.LightGray;
this.cbToggle.ConvertEnterToTabForDialogs = false;
this.cbToggle.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable;
this.cbToggle.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.cbToggle.Location = new System.Drawing.Point(168, 48);
this.cbToggle.Name = "cbToggle";
this.cbToggle.SeparatorColor = System.Drawing.Color.FromArgb(((int)(((byte)(90)))), ((int)(((byte)(90)))), ((int)(((byte)(90)))));
this.cbToggle.SeparatorMargin = 1;
this.cbToggle.SeparatorStyle = System.Drawing.Drawing2D.DashStyle.Solid;
this.cbToggle.SeparatorWidth = 1;
this.cbToggle.Size = new System.Drawing.Size(152, 21);
this.cbToggle.TabIndex = 2;
this.cbToggle.SelectedIndexChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
this.cbToggle.TextChanged += new System.EventHandler(this.cbToggle_SelectedIndexChanged);
//
// tbHidden
//
this.tbHidden.AddX = 0;
this.tbHidden.AddY = 0;
this.tbHidden.AllowSpace = false;
this.tbHidden.BorderColor = System.Drawing.Color.LightGray;
this.tbHidden.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbHidden.ChangeVisibility = false;
this.tbHidden.ChildControl = null;
this.tbHidden.ConvertEnterToTab = true;
this.tbHidden.ConvertEnterToTabForDialogs = false;
this.tbHidden.Decimals = 0;
this.tbHidden.DisplayList = new object[0];
this.tbHidden.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbHidden.Location = new System.Drawing.Point(168, 23);
this.tbHidden.Name = "tbHidden";
this.tbHidden.OnDropDownCloseFocus = true;
this.tbHidden.SelectType = 0;
this.tbHidden.Size = new System.Drawing.Size(224, 20);
this.tbHidden.TabIndex = 0;
this.tbHidden.UseValueForChildsVisibilty = false;
this.tbHidden.Value = true;
this.tbHidden.TextChanged += new System.EventHandler(this.tbHidden_TextChanged);
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 47);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(152, 23);
this.label3.TabIndex = 1;
this.label3.Text = "Toggle Item (Textbox name)";
//
// label2
//
this.label2.Location = new System.Drawing.Point(16, 22);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(120, 23);
this.label2.TabIndex = 0;
this.label2.Text = "Hidden (initial visibility)";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 106);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(80, 16);
this.label1.TabIndex = 2;
this.label1.Text = "Row Height";
//
// tbRowHeight
//
this.tbRowHeight.AddX = 0;
this.tbRowHeight.AddY = 0;
this.tbRowHeight.AllowSpace = false;
this.tbRowHeight.BorderColor = System.Drawing.Color.LightGray;
this.tbRowHeight.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.tbRowHeight.ChangeVisibility = false;
this.tbRowHeight.ChildControl = null;
this.tbRowHeight.ConvertEnterToTab = true;
this.tbRowHeight.ConvertEnterToTabForDialogs = false;
this.tbRowHeight.Decimals = 0;
this.tbRowHeight.DisplayList = new object[0];
this.tbRowHeight.HitText = Oranikle.Studio.Controls.HitText.String;
this.tbRowHeight.Location = new System.Drawing.Point(88, 104);
this.tbRowHeight.Name = "tbRowHeight";
this.tbRowHeight.OnDropDownCloseFocus = true;
this.tbRowHeight.SelectType = 0;
this.tbRowHeight.Size = new System.Drawing.Size(100, 20);
this.tbRowHeight.TabIndex = 3;
this.tbRowHeight.UseValueForChildsVisibilty = false;
this.tbRowHeight.Value = true;
this.tbRowHeight.TextChanged += new System.EventHandler(this.tbRowHeight_TextChanged);
//
// TableRowCtl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.Controls.Add(this.tbRowHeight);
this.Controls.Add(this.label1);
this.Controls.Add(this.grpBoxVisibility);
this.Name = "TableRowCtl";
this.Size = new System.Drawing.Size(472, 288);
this.grpBoxVisibility.ResumeLayout(false);
this.grpBoxVisibility.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public bool IsValid()
{
try
{
if (fHeight)
DesignerUtility.ValidateSize(this.tbRowHeight.Text, true, false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Height is Invalid");
return false;
}
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
{
if (vh.StartsWith("="))
{}
else
{
vh = vh.ToLower();
switch (vh)
{
case "true":
case "false":
break;
default:
MessageBox.Show(String.Format("{0} must be an expression or 'true' or 'false'", tbHidden.Text), "Hidden is Invalid");
return false;
}
}
}
}
return true;
}
public void Apply()
{
// take information in control and apply to all the style nodes
// Only change information that has been marked as modified;
// this way when group is selected it is possible to change just
// the items you want and keep the rest the same.
ApplyChanges(this._TableRow);
// nothing has changed now
fHeight = fHidden = fToggle = false;
}
private void ApplyChanges(XmlNode rNode)
{
if (fHidden || fToggle)
{
XmlNode visNode = _Draw.SetElement(rNode, "Visibility", null);
if (fHidden)
{
string vh = this.tbHidden.Text.Trim();
if (vh.Length > 0)
_Draw.SetElement(visNode, "Hidden", vh);
else
_Draw.RemoveElement(visNode, "Hidden");
}
if (fToggle)
_Draw.SetElement(visNode, "ToggleItem", this.cbToggle.Text);
}
if (fHeight) // already validated
_Draw.SetElement(rNode, "Height", this.tbRowHeight.Text);
}
private void tbHidden_TextChanged(object sender, System.EventArgs e)
{
fHidden = true;
}
private void tbRowHeight_TextChanged(object sender, System.EventArgs e)
{
fHeight = true;
}
private void cbToggle_SelectedIndexChanged(object sender, System.EventArgs e)
{
fToggle = true;
}
private void bExpr_Click(object sender, System.EventArgs e)
{
Button b = sender as Button;
if (b == null)
return;
Control c = null;
switch (b.Tag as string)
{
case "visibility":
c = tbHidden;
break;
}
if (c == null)
return;
using (DialogExprEditor ee = new DialogExprEditor(_Draw, c.Text, _TableRow))
{
DialogResult dr = ee.ShowDialog();
if (dr == DialogResult.OK)
c.Text = ee.Expression;
return;
}
}
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.ProfilePPTPBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfilePPTPProfilePPTPStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileEnabledState))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBProfileStatisticsByVirtual))]
public partial class LocalLBProfilePPTP : iControlInterface {
public LocalLBProfilePPTP() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// create
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void create(
string [] profile_names
) {
this.Invoke("create", new object [] {
profile_names});
}
public System.IAsyncResult Begincreate(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("create", new object[] {
profile_names}, callback, asyncState);
}
public void Endcreate(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_all_profiles
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void delete_all_profiles(
) {
this.Invoke("delete_all_profiles", new object [0]);
}
public System.IAsyncResult Begindelete_all_profiles(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_all_profiles", new object[0], callback, asyncState);
}
public void Enddelete_all_profiles(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// delete_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void delete_profile(
string [] profile_names
) {
this.Invoke("delete_profile", new object [] {
profile_names});
}
public System.IAsyncResult Begindelete_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("delete_profile", new object[] {
profile_names}, callback, asyncState);
}
public void Enddelete_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfilePPTPProfilePPTPStatistics get_all_statistics(
) {
object [] results = this.Invoke("get_all_statistics", new object [0]);
return ((LocalLBProfilePPTPProfilePPTPStatistics)(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[0], callback, asyncState);
}
public LocalLBProfilePPTPProfilePPTPStatistics Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfilePPTPProfilePPTPStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_csv_format_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_csv_format_state(
string [] profiles
) {
object [] results = this.Invoke("get_csv_format_state", new object [] {
profiles});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_csv_format_state(string [] profiles, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_csv_format_state", new object[] {
profiles}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_csv_format_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_default_profile(
string [] profile_names
) {
object [] results = this.Invoke("get_default_profile", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_default_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_default_profile", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_description(
string [] profile_names
) {
object [] results = this.Invoke("get_description", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_description(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_description", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_include_destination_ip_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileEnabledState [] get_include_destination_ip_state(
string [] profile_names
) {
object [] results = this.Invoke("get_include_destination_ip_state", new object [] {
profile_names});
return ((LocalLBProfileEnabledState [])(results[0]));
}
public System.IAsyncResult Beginget_include_destination_ip_state(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_include_destination_ip_state", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfileEnabledState [] Endget_include_destination_ip_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileEnabledState [])(results[0]));
}
//-----------------------------------------------------------------------
// get_list
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_list(
) {
object [] results = this.Invoke("get_list", new object [0]);
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_list(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_list", new object[0], callback, asyncState);
}
public string [] Endget_list(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_publisher_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string [] get_publisher_name(
string [] profile_names
) {
object [] results = this.Invoke("get_publisher_name", new object [] {
profile_names});
return ((string [])(results[0]));
}
public System.IAsyncResult Beginget_publisher_name(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_publisher_name", new object[] {
profile_names}, callback, asyncState);
}
public string [] Endget_publisher_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfilePPTPProfilePPTPStatistics get_statistics(
string [] profile_names
) {
object [] results = this.Invoke("get_statistics", new object [] {
profile_names});
return ((LocalLBProfilePPTPProfilePPTPStatistics)(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
profile_names}, callback, asyncState);
}
public LocalLBProfilePPTPProfilePPTPStatistics Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfilePPTPProfilePPTPStatistics)(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBProfileStatisticsByVirtual get_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
object [] results = this.Invoke("get_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
public System.IAsyncResult Beginget_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public LocalLBProfileStatisticsByVirtual Endget_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBProfileStatisticsByVirtual)(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// is_base_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_base_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_base_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_base_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_base_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_base_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// is_system_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public bool [] is_system_profile(
string [] profile_names
) {
object [] results = this.Invoke("is_system_profile", new object [] {
profile_names});
return ((bool [])(results[0]));
}
public System.IAsyncResult Beginis_system_profile(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("is_system_profile", new object[] {
profile_names}, callback, asyncState);
}
public bool [] Endis_system_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((bool [])(results[0]));
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void reset_statistics(
string [] profile_names
) {
this.Invoke("reset_statistics", new object [] {
profile_names});
}
public System.IAsyncResult Beginreset_statistics(string [] profile_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
profile_names}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics_by_virtual
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void reset_statistics_by_virtual(
string [] profile_names,
string [] [] virtual_names
) {
this.Invoke("reset_statistics_by_virtual", new object [] {
profile_names,
virtual_names});
}
public System.IAsyncResult Beginreset_statistics_by_virtual(string [] profile_names,string [] [] virtual_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics_by_virtual", new object[] {
profile_names,
virtual_names}, callback, asyncState);
}
public void Endreset_statistics_by_virtual(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_csv_format_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void set_csv_format_state(
string [] profiles,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_csv_format_state", new object [] {
profiles,
states});
}
public System.IAsyncResult Beginset_csv_format_state(string [] profiles,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_csv_format_state", new object[] {
profiles,
states}, callback, asyncState);
}
public void Endset_csv_format_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_default_profile
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void set_default_profile(
string [] profile_names,
string [] defaults
) {
this.Invoke("set_default_profile", new object [] {
profile_names,
defaults});
}
public System.IAsyncResult Beginset_default_profile(string [] profile_names,string [] defaults, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_default_profile", new object[] {
profile_names,
defaults}, callback, asyncState);
}
public void Endset_default_profile(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_description
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void set_description(
string [] profile_names,
string [] descriptions
) {
this.Invoke("set_description", new object [] {
profile_names,
descriptions});
}
public System.IAsyncResult Beginset_description(string [] profile_names,string [] descriptions, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_description", new object[] {
profile_names,
descriptions}, callback, asyncState);
}
public void Endset_description(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_include_destination_ip_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void set_include_destination_ip_state(
string [] profile_names,
LocalLBProfileEnabledState [] states
) {
this.Invoke("set_include_destination_ip_state", new object [] {
profile_names,
states});
}
public System.IAsyncResult Beginset_include_destination_ip_state(string [] profile_names,LocalLBProfileEnabledState [] states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_include_destination_ip_state", new object[] {
profile_names,
states}, callback, asyncState);
}
public void Endset_include_destination_ip_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_publisher_name
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/ProfilePPTP",
RequestNamespace="urn:iControl:LocalLB/ProfilePPTP", ResponseNamespace="urn:iControl:LocalLB/ProfilePPTP")]
public void set_publisher_name(
string [] profile_names,
string [] publishers
) {
this.Invoke("set_publisher_name", new object [] {
profile_names,
publishers});
}
public System.IAsyncResult Beginset_publisher_name(string [] profile_names,string [] publishers, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_publisher_name", new object[] {
profile_names,
publishers}, callback, asyncState);
}
public void Endset_publisher_name(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfilePPTP.ProfilePPTPStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBProfilePPTPProfilePPTPStatisticEntry
{
private string profile_nameField;
public string profile_name
{
get { return this.profile_nameField; }
set { this.profile_nameField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.ProfilePPTP.ProfilePPTPStatistics", Namespace = "urn:iControl")]
public partial class LocalLBProfilePPTPProfilePPTPStatistics
{
private LocalLBProfilePPTPProfilePPTPStatisticEntry [] statisticsField;
public LocalLBProfilePPTPProfilePPTPStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
// Copyright 2020 Google LLC.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Services;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// Shows how to download a set of reports from a list of accounts in parallel. If you need
/// to obtain a list of accounts, please see the GetAccountHierarchy or
/// ListAccessibleCustomers examples.";
/// </summary>
public class ParallelReportDownload : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="ParallelReportDownload"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The Google Ads customer Id.
/// </summary>
[Option("customerIds", Required = true, HelpText =
"The Google Ads customer IDs for which the call is made.")]
public IEnumerable<long> CustomerIds { get; set; }
/// <summary>
/// Optional login customer ID if your access to the CIDs is via a manager account.
/// </summary>
[Option("loginCustomerId", Required = false, HelpText =
"Optional login customer ID if your access to the CIDs is via a manager account.")]
public long? LoginCustomerId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The Google Ads customer IDs for which the call is made.
// Add more items to the array as desired.
options.CustomerIds = new long[]
{
long.Parse("INSERT_CUSTOMER_ID_1_HERE"),
long.Parse("INSERT_CUSTOMER_ID_2_HERE")
};
// Optional login customer ID if your access to the CIDs is via a manager
// account.
options.LoginCustomerId = long.Parse("INSERT_LOGIN_CUSTOMER_ID_HERE");
return 0;
});
ParallelReportDownload codeExample = new ParallelReportDownload();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerIds.ToArray(),
options.LoginCustomerId);
}
// Defines the Google Ads Query Language (GAQL) query strings to run for each customer ID.
private readonly Dictionary<string, string> GAQL_QUERY_STRINGS =
new Dictionary<string, string>()
{
{
"Campaign Query",
@"SELECT campaign.id, metrics.impressions, metrics.clicks
FROM campaign
WHERE segments.date DURING LAST_30_DAYS"
},
{
"Ad Group Query",
@"SELECT campaign.id, ad_group.id, metrics.impressions, metrics.clicks
FROM ad_group
WHERE segments.date DURING LAST_30_DAYS"
}
};
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"Shows how to download a set of reports from a list of accounts in parallel. If you " +
"need to obtain a list of accounts, please see the GetAccountHierarchy or " +
"ListAccessibleCustomers examples.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerIds">The Google Ads customer Id.</param>
/// <param name="loginCustomerId">Optional login customer ID if your access to the CIDs
/// is via a manager account.</param>
public void Run(GoogleAdsClient client, long[] customerIds, long? loginCustomerId)
{
// If a manager ID is supplied, update the login credentials.
if (loginCustomerId.HasValue)
{
client.Config.LoginCustomerId = loginCustomerId.ToString();
}
// Get the GoogleAdsService. A single client can be shared by all threads.
GoogleAdsServiceClient googleAdsService = client.GetService(
Services.V10.GoogleAdsService);
try
{
// Begin downloading reports and block program termination until complete.
Task task = RunDownloadParallelAsync(googleAdsService, customerIds);
task.Wait();
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
}
/// <summary>
/// Initiate all download requests, wait for their completion, and report the results.
/// </summary>
/// <param name="googleAdsService">The Google Ads service.</param>
/// <param name="customerIds">The list of customer IDs from which to request data.</param>
/// <returns>The asynchronous operation.</returns>
private async Task RunDownloadParallelAsync(
GoogleAdsServiceClient googleAdsService, long[] customerIds)
{
// List of all requests to ensure that we wait for the reports to complete on all
// customer IDs before proceeding.
ConcurrentBag<Task<bool>> tasks =
new ConcurrentBag<Task<bool>>();
// Collection of downloaded responses.
ConcurrentBag<ReportDownload> responses = new ConcurrentBag<ReportDownload>();
// IMPORTANT: You should avoid hitting the same customer ID in parallel. There are rate
// limits at the customer ID level which are much stricter than limits at the developer
// token level. Hitting these limits frequently enough will significantly reduce
// throughput as the client library will automatically retry with exponential back-off
// before failing the request.
Parallel.ForEach(GAQL_QUERY_STRINGS, query =>
{
Parallel.ForEach(customerIds, customerId =>
{
Console.WriteLine($"Requesting {query.Key} for CID {customerId}.");
// Issue an asynchronous search request and add it to the list of requests
// in progress.
tasks.Add(DownloadReportAsync(googleAdsService, customerId, query.Key,
query.Value, responses));
});
}
);
Console.WriteLine($"Awaiting results from {tasks.Count} requests...\n");
// Proceed only when all requests have completed.
await Task.WhenAll(tasks);
// Give a summary report for each successful download.
foreach (ReportDownload reportDownload in responses)
{
Console.WriteLine(reportDownload);
}
}
/// <summary>
/// Initiates one asynchronous report download.
/// </summary>
/// <param name="googleAdsService">The Google Ads service client.</param>
/// <param name="customerId">The customer ID from which data is requested.</param>
/// <param name="queryKey">The name of the query to be downloaded.</param>
/// <param name="queryValue">The query for the download request.</param>
/// <param name="responses">Collection of all successful report downloads.</param>
/// <returns>The asynchronous operation.</returns>
/// <exception cref="GoogleAdsException">Thrown if errors encountered in the execution of
/// the request.</exception>
private Task<bool> DownloadReportAsync(
GoogleAdsServiceClient googleAdsService, long customerId, string queryKey,
string queryValue, ConcurrentBag<ReportDownload> responses)
{
try
{
// Issue an asynchronous download request.
googleAdsService.SearchStream(
customerId.ToString(), queryValue,
delegate (SearchGoogleAdsStreamResponse resp)
{
// Store the results.
responses.Add(new ReportDownload()
{
CustomerId = customerId,
QueryKey = queryKey,
Response = resp
});
}
);
return Task.FromResult(true);
}
catch (AggregateException ae)
{
Console.WriteLine($"Download failed for {queryKey} and CID {customerId}!");
GoogleAdsException gae = GoogleAdsException.FromTaskException(ae);
var download = new ReportDownload()
{
CustomerId = customerId,
QueryKey = queryKey,
Exception = gae
};
if (gae != null)
{
Console.WriteLine($"Message: {gae.Message}");
Console.WriteLine($"Failure: {gae.Failure}");
Console.WriteLine($"Request ID: {gae.RequestId}");
download.Exception = gae;
}
else
{
download.Exception = ae;
}
responses.Add(download);
return Task.FromResult(false);
}
}
/// <summary>
/// Stores a result from a reporting API call. In this case we simply report a count of
/// the responses, but one could also write the response to a database/file, pass the
/// response on to another method for further processing, etc.
/// </summary>
private class ReportDownload
{
internal long CustomerId { get; set; }
internal string QueryKey { get; set; }
internal SearchGoogleAdsStreamResponse Response { get; set; }
internal Exception Exception { get; set; }
public override string ToString()
{
if (Exception != null)
{
return $"Download failed for {QueryKey} and CID {CustomerId}. " +
$"Exception: {Exception}";
}
else
{
return $"{QueryKey} downloaded for CID {CustomerId}: " +
$"{Response.Results.Count} rows returned.";
}
}
}
}
}
| |
/*
* 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.
*/
#pragma warning disable 618
namespace Apache.Ignite.Core.Tests.Cache.Query.Continuous
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Event;
using Apache.Ignite.Core.Cache.Query;
using Apache.Ignite.Core.Cache.Query.Continuous;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Impl.Cache.Event;
using Apache.Ignite.Core.Resource;
using NUnit.Framework;
/// <summary>
/// Tests for continuous query.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
[SuppressMessage("ReSharper", "PossibleNullReferenceException")]
[SuppressMessage("ReSharper", "StaticMemberInGenericType")]
public abstract class ContinuousQueryAbstractTest
{
/** Cache name: ATOMIC, backup. */
protected const string CACHE_ATOMIC_BACKUP = "atomic_backup";
/** Cache name: ATOMIC, no backup. */
protected const string CACHE_ATOMIC_NO_BACKUP = "atomic_no_backup";
/** Cache name: TRANSACTIONAL, backup. */
protected const string CACHE_TX_BACKUP = "transactional_backup";
/** Cache name: TRANSACTIONAL, no backup. */
protected const string CACHE_TX_NO_BACKUP = "transactional_no_backup";
/** Listener events. */
public static BlockingCollection<CallbackEvent> CB_EVTS = new BlockingCollection<CallbackEvent>();
/** Listener events. */
public static BlockingCollection<FilterEvent> FILTER_EVTS = new BlockingCollection<FilterEvent>();
/** First node. */
private IIgnite grid1;
/** Second node. */
private IIgnite grid2;
/** Cache on the first node. */
private ICache<int, BinarizableEntry> cache1;
/** Cache on the second node. */
private ICache<int, BinarizableEntry> cache2;
/** Cache name. */
private readonly string cacheName;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cacheName">Cache name.</param>
protected ContinuousQueryAbstractTest(string cacheName)
{
this.cacheName = cacheName;
}
/// <summary>
/// Set-up routine.
/// </summary>
[TestFixtureSetUp]
public void SetUp()
{
var cfg = new IgniteConfiguration(TestUtils.GetTestConfiguration())
{
BinaryConfiguration = new BinaryConfiguration
{
TypeConfigurations = new List<BinaryTypeConfiguration>
{
new BinaryTypeConfiguration(typeof(BinarizableEntry)),
new BinaryTypeConfiguration(typeof(BinarizableFilter)),
new BinaryTypeConfiguration(typeof(KeepBinaryFilter))
}
},
SpringConfigUrl = "config\\cache-query-continuous.xml",
IgniteInstanceName = "grid-1"
};
grid1 = Ignition.Start(cfg);
cache1 = grid1.GetCache<int, BinarizableEntry>(cacheName);
cfg.IgniteInstanceName = "grid-2";
grid2 = Ignition.Start(cfg);
cache2 = grid2.GetCache<int, BinarizableEntry>(cacheName);
}
/// <summary>
/// Tear-down routine.
/// </summary>
[TestFixtureTearDown]
public void TearDown()
{
Ignition.StopAll(true);
}
/// <summary>
/// Before-test routine.
/// </summary>
[SetUp]
public void BeforeTest()
{
CB_EVTS = new BlockingCollection<CallbackEvent>();
FILTER_EVTS = new BlockingCollection<FilterEvent>();
AbstractFilter<BinarizableEntry>.res = true;
AbstractFilter<BinarizableEntry>.err = false;
AbstractFilter<BinarizableEntry>.marshErr = false;
AbstractFilter<BinarizableEntry>.unmarshErr = false;
cache1.Remove(PrimaryKey(cache1));
cache1.Remove(PrimaryKey(cache2));
Assert.AreEqual(0, cache1.GetSize());
Assert.AreEqual(0, cache2.GetSize());
Console.WriteLine("Test started: " + TestContext.CurrentContext.Test.Name);
}
/// <summary>
/// Test arguments validation.
/// </summary>
[Test]
public void TestValidation()
{
Assert.Throws<ArgumentException>(() => { cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(null)); });
}
/// <summary>
/// Test multiple closes.
/// </summary>
[Test]
public void TestMultipleClose()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
Assert.AreNotEqual(key1, key2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
IDisposable qryHnd;
using (qryHnd = cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
qryHnd.Dispose();
}
/// <summary>
/// Test regular callback operations.
/// </summary>
[Test]
public void TestCallback()
{
CheckCallback(false);
}
/// <summary>
/// Check regular callback execution.
/// </summary>
/// <param name="loc"></param>
protected void CheckCallback(bool loc)
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>(), true) :
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckCallbackSingle(key1, Entry(key1), Entry(key1 + 1), CacheEntryEventType.Updated);
cache1.Remove(key1);
CheckCallbackSingle(key1, Entry(key1 + 1), Entry(key1 + 1), CacheEntryEventType.Removed);
// Put from remote node.
cache2.GetAndPut(key2, Entry(key2));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2), Entry(key2 + 1), CacheEntryEventType.Updated);
cache1.Remove(key2);
if (loc)
CheckNoCallback(100);
else
CheckCallbackSingle(key2, Entry(key2 + 1), Entry(key2 + 1), CacheEntryEventType.Removed);
}
cache1.Put(key1, Entry(key1));
CheckNoCallback(100);
cache1.Put(key2, Entry(key2));
CheckNoCallback(100);
}
/// <summary>
/// Test Ignite injection into callback.
/// </summary>
[Test]
public void TestCallbackInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
Assert.IsNull(cb.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb)))
{
Assert.IsNotNull(cb.ignite);
}
}
/// <summary>
/// Test binarizable filter logic.
/// </summary>
[Test]
public void TestFilterBinarizable()
{
CheckFilter(true, false);
}
/// <summary>
/// Test serializable filter logic.
/// </summary>
[Test]
public void TestFilterSerializable()
{
CheckFilter(false, false);
}
/// <summary>
/// Tests the defaults.
/// </summary>
[Test]
public void TestDefaults()
{
var qry = new ContinuousQuery<int, int>(null);
Assert.AreEqual(ContinuousQuery.DefaultAutoUnsubscribe, qry.AutoUnsubscribe);
Assert.AreEqual(ContinuousQuery.DefaultBufferSize, qry.BufferSize);
Assert.AreEqual(ContinuousQuery.DefaultTimeInterval, qry.TimeInterval);
Assert.IsFalse(qry.Local);
}
/// <summary>
/// Check filter.
/// </summary>
/// <param name="binarizable">Binarizable.</param>
/// <param name="loc">Local cache flag.</param>
protected void CheckFilter(bool binarizable, bool loc)
{
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc ?
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true) :
new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
int key2 = PrimaryKey(cache2);
cache1.GetAndPut(key2, Entry(key2));
if (loc)
{
CheckNoFilter(key2);
CheckNoCallback(key2);
}
else
{
CheckFilterSingle(key2, null, Entry(key2));
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
AbstractFilter<BinarizableEntry>.res = false;
// Ignored put from local node.
cache1.GetAndPut(key1, Entry(key1 + 1));
CheckFilterSingle(key1, Entry(key1), Entry(key1 + 1));
CheckNoCallback(100);
// Ignored put from remote node.
cache1.GetAndPut(key2, Entry(key2 + 1));
if (loc)
CheckNoFilter(100);
else
CheckFilterSingle(key2, Entry(key2), Entry(key2 + 1));
CheckNoCallback(100);
}
}
/// <summary>
/// Test binarizable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorBinarizable()
{
CheckFilterInvokeError(true);
}
/// <summary>
/// Test serializable filter error during invoke.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterInvokeErrorSerializable()
{
CheckFilterInvokeError(false);
}
/// <summary>
/// Check filter error handling logic during invoke.
/// </summary>
private void CheckFilterInvokeError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.err = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache1), Entry(1)));
// Put from remote node.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache2), Entry(1)));
}
}
/// <summary>
/// Test binarizable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorBinarizable()
{
CheckFilterMarshalError(true);
}
/// <summary>
/// Test serializable filter marshalling error.
/// </summary>
[Test]
public void TestFilterMarshalErrorSerializable()
{
CheckFilterMarshalError(false);
}
/// <summary>
/// Check filter marshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterMarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.marshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>)new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
Assert.Throws<Exception>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
/// <summary>
/// Test non-serializable filter error.
/// </summary>
[Test]
public void TestFilterNonSerializable()
{
CheckFilterNonSerializable(false);
}
/// <summary>
/// Test non-serializable filter behavior.
/// </summary>
/// <param name="loc"></param>
protected void CheckFilterNonSerializable(bool loc)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter = new LocalFilter();
ContinuousQuery<int, BinarizableEntry> qry = loc
? new ContinuousQuery<int, BinarizableEntry>(lsnr, filter, true)
: new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
if (loc)
{
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
}
}
else
{
Assert.Throws<BinaryObjectException>(() =>
{
using (cache1.QueryContinuous(qry))
{
// No-op.
}
});
}
}
/// <summary>
/// Test binarizable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorBinarizable()
{
CheckFilterUnmarshalError(true);
}
/// <summary>
/// Test serializable filter unmarshalling error.
/// </summary>
[Ignore("IGNITE-521")]
[Test]
public void TestFilterUnmarshalErrorSerializable()
{
CheckFilterUnmarshalError(false);
}
/// <summary>
/// Check filter unmarshal error handling.
/// </summary>
/// <param name="binarizable">Binarizable flag.</param>
private void CheckFilterUnmarshalError(bool binarizable)
{
AbstractFilter<BinarizableEntry>.unmarshErr = true;
ICacheEntryEventListener<int, BinarizableEntry> lsnr = new Listener<BinarizableEntry>();
ICacheEntryEventFilter<int, BinarizableEntry> filter =
binarizable ? (AbstractFilter<BinarizableEntry>) new BinarizableFilter() : new SerializableFilter();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(lsnr, filter);
using (cache1.QueryContinuous(qry))
{
// Local put must be fine.
int key1 = PrimaryKey(cache1);
cache1.GetAndPut(key1, Entry(key1));
CheckFilterSingle(key1, null, Entry(key1));
// Remote put must fail.
Assert.Throws<IgniteException>(() => cache1.GetAndPut(PrimaryKey(cache2), Entry(1)));
}
}
/// <summary>
/// Test Ignite injection into filters.
/// </summary>
[Test]
public void TestFilterInjection()
{
Listener<BinarizableEntry> cb = new Listener<BinarizableEntry>();
BinarizableFilter filter = new BinarizableFilter();
Assert.IsNull(filter.ignite);
using (cache1.QueryContinuous(new ContinuousQuery<int, BinarizableEntry>(cb, filter)))
{
// Local injection.
Assert.IsNotNull(filter.ignite);
// Remote injection.
cache1.GetAndPut(PrimaryKey(cache2), Entry(1));
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, 500));
Assert.IsNotNull(evt.ignite);
}
}
/// <summary>
/// Test "keep-binary" scenario.
/// </summary>
[Test]
public void TestKeepBinary()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
ContinuousQuery<int, IBinaryObject> qry = new ContinuousQuery<int, IBinaryObject>(
new Listener<IBinaryObject>(), new KeepBinaryFilter());
using (cache.QueryContinuous(qry))
{
// 1. Local put.
cache1.GetAndPut(PrimaryKey(cache1), Entry(1));
CallbackEvent cbEvt;
FilterEvent filterEvt;
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache1), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(1), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache1), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(1), (cbEvt.entries.First().Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
// 2. Remote put.
ClearEvents();
cache1.GetAndPut(PrimaryKey(cache2), Entry(2));
Assert.IsTrue(FILTER_EVTS.TryTake(out filterEvt, 500));
Assert.AreEqual(PrimaryKey(cache2), filterEvt.entry.Key);
Assert.AreEqual(null, filterEvt.entry.OldValue);
Assert.AreEqual(Entry(2), (filterEvt.entry.Value as IBinaryObject)
.Deserialize<BinarizableEntry>());
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
Assert.AreEqual(1, cbEvt.entries.Count);
Assert.AreEqual(PrimaryKey(cache2), cbEvt.entries.First().Key);
Assert.AreEqual(null, cbEvt.entries.First().OldValue);
Assert.AreEqual(Entry(2),
(cbEvt.entries.First().Value as IBinaryObject).Deserialize<BinarizableEntry>());
}
}
/// <summary>
/// Test value types (special handling is required for nulls).
/// </summary>
[Test]
public void TestValueTypes()
{
var cache = grid1.GetCache<int, int>(cacheName);
var qry = new ContinuousQuery<int, int>(new Listener<int>());
var key = PrimaryKey(cache);
using (cache.QueryContinuous(qry))
{
// First update
cache.Put(key, 1);
CallbackEvent cbEvt;
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
var cbEntry = cbEvt.entries.Single();
Assert.IsFalse(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(null, cbEntry.OldValue);
Assert.AreEqual(1, cbEntry.Value);
// Second update
cache.Put(key, 2);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(1, cbEntry.OldValue);
Assert.AreEqual(2, cbEntry.Value);
// Remove
cache.Remove(key);
Assert.IsTrue(CB_EVTS.TryTake(out cbEvt, 500));
cbEntry = cbEvt.entries.Single();
Assert.IsTrue(cbEntry.HasOldValue);
Assert.IsTrue(cbEntry.HasValue);
Assert.AreEqual(key, cbEntry.Key);
Assert.AreEqual(2, cbEntry.OldValue);
Assert.AreEqual(2, cbEntry.Value);
}
}
/// <summary>
/// Test whether buffer size works fine.
/// </summary>
[Test]
public void TestBufferSize()
{
// Put two remote keys in advance.
var rmtKeys = TestUtils.GetPrimaryKeys(cache2.Ignite, cache2.Name).Take(2).ToList();
ContinuousQuery<int, BinarizableEntry> qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(1000000);
using (cache1.QueryContinuous(qry))
{
qry.BufferSize = 2;
cache1.GetAndPut(rmtKeys[0], Entry(rmtKeys[0]));
CheckNoCallback(100);
cache1.GetAndPut(rmtKeys[1], Entry(rmtKeys[1]));
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, 1000));
Assert.AreEqual(2, evt.entries.Count);
var entryRmt0 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[0]); });
var entryRmt1 = evt.entries.Single(entry => { return entry.Key.Equals(rmtKeys[1]); });
Assert.AreEqual(rmtKeys[0], entryRmt0.Key);
Assert.IsNull(entryRmt0.OldValue);
Assert.AreEqual(Entry(rmtKeys[0]), entryRmt0.Value);
Assert.AreEqual(rmtKeys[1], entryRmt1.Key);
Assert.IsNull(entryRmt1.OldValue);
Assert.AreEqual(Entry(rmtKeys[1]), entryRmt1.Value);
}
cache1.Remove(rmtKeys[0]);
cache1.Remove(rmtKeys[1]);
}
/// <summary>
/// Test whether timeout works fine.
/// </summary>
[Test]
public void TestTimeout()
{
int key1 = PrimaryKey(cache1);
int key2 = PrimaryKey(cache2);
ContinuousQuery<int, BinarizableEntry> qry =
new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
qry.BufferSize = 2;
qry.TimeInterval = TimeSpan.FromMilliseconds(500);
using (cache1.QueryContinuous(qry))
{
// Put from local node.
cache1.GetAndPut(key1, Entry(key1));
CheckCallbackSingle(key1, null, Entry(key1), CacheEntryEventType.Created);
// Put from remote node.
cache1.GetAndPut(key2, Entry(key2));
CheckNoCallback(100);
CheckCallbackSingle(key2, null, Entry(key2), CacheEntryEventType.Created);
}
}
/// <summary>
/// Test whether nested Ignite API call from callback works fine.
/// </summary>
[Test]
public void TestNestedCallFromCallback()
{
var cache = cache1.WithKeepBinary<int, IBinaryObject>();
int key = PrimaryKey(cache1);
NestedCallListener cb = new NestedCallListener();
using (cache.QueryContinuous(new ContinuousQuery<int, IBinaryObject>(cb)))
{
cache1.GetAndPut(key, Entry(key));
cb.countDown.Wait();
}
cache.Remove(key);
}
/// <summary>
/// Tests the initial query.
/// </summary>
[Test]
public void TestInitialQuery()
{
// Scan query, GetAll
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.GetAll());
// Scan query, iterator
TestInitialQuery(new ScanQuery<int, BinarizableEntry>(new InitialQueryScanFilter()), cur => cur.ToList());
// Sql query, GetAll
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.GetAll());
// Sql query, iterator
TestInitialQuery(new SqlQuery(typeof(BinarizableEntry), "val < 33"), cur => cur.ToList());
// Text query, GetAll
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.GetAll());
// Text query, iterator
TestInitialQuery(new TextQuery(typeof(BinarizableEntry), "1*"), cur => cur.ToList());
// Test exception: invalid initial query
var ex = Assert.Throws<IgniteException>(
() => TestInitialQuery(new TextQuery(typeof (BinarizableEntry), "*"), cur => cur.GetAll()));
Assert.AreEqual("Cannot parse '*': '*' or '?' not allowed as first character in WildcardQuery", ex.Message);
}
/// <summary>
/// Tests the initial query.
/// </summary>
private void TestInitialQuery(QueryBase initialQry, Func<IQueryCursor<ICacheEntry<int, BinarizableEntry>>,
IEnumerable<ICacheEntry<int, BinarizableEntry>>> getAllFunc)
{
var qry = new ContinuousQuery<int, BinarizableEntry>(new Listener<BinarizableEntry>());
cache1.Put(11, Entry(11));
cache1.Put(12, Entry(12));
cache1.Put(33, Entry(33));
try
{
IContinuousQueryHandle<ICacheEntry<int, BinarizableEntry>> contQry;
using (contQry = cache1.QueryContinuous(qry, initialQry))
{
// Check initial query
var initialEntries =
getAllFunc(contQry.GetInitialQueryCursor()).Distinct().OrderBy(x => x.Key).ToList();
Assert.Throws<InvalidOperationException>(() => contQry.GetInitialQueryCursor());
Assert.AreEqual(2, initialEntries.Count);
for (int i = 0; i < initialEntries.Count; i++)
{
Assert.AreEqual(i + 11, initialEntries[i].Key);
Assert.AreEqual(i + 11, initialEntries[i].Value.val);
}
// Check continuous query
cache1.Put(44, Entry(44));
CheckCallbackSingle(44, null, Entry(44), CacheEntryEventType.Created);
}
Assert.Throws<ObjectDisposedException>(() => contQry.GetInitialQueryCursor());
contQry.Dispose(); // multiple dispose calls are ok
}
finally
{
cache1.Clear();
}
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
private void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal)
{
CheckFilterSingle(expKey, expOldVal, expVal, 1000);
ClearEvents();
}
/// <summary>
/// Check single filter event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected value.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckFilterSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal, int timeout)
{
FilterEvent evt;
Assert.IsTrue(FILTER_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(expKey, evt.entry.Key);
Assert.AreEqual(expOldVal, evt.entry.OldValue);
Assert.AreEqual(expVal, evt.entry.Value);
ClearEvents();
}
/// <summary>
/// Clears the events collection.
/// </summary>
private static void ClearEvents()
{
while (FILTER_EVTS.Count > 0)
FILTER_EVTS.Take();
}
/// <summary>
/// Ensure that no filter events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private static void CheckNoFilter(int timeout)
{
FilterEvent evt;
Assert.IsFalse(FILTER_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Check single callback event.
/// </summary>
/// <param name="expKey">Expected key.</param>
/// <param name="expOldVal">Expected old value.</param>
/// <param name="expVal">Expected new value.</param>
/// <param name="expType">Expected type.</param>
/// <param name="timeout">Timeout.</param>
private static void CheckCallbackSingle(int expKey, BinarizableEntry expOldVal, BinarizableEntry expVal,
CacheEntryEventType expType, int timeout = 1000)
{
CallbackEvent evt;
Assert.IsTrue(CB_EVTS.TryTake(out evt, timeout));
Assert.AreEqual(0, CB_EVTS.Count);
var e = evt.entries.Single();
Assert.AreEqual(expKey, e.Key);
Assert.AreEqual(expOldVal, e.OldValue);
Assert.AreEqual(expVal, e.Value);
Assert.AreEqual(expType, e.EventType);
}
/// <summary>
/// Ensure that no callback events are logged.
/// </summary>
/// <param name="timeout">Timeout.</param>
private void CheckNoCallback(int timeout)
{
CallbackEvent evt;
Assert.IsFalse(CB_EVTS.TryTake(out evt, timeout));
}
/// <summary>
/// Create entry.
/// </summary>
/// <param name="val">Value.</param>
/// <returns>Entry.</returns>
private static BinarizableEntry Entry(int val)
{
return new BinarizableEntry(val);
}
/// <summary>
/// Get primary key for cache.
/// </summary>
/// <param name="cache">Cache.</param>
/// <returns>Primary key.</returns>
private static int PrimaryKey<T>(ICache<int, T> cache)
{
return TestUtils.GetPrimaryKey(cache.Ignite, cache.Name);
}
/// <summary>
/// Creates object-typed event.
/// </summary>
private static ICacheEntryEvent<object, object> CreateEvent<T, V>(ICacheEntryEvent<T,V> e)
{
switch (e.EventType)
{
case CacheEntryEventType.Created:
return new CacheEntryCreateEvent<object, object>(e.Key, e.Value);
case CacheEntryEventType.Updated:
return new CacheEntryUpdateEvent<object, object>(e.Key, e.OldValue, e.Value);
default:
return new CacheEntryRemoveEvent<object, object>(e.Key, e.OldValue);
}
}
/// <summary>
/// Binarizable entry.
/// </summary>
public class BinarizableEntry
{
/** Value. */
public readonly int val;
/** <inheritDot /> */
public override int GetHashCode()
{
return val;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="val">Value.</param>
public BinarizableEntry(int val)
{
this.val = val;
}
/** <inheritDoc /> */
public override bool Equals(object obj)
{
return obj != null && obj is BinarizableEntry && ((BinarizableEntry)obj).val == val;
}
/** <inheritDoc /> */
public override string ToString()
{
return string.Format("BinarizableEntry [Val: {0}]", val);
}
}
/// <summary>
/// Abstract filter.
/// </summary>
[Serializable]
public abstract class AbstractFilter<V> : ICacheEntryEventFilter<int, V>
{
/** Result. */
public static volatile bool res = true;
/** Throw error on invocation. */
public static volatile bool err;
/** Throw error during marshalling. */
public static volatile bool marshErr;
/** Throw error during unmarshalling. */
public static volatile bool unmarshErr;
/** Grid. */
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public bool Evaluate(ICacheEntryEvent<int, V> evt)
{
if (err)
throw new Exception("Filter error.");
FILTER_EVTS.Add(new FilterEvent(ignite, CreateEvent(evt)));
return res;
}
}
/// <summary>
/// Filter which cannot be serialized.
/// </summary>
public class LocalFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
throw new BinaryObjectException("Expected");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
throw new BinaryObjectException("Expected");
}
}
/// <summary>
/// Binarizable filter.
/// </summary>
public class BinarizableFilter : AbstractFilter<BinarizableEntry>, IBinarizable
{
/** <inheritDoc /> */
public void WriteBinary(IBinaryWriter writer)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
/** <inheritDoc /> */
public void ReadBinary(IBinaryReader reader)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
}
/// <summary>
/// Serializable filter.
/// </summary>
[Serializable]
public class SerializableFilter : AbstractFilter<BinarizableEntry>, ISerializable
{
/// <summary>
/// Constructor.
/// </summary>
public SerializableFilter()
{
// No-op.
}
/// <summary>
/// Serialization constructor.
/// </summary>
/// <param name="info">Info.</param>
/// <param name="context">Context.</param>
protected SerializableFilter(SerializationInfo info, StreamingContext context)
{
if (unmarshErr)
throw new Exception("Filter unmarshalling error.");
}
/** <inheritDoc /> */
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
if (marshErr)
throw new Exception("Filter marshalling error.");
}
}
/// <summary>
/// Filter for "keep-binary" scenario.
/// </summary>
public class KeepBinaryFilter : AbstractFilter<IBinaryObject>
{
// No-op.
}
/// <summary>
/// Listener.
/// </summary>
public class Listener<V> : ICacheEntryEventListener<int, V>
{
[InstanceResource]
public IIgnite ignite;
/** <inheritDoc /> */
public void OnEvent(IEnumerable<ICacheEntryEvent<int, V>> evts)
{
CB_EVTS.Add(new CallbackEvent(evts.Select(CreateEvent).ToList()));
}
}
/// <summary>
/// Listener with nested Ignite API call.
/// </summary>
public class NestedCallListener : ICacheEntryEventListener<int, IBinaryObject>
{
/** Event. */
public readonly CountdownEvent countDown = new CountdownEvent(1);
public void OnEvent(IEnumerable<ICacheEntryEvent<int, IBinaryObject>> evts)
{
foreach (ICacheEntryEvent<int, IBinaryObject> evt in evts)
{
IBinaryObject val = evt.Value;
IBinaryType meta = val.GetBinaryType();
Assert.AreEqual(typeof(BinarizableEntry).FullName, meta.TypeName);
}
countDown.Signal();
}
}
/// <summary>
/// Filter event.
/// </summary>
public class FilterEvent
{
/** Grid. */
public IIgnite ignite;
/** Entry. */
public ICacheEntryEvent<object, object> entry;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="ignite">Grid.</param>
/// <param name="entry">Entry.</param>
public FilterEvent(IIgnite ignite, ICacheEntryEvent<object, object> entry)
{
this.ignite = ignite;
this.entry = entry;
}
}
/// <summary>
/// Callbakc event.
/// </summary>
public class CallbackEvent
{
/** Entries. */
public ICollection<ICacheEntryEvent<object, object>> entries;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="entries">Entries.</param>
public CallbackEvent(ICollection<ICacheEntryEvent<object, object>> entries)
{
this.entries = entries;
}
}
/// <summary>
/// ScanQuery filter for InitialQuery test.
/// </summary>
[Serializable]
private class InitialQueryScanFilter : ICacheEntryFilter<int, BinarizableEntry>
{
/** <inheritdoc /> */
public bool Invoke(ICacheEntry<int, BinarizableEntry> entry)
{
return entry.Key < 33;
}
}
}
}
| |
using System;
using System.Text.RegularExpressions;
using Spk.Common.Helpers.DateTime;
using Spk.Common.Helpers.String;
namespace Spk.Common.Helpers.Guard
{
/// <summary>
/// Guard methods that perform various validation against method arguments
/// </summary>
public static class ArgumentGuard
{
#region GuardIsWithinRange
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static double GuardIsWithinRange(
this double argument,
double lower,
double upper,
string paramName)
{
if (argument < lower || argument > upper)
{
throw new ArgumentOutOfRangeException(paramName,
$"Must be in the following range : {lower} to {upper}");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static float GuardIsWithinRange(
this float argument,
double lower,
double upper,
string paramName)
{
return (float)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static decimal GuardIsWithinRange(
this decimal argument,
double lower,
double upper,
string paramName)
{
return (decimal)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static short GuardIsWithinRange(
this short argument,
double lower,
double upper,
string paramName)
{
return (short)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static int GuardIsWithinRange(
this int argument,
double lower,
double upper,
string paramName)
{
return (int)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static long GuardIsWithinRange(
this long argument,
double lower,
double upper,
string paramName)
{
return (long)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ushort GuardIsWithinRange(
this ushort argument,
double lower,
double upper,
string paramName)
{
return (ushort)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static uint GuardIsWithinRange(
this uint argument,
double lower,
double upper,
string paramName)
{
return (uint)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is within range from <paramref name="lower"/> to <paramref name="upper"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="lower">The lower bound of the test</param>
/// <param name="upper">The upper bound of the test</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <remarks>The test on <paramref name="lower"/> and <paramref name="upper"/> is inclusive.</remarks>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ulong GuardIsWithinRange(
this ulong argument,
double lower,
double upper,
string paramName)
{
return (ulong)((double)argument).GuardIsWithinRange(lower, upper, paramName);
}
#endregion
#region GuardIsGreaterThan
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static double GuardIsGreaterThan(
this double argument,
double target,
string paramName)
{
if (argument <= target)
{
throw new ArgumentOutOfRangeException(paramName, $"Must be greater than {target}");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static float GuardIsGreaterThan(
this float argument,
double target,
string paramName)
{
return (float)((double)argument).GuardIsGreaterThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static decimal GuardIsGreaterThan(
this decimal argument,
double target,
string paramName)
{
return (decimal)((double)argument).GuardIsGreaterThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static short GuardIsGreaterThan(
this short argument,
double target,
string paramName)
{
return (short)((double)argument).GuardIsGreaterThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static int GuardIsGreaterThan(
this int argument,
double target,
string paramName)
{
return (int)((double)argument).GuardIsGreaterThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static long GuardIsGreaterThan(
this long argument,
double target,
string paramName)
{
return (long)((double)argument).GuardIsGreaterThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ushort GuardIsGreaterThan(
this ushort argument,
double target,
string paramName)
{
return (ushort)((double)argument).GuardIsGreaterThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static uint GuardIsGreaterThan(
this uint argument,
double target,
string paramName)
{
return (uint)((double)argument).GuardIsGreaterThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ulong GuardIsGreaterThan(
this ulong argument,
double target,
string paramName)
{
return (ulong)((double)argument).GuardIsGreaterThan(target, paramName);
}
#endregion
#region GuardIsGreaterThanOrEqualTo
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static double GuardIsGreaterThanOrEqualTo(
this double argument,
double target,
string paramName)
{
if (argument < target)
{
throw new ArgumentOutOfRangeException(paramName, $"Must be greater than or equal to {target}");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static float GuardIsGreaterThanOrEqualTo(
this float argument,
double target,
string paramName)
{
return (float)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static decimal GuardIsGreaterThanOrEqualTo(
this decimal argument,
double target,
string paramName)
{
return (decimal)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static short GuardIsGreaterThanOrEqualTo(
this short argument,
double target,
string paramName)
{
return (short)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static int GuardIsGreaterThanOrEqualTo(
this int argument,
double target,
string paramName)
{
return (int)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static long GuardIsGreaterThanOrEqualTo(
this long argument,
double target,
string paramName)
{
return (long)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ushort GuardIsGreaterThanOrEqualTo(
this ushort argument,
double target,
string paramName)
{
return (ushort)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static uint GuardIsGreaterThanOrEqualTo(
this uint argument,
double target,
string paramName)
{
return (uint)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is greater or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ulong GuardIsGreaterThanOrEqualTo(
this ulong argument,
double target,
string paramName)
{
return (ulong)((double)argument).GuardIsGreaterThanOrEqualTo(target, paramName);
}
#endregion
#region GuardIsLessThan
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static double GuardIsLessThan(
this double argument,
double target,
string paramName)
{
if (argument >= target)
{
throw new ArgumentOutOfRangeException(paramName, $"Must be less than {target}");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static float GuardIsLessThan(
this float argument,
double target,
string paramName)
{
return (float)((double)argument).GuardIsLessThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static decimal GuardIsLessThan(
this decimal argument,
double target,
string paramName)
{
return (decimal)((double)argument).GuardIsLessThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static short GuardIsLessThan(
this short argument,
double target,
string paramName)
{
return (short)((double)argument).GuardIsLessThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static int GuardIsLessThan(
this int argument,
double target,
string paramName)
{
return (int)((double)argument).GuardIsLessThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static long GuardIsLessThan(
this long argument,
double target,
string paramName)
{
return (long)((double)argument).GuardIsLessThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ushort GuardIsLessThan(
this ushort argument,
double target,
string paramName)
{
return (ushort)((double)argument).GuardIsLessThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static uint GuardIsLessThan(
this uint argument,
double target,
string paramName)
{
return (uint)((double)argument).GuardIsLessThan(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less than <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ulong GuardIsLessThan(
this ulong argument,
double target,
string paramName)
{
return (ulong)((double)argument).GuardIsLessThan(target, paramName);
}
#endregion
#region GuardIsLessThanOrEqualTo
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static double GuardIsLessThanOrEqualTo(
this double argument,
double target,
string paramName)
{
if (argument > target)
{
throw new ArgumentOutOfRangeException(paramName, $"Must be greater than or equal to {target}");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static float GuardIsLessThanOrEqualTo(
this float argument,
double target,
string paramName)
{
return (float)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static decimal GuardIsLessThanOrEqualTo(
this decimal argument,
double target,
string paramName)
{
return (decimal)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static short GuardIsLessThanOrEqualTo(
this short argument,
double target,
string paramName)
{
return (short)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static int GuardIsLessThanOrEqualTo(
this int argument,
double target,
string paramName)
{
return (int)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static long GuardIsLessThanOrEqualTo(
this long argument,
double target,
string paramName)
{
return (long)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ushort GuardIsLessThanOrEqualTo(
this ushort argument,
double target,
string paramName)
{
return (ushort)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static uint GuardIsLessThanOrEqualTo(
this uint argument,
double target,
string paramName)
{
return (uint)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> is less or equals to <paramref name="target"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The target that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static ulong GuardIsLessThanOrEqualTo(
this ulong argument,
double target,
string paramName)
{
return (ulong)((double)argument).GuardIsLessThanOrEqualTo(target, paramName);
}
#endregion
/// <summary>
/// Guards that <paramref name="argument"/> matches <paramref name="regex"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="regex">The regular expression that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when throwing <exception cref="ArgumentException"></exception></param>
/// <exception cref="ArgumentException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static string GuardMatchesRegex(
this string argument,
Regex regex,
string paramName)
{
regex.GuardIsNotNull(nameof(regex));
if (!regex.IsMatch(argument))
{
throw new ArgumentException($"Must match '{regex}'", paramName);
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> matches <paramref name="regex"/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="regex">The regex expression that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when throwing <exception cref="ArgumentException"></exception></param>
/// <exception cref="ArgumentException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static string GuardMatchesRegex(
this string argument,
string regex,
string paramName)
{
regex.GuardIsNotNull(nameof(regex));
return argument.GuardMatchesRegex(new Regex(regex), paramName);
}
/// <summary>
/// Guards that <paramref name="argument"/> date is later than <paramref name="target" /> date
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The date that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static System.DateTime GuardIsLaterThan(
this System.DateTime argument,
System.DateTime target,
string paramName)
{
if (argument <= target)
{
throw new ArgumentOutOfRangeException(paramName, $"Must be later than {target}");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> date is earlier than <paramref name="target" /> date/>
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="target">The date that <paramref name="argument"/> validates against</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static System.DateTime GuardIsEarlierThan(
this System.DateTime argument,
System.DateTime target,
string paramName)
{
if (argument >= target)
{
throw new ArgumentOutOfRangeException(paramName, $"Must be ealier than {target}");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> string is not null or all white spaces
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentOutOfRangeException">throwing</exception></param>
/// <exception cref="ArgumentOutOfRangeException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static string GuardIsNotNullOrWhiteSpace(
this string argument,
string paramName)
{
if (argument.IsNullOrWhiteSpace())
{
throw new ArgumentException("Must not be null or contain only white spaces", paramName);
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> not null
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="paramName">the name of the param beign tested. This is used when <exception cref="ArgumentNullException">throwing</exception></param>
/// <exception cref="ArgumentNullException">When test fails</exception>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static T GuardIsNotNull<T>(
this T argument,
string paramName)
{
if (ReferenceEquals(argument, null))
{
throw new ArgumentNullException(paramName, "Must not be null");
}
return argument;
}
/// <summary>
/// Guards that <paramref name="argument"/> not empty
/// </summary>
/// <param name="argument">the argument being guarded</param>
/// <param name="paramName">the name of the param being tested. This is used when <exception cref="ArgumentException"> throwing</exception></param>
/// <returns>Returns <paramref name="argument"/> as is, when the test succeeds</returns>
public static Guid GuardGuidIsNotEmpty(this Guid argument, string paramName)
{
if (argument == Guid.Empty)
{
throw new ArgumentException("Must not be empty", paramName);
}
return argument;
}
}
}
| |
// 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.Xml.Schema;
using System.Collections;
using System.Diagnostics;
namespace System.Xml
{
internal partial class XmlWrappingWriter : XmlWriter
{
//
// Fields
//
protected XmlWriter writer;
//
// Constructor
//
internal XmlWrappingWriter(XmlWriter baseWriter)
{
Debug.Assert(baseWriter != null);
this.writer = baseWriter;
}
//
// XmlWriter implementation
//
public override XmlWriterSettings Settings { get { return writer.Settings; } }
public override WriteState WriteState { get { return writer.WriteState; } }
public override XmlSpace XmlSpace { get { return writer.XmlSpace; } }
public override string XmlLang { get { return writer.XmlLang; } }
public override void WriteStartDocument()
{
writer.WriteStartDocument();
}
public override void WriteStartDocument(bool standalone)
{
writer.WriteStartDocument(standalone);
}
public override void WriteEndDocument()
{
writer.WriteEndDocument();
}
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
writer.WriteDocType(name, pubid, sysid, subset);
}
public override void WriteStartElement(string prefix, string localName, string ns)
{
writer.WriteStartElement(prefix, localName, ns);
}
public override void WriteEndElement()
{
writer.WriteEndElement();
}
public override void WriteFullEndElement()
{
writer.WriteFullEndElement();
}
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
writer.WriteStartAttribute(prefix, localName, ns);
}
public override void WriteEndAttribute()
{
writer.WriteEndAttribute();
}
public override void WriteCData(string text)
{
writer.WriteCData(text);
}
public override void WriteComment(string text)
{
writer.WriteComment(text);
}
public override void WriteProcessingInstruction(string name, string text)
{
writer.WriteProcessingInstruction(name, text);
}
public override void WriteEntityRef(string name)
{
writer.WriteEntityRef(name);
}
public override void WriteCharEntity(char ch)
{
writer.WriteCharEntity(ch);
}
public override void WriteWhitespace(string ws)
{
writer.WriteWhitespace(ws);
}
public override void WriteString(string text)
{
writer.WriteString(text);
}
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
writer.WriteSurrogateCharEntity(lowChar, highChar);
}
public override void WriteChars(char[] buffer, int index, int count)
{
writer.WriteChars(buffer, index, count);
}
public override void WriteRaw(char[] buffer, int index, int count)
{
writer.WriteRaw(buffer, index, count);
}
public override void WriteRaw(string data)
{
writer.WriteRaw(data);
}
public override void WriteBase64(byte[] buffer, int index, int count)
{
writer.WriteBase64(buffer, index, count);
}
public override void Flush()
{
writer.Flush();
}
public override string LookupPrefix(string ns)
{
return writer.LookupPrefix(ns);
}
public override void WriteValue(object value)
{
writer.WriteValue(value);
}
public override void WriteValue(string value)
{
writer.WriteValue(value);
}
public override void WriteValue(bool value)
{
writer.WriteValue(value);
}
public override void WriteValue(DateTimeOffset value)
{
writer.WriteValue(value);
}
public override void WriteValue(double value)
{
writer.WriteValue(value);
}
public override void WriteValue(float value)
{
writer.WriteValue(value);
}
public override void WriteValue(decimal value)
{
writer.WriteValue(value);
}
public override void WriteValue(int value)
{
writer.WriteValue(value);
}
public override void WriteValue(long value)
{
writer.WriteValue(value);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)writer).Dispose();
}
}
}
}
| |
using spreadsheet = DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using System.IO;
using Signum.Utilities.DataStructures;
using Signum.Utilities.Reflection;
using Signum.Entities.Excel;
namespace Signum.Engine.Excel;
public static class PlainExcelGenerator
{
public static byte[] Template { get; set; } = null!;
public static CellBuilder CellBuilder { get; set; } = null!;
static PlainExcelGenerator()
{
SetTemplate(typeof(PlainExcelGenerator).Assembly.GetManifestResourceStream("Signum.Engine.Excel.plainExcelTemplate.xlsx")!);
}
public static void SetTemplate(Stream templateStream)
{
Template = templateStream.ReadAllBytes();
MemoryStream memoryStream = new MemoryStream();
memoryStream.WriteAllBytes(Template);
using (SpreadsheetDocument document = SpreadsheetDocument.Open(memoryStream, true))
{
document.PackageProperties.Creator = "";
document.PackageProperties.LastModifiedBy = "";
WorkbookPart workbookPart = document.WorkbookPart!;
WorksheetPart worksheetPart = document.GetWorksheetPartById("rId1");
Worksheet worksheet = worksheetPart.Worksheet;
CellBuilder = new CellBuilder()
{
CellFormatCount = document.WorkbookPart!.WorkbookStylesPart!.Stylesheet.CellFormats!.Count!,
DefaultStyles = new Dictionary<DefaultStyle, UInt32Value>
{
{ DefaultStyle.Title, worksheet.FindCell("A1").StyleIndex! },
{ DefaultStyle.Header, worksheet.FindCell("A2").StyleIndex! },
{ DefaultStyle.Date, worksheet.FindCell("B3").StyleIndex! },
{ DefaultStyle.DateTime, worksheet.FindCell("C3").StyleIndex! },
{ DefaultStyle.Text, worksheet.FindCell("D3").StyleIndex! },
{ DefaultStyle.General, worksheet.FindCell("E3").StyleIndex! },
{ DefaultStyle.Boolean, worksheet.FindCell("E3").StyleIndex! },
{ DefaultStyle.Enum, worksheet.FindCell("E3").StyleIndex! },
{ DefaultStyle.Number, worksheet.FindCell("F3").StyleIndex! },
{ DefaultStyle.Decimal, worksheet.FindCell("G3").StyleIndex! },
{ DefaultStyle.Percentage, worksheet.FindCell("H3").StyleIndex! },
{ DefaultStyle.Time, worksheet.FindCell("I3").StyleIndex! },
}
};
}
}
public static byte[] WritePlainExcel(ResultTable results,string title)
{
using (MemoryStream ms = new MemoryStream())
{
WritePlainExcel(results, ms,title);
return ms.ToArray();
}
}
public static void WritePlainExcel(ResultTable results, string fileName,string title)
{
using (FileStream fs = File.Create(fileName))
WritePlainExcel(results, fs,title);
}
static void WritePlainExcel(ResultTable results, Stream stream, string title)
{
stream.WriteAllBytes(Template);
if (results == null)
throw new ApplicationException(ExcelMessage.ThereAreNoResultsToWrite.NiceToString());
using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, true))
{
document.PackageProperties.Creator = "";
document.PackageProperties.LastModifiedBy = "";
WorkbookPart workbookPart = document.WorkbookPart!;
WorksheetPart worksheetPart = document.GetWorksheetPartById("rId1");
worksheetPart.Worksheet = new Worksheet();
worksheetPart.Worksheet.Append(new Columns(results.Columns.Select((c, i) => new spreadsheet.Column()
{
Min = (uint)i + 1,
Max = (uint)i + 1,
Width = GetColumnWidth(c.Column.Type),
BestFit = true,
CustomWidth = true
}).ToArray()));
Dictionary<ResultColumn, (DefaultStyle defaultStyle, UInt32Value styleIndex)> indexes =
results.Columns.ToDictionary(c => c, c => CellBuilder.GetDefaultStyleAndIndex(c));
var ss = document.WorkbookPart!.WorkbookStylesPart!.Stylesheet;
{
var maxIndex = ss.NumberingFormats!.ChildElements.Cast<NumberingFormat>()
.Max(f => (uint)f.NumberFormatId!) + 1;
var decimalCellFormat = ss.CellFormats!.ElementAt((int)(uint)CellBuilder.DefaultStyles[DefaultStyle.Decimal]);
foreach (var kvp in CellBuilder.CustomDecimalStyles)
{
var numberingFormat = new NumberingFormat
{
NumberFormatId = maxIndex++,
FormatCode = kvp.Key
};
ss.NumberingFormats.AppendChild(numberingFormat);
var cellFormat = (CellFormat)decimalCellFormat.CloneNode(false);
cellFormat.NumberFormatId = numberingFormat.NumberFormatId;
ss.CellFormats!.AppendChild(cellFormat);
ss.CellFormats.Count = (uint)ss.CellFormats.ChildElements.Count;
if (ss.CellFormats.Count != kvp.Value + 1)
{
throw new InvalidOperationException("Unexpected CellFormats count");
}
}
}
worksheetPart.Worksheet.Append(new Sequence<Row>()
{
new [] { CellBuilder.Cell(title,DefaultStyle.Title) }.ToRow(),
(from c in results.Columns
select CellBuilder.Cell(c.Column.DisplayName, DefaultStyle.Header)).ToRow(),
from r in results.Rows
select (from c in results.Columns
let t = indexes.GetOrThrow(c)
select CellBuilder.Cell(r[c], t.defaultStyle,t.styleIndex)).ToRow()
}.ToSheetData());
workbookPart.Workbook.Save();
document.Close();
}
}
public static byte[] WritePlainExcel<T>(IEnumerable<T> results)
{
using (MemoryStream ms = new MemoryStream())
{
WritePlainExcel(results, ms);
return ms.ToArray();
}
}
public static void WritePlainExcel<T>(IEnumerable<T> results, string fileName)
{
using (FileStream fs = File.Create(fileName))
WritePlainExcel(results, fs);
}
public static void WritePlainExcel<T>(IEnumerable<T> results, Stream stream)
{
stream.WriteAllBytes(Template);
if (results == null)
throw new ApplicationException(ExcelMessage.ThereAreNoResultsToWrite.NiceToString());
var members = MemberEntryFactory.GenerateList<T>(MemberOptions.Fields | MemberOptions.Properties | MemberOptions.Getter);
var formats = members.ToDictionary(a => a.Name, a => a.MemberInfo.GetCustomAttribute<FormatAttribute>()?.Format);
using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, true))
{
document.PackageProperties.Creator = "";
document.PackageProperties.LastModifiedBy = "";
WorkbookPart workbookPart = document.WorkbookPart!;
WorksheetPart worksheetPart = document.GetWorksheetPartById("rId1");
worksheetPart.Worksheet = new Worksheet();
worksheetPart.Worksheet.Append(new Columns(members.Select((c, i) => new spreadsheet.Column()
{
Min = (uint)i + 1,
Max = (uint)i + 1,
Width = GetColumnWidth(c.MemberInfo.ReturningType()),
BestFit = true,
CustomWidth = true
}).ToArray()));
worksheetPart.Worksheet.Append(new Sequence<Row>()
{
(from c in members
select CellBuilder.Cell(c.Name, DefaultStyle.Header)).ToRow(),
from r in results
select (from c in members
let template = formats.TryGetCN(c.Name) == "d" ? DefaultStyle.Date : CellBuilder.GetDefaultStyle(c.MemberInfo.ReturningType())
select CellBuilder.Cell(c.Getter!(r), template)).ToRow()
}.ToSheetData());
workbookPart.Workbook.Save();
document.Close();
}
}
static double GetColumnWidth(Type type)
{
type = type.UnNullify();
if (type == typeof(DateTime))
return 20;
if (type == typeof(DateOnly))
return 15;
if (type == typeof(string))
return 50;
if (type.IsLite())
return 50;
return 10;
}
public static List<T> ReadPlainExcel<T>(Stream stream, Func<string[], T> selector)
{
using (SpreadsheetDocument document = SpreadsheetDocument.Open(stream, false))
{
WorkbookPart workbookPart = document.WorkbookPart!;
WorksheetPart worksheetPart = document.GetWorksheetPartById("rId1");
var data = worksheetPart.Worksheet.Descendants<SheetData>().Single();
return data.Descendants<Row>().Skip(1).Select(r => selector(r.Descendants<Cell>().Select(c => document.GetCellValue(c)).ToArray())).ToList();
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using ClientDependency.Core.Config;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Umbraco.Core;
using Umbraco.Core.Configuration;
using Umbraco.Core.Configuration.UmbracoSettings;
using Umbraco.Core.IO;
using Umbraco.Web.Features;
using Umbraco.Web.HealthCheck;
using Umbraco.Web.Models.ContentEditing;
using Umbraco.Web.Mvc;
using Umbraco.Web.PropertyEditors;
using Umbraco.Web.Trees;
using Umbraco.Web.WebServices;
using Constants = Umbraco.Core.Constants;
namespace Umbraco.Web.Editors
{
/// <summary>
/// Used to collect the server variables for use in the back office angular app
/// </summary>
internal class BackOfficeServerVariables
{
private readonly UrlHelper _urlHelper;
private readonly ApplicationContext _applicationContext;
private readonly HttpContextBase _httpContext;
private readonly IOwinContext _owinContext;
public BackOfficeServerVariables(UrlHelper urlHelper, ApplicationContext applicationContext, IUmbracoSettingsSection umbracoSettings)
{
_urlHelper = urlHelper;
_applicationContext = applicationContext;
_httpContext = _urlHelper.RequestContext.HttpContext;
_owinContext = _httpContext.GetOwinContext();
}
/// <summary>
/// Returns the server variables for non-authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> BareMinimumServerVariables()
{
//this is the filter for the keys that we'll keep based on the full version of the server vars
var keepOnlyKeys = new Dictionary<string, string[]>
{
{"umbracoUrls", new[] {"authenticationApiBaseUrl", "serverVarsJs", "externalLoginsUrl", "currentUserApiBaseUrl"}},
{"umbracoSettings", new[] {"allowPasswordReset", "imageFileTypes", "maxFileSize", "loginBackgroundImage", "canSendRequiredEmail"}},
{"application", new[] {"applicationPath", "cacheBuster"}},
{"isDebuggingEnabled", new string[] { }},
{"features", new [] {"disabledFeatures"}}
};
//now do the filtering...
var defaults = GetServerVariables();
foreach (var key in defaults.Keys.ToArray())
{
if (keepOnlyKeys.ContainsKey(key) == false)
{
defaults.Remove(key);
}
else
{
var asDictionary = defaults[key] as IDictionary;
if (asDictionary != null)
{
var toKeep = keepOnlyKeys[key];
foreach (var k in asDictionary.Keys.Cast<string>().ToArray())
{
if (toKeep.Contains(k) == false)
{
asDictionary.Remove(k);
}
}
}
}
}
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
// so based on compat and how things are currently working we need to replace the serverVarsJs one
((Dictionary<string, object>)defaults["umbracoUrls"])["serverVarsJs"] = _urlHelper.Action("ServerVariables", "BackOffice");
return defaults;
}
/// <summary>
/// Returns the server variables for authenticated users
/// </summary>
/// <returns></returns>
internal Dictionary<string, object> GetServerVariables()
{
var defaultVals = new Dictionary<string, object>
{
{
"umbracoUrls", new Dictionary<string, object>
{
//TODO: Add 'umbracoApiControllerBaseUrl' which people can use in JS
// to prepend their URL. We could then also use this in our own resources instead of
// having each url defined here explicitly - we can do that in v8! for now
// for umbraco services we'll stick to explicitly defining the endpoints.
{"externalLoginsUrl", _urlHelper.Action("ExternalLogin", "BackOffice")},
{"externalLinkLoginsUrl", _urlHelper.Action("LinkLogin", "BackOffice")},
{"legacyTreeJs", _urlHelper.Action("LegacyTreeJs", "BackOffice")},
{"manifestAssetList", _urlHelper.Action("GetManifestAssetList", "BackOffice")},
{"gridConfig", _urlHelper.Action("GetGridConfig", "BackOffice")},
//TODO: This is ultra confusing! this same key is used for different things, when returning the full app when authenticated it is this URL but when not auth'd it's actually the ServerVariables address
{"serverVarsJs", _urlHelper.Action("Application", "BackOffice")},
//API URLs
{
"packagesRestApiBaseUrl", Constants.PackageRepository.RestApiBaseUrl
},
{
"redirectUrlManagementApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RedirectUrlManagementController>(
controller => controller.GetEnableState())
},
{
"tourApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TourController>(
controller => controller.GetTours())
},
{
"embedApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RteEmbedController>(
controller => controller.GetEmbed("", 0, 0))
},
{
"userApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UsersController>(
controller => controller.PostSaveUser(null))
},
{
"userGroupsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UserGroupsController>(
controller => controller.PostSaveUserGroup(null))
},
{
"contentApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentController>(
controller => controller.PostSave(null))
},
{
"mediaApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaController>(
controller => controller.GetRootMedia())
},
{
"imagesApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ImagesController>(
controller => controller.GetBigThumbnail(0))
},
{
"sectionApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<SectionController>(
controller => controller.GetSections())
},
{
"treeApplicationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ApplicationTreeController>(
controller => controller.GetApplicationTrees(null, null, null, true))
},
{
"contentTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"mediaTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTypeController>(
controller => controller.GetAllowedChildren(0))
},
{
"macroApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MacroController>(
controller => controller.GetMacroParameters(0))
},
{
"authenticationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<AuthenticationController>(
controller => controller.PostLogin(null))
},
{
"currentUserApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CurrentUserController>(
controller => controller.PostChangePassword(null))
},
{
"legacyApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LegacyController>(
controller => controller.DeleteLegacyItem(null, null, null))
},
{
"entityApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<EntityController>(
controller => controller.GetById(0, UmbracoEntityTypes.Media))
},
{
"dataTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DataTypeController>(
controller => controller.GetById(0))
},
{
"dashboardApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DashboardController>(
controller => controller.GetDashboard(null))
},
{
"logApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<LogController>(
controller => controller.GetEntityLog(0))
},
{
"memberApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberController>(
controller => controller.GetByKey(Guid.Empty))
},
{
"packageInstallApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<PackageInstallController>(
controller => controller.Fetch(string.Empty))
},
{
"relationApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RelationController>(
controller => controller.GetById(0))
},
{
"rteApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<RichTextPreValueController>(
controller => controller.GetConfiguration())
},
{
"stylesheetApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<StylesheetController>(
controller => controller.GetAll())
},
{
"memberTypeApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTypeController>(
controller => controller.GetAllTypes())
},
{
"updateCheckApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<UpdateCheckController>(
controller => controller.GetCheck())
},
{
"templateApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateController>(
controller => controller.GetById(0))
},
{
"memberTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MemberTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"mediaTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<MediaTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"contentTreeBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ContentTreeController>(
controller => controller.GetNodes("-1", null))
},
{
"tagsDataBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TagsDataController>(
controller => controller.GetTags(""))
},
{
"examineMgmtBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<ExamineManagementApiController>(
controller => controller.GetIndexerDetails())
},
{
"xmlDataIntegrityBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<XmlDataIntegrityController>(
controller => controller.CheckContentXmlTable())
},
{
"healthCheckBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HealthCheckController>(
controller => controller.GetAllHealthChecks())
},
{
"templateQueryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<TemplateQueryController>(
controller => controller.PostTemplateQuery(null))
},
{
"codeFileApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<CodeFileController>(
controller => controller.GetByPath("", ""))
},
{
"dictionaryApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<DictionaryController>(
controller => controller.DeleteById(int.MaxValue))
},
{
"helpApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<HelpController>(
controller => controller.GetContextHelpForPage("","",""))
},
{
"backOfficeAssetsApiBaseUrl", _urlHelper.GetUmbracoApiServiceBaseUrl<BackOfficeAssetsController>(
controller => controller.GetSupportedMomentLocales())
}
}
},
{
"umbracoSettings", new Dictionary<string, object>
{
{"umbracoPath", GlobalSettings.Path},
{"mediaPath", IOHelper.ResolveUrl(SystemDirectories.Media).TrimEnd('/')},
{"appPluginsPath", IOHelper.ResolveUrl(SystemDirectories.AppPlugins).TrimEnd('/')},
{
"imageFileTypes",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.ImageFileTypes)
},
{
"disallowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.DisallowedUploadFiles)
},
{
"allowedUploadFiles",
string.Join(",", UmbracoConfig.For.UmbracoSettings().Content.AllowedUploadFiles)
},
{
"maxFileSize",
GetMaxRequestLength()
},
{"keepUserLoggedIn", UmbracoConfig.For.UmbracoSettings().Security.KeepUserLoggedIn},
{"usernameIsEmail", UmbracoConfig.For.UmbracoSettings().Security.UsernameIsEmail},
{"cssPath", IOHelper.ResolveUrl(SystemDirectories.Css).TrimEnd('/')},
{"allowPasswordReset", UmbracoConfig.For.UmbracoSettings().Security.AllowPasswordReset},
{"loginBackgroundImage", UmbracoConfig.For.UmbracoSettings().Content.LoginBackgroundImage},
{"showUserInvite", EmailSender.CanSendRequiredEmail},
{"canSendRequiredEmail", EmailSender.CanSendRequiredEmail},
}
},
{
"umbracoPlugins", new Dictionary<string, object>
{
{"trees", GetTreePluginsMetaData()}
}
},
{
"isDebuggingEnabled", _httpContext.IsDebuggingEnabled
},
{
"application", GetApplicationState()
},
{
"externalLogins", new Dictionary<string, object>
{
{
"providers", _owinContext.Authentication.GetExternalAuthenticationTypes()
.Where(p => p.Properties.ContainsKey("UmbracoBackOffice"))
.Select(p => new
{
authType = p.AuthenticationType, caption = p.Caption,
//TODO: Need to see if this exposes any sensitive data!
properties = p.Properties
})
.ToArray()
}
}
},
{
"features", new Dictionary<string,object>
{
{
"disabledFeatures", new Dictionary<string,object>
{
{ "disableTemplates", FeaturesResolver.Current.Features.Disabled.DisableTemplates}
}
}
}
}
};
return defaultVals;
}
private IEnumerable<Dictionary<string, string>> GetTreePluginsMetaData()
{
var treeTypes = TreeControllerTypes.Value;
//get all plugin trees with their attributes
var treesWithAttributes = treeTypes.Select(x => new
{
tree = x,
attributes =
x.GetCustomAttributes(false)
}).ToArray();
var pluginTreesWithAttributes = treesWithAttributes
//don't resolve any tree decorated with CoreTreeAttribute
.Where(x => x.attributes.All(a => (a is CoreTreeAttribute) == false))
//we only care about trees with the PluginControllerAttribute
.Where(x => x.attributes.Any(a => a is PluginControllerAttribute))
.ToArray();
return (from p in pluginTreesWithAttributes
let treeAttr = p.attributes.OfType<TreeAttribute>().Single()
let pluginAttr = p.attributes.OfType<PluginControllerAttribute>().Single()
select new Dictionary<string, string>
{
{"alias", treeAttr.Alias}, {"packageFolder", pluginAttr.AreaName}
}).ToArray();
}
/// <summary>
/// A lazy reference to all tree controller types
/// </summary>
/// <remarks>
/// We are doing this because if we constantly resolve the tree controller types from the PluginManager it will re-scan and also re-log that
/// it's resolving which is unecessary and annoying.
/// </remarks>
private static readonly Lazy<IEnumerable<Type>> TreeControllerTypes = new Lazy<IEnumerable<Type>>(() => PluginManager.Current.ResolveAttributedTreeControllers().ToArray());
/// <summary>
/// Returns the server variables regarding the application state
/// </summary>
/// <returns></returns>
private Dictionary<string, object> GetApplicationState()
{
var app = new Dictionary<string, object>
{
{"assemblyVersion", UmbracoVersion.AssemblyVersion}
};
var version = UmbracoVersion.GetSemanticVersion().ToSemanticString();
//the value is the hash of the version, cdf version and the configured state
app.Add("cacheBuster", $"{version}.{_applicationContext.IsConfigured}.{ClientDependencySettings.Instance.Version}".GenerateHash());
app.Add("version", version);
//useful for dealing with virtual paths on the client side when hosted in virtual directories especially
app.Add("applicationPath", _httpContext.Request.ApplicationPath.EnsureEndsWith('/'));
//add the server's GMT time offset in minutes
app.Add("serverTimeOffset", Convert.ToInt32(DateTimeOffset.Now.Offset.TotalMinutes));
return app;
}
private string GetMaxRequestLength()
{
var section = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
if (section == null) return string.Empty;
return section.MaxRequestLength.ToString();
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Text;
using System.Runtime.InteropServices;
using System.Globalization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.IO
{
public static class Directory
{
public static DirectoryInfo GetParent(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
String s = Path.GetDirectoryName(fullPath);
if (s == null)
return null;
return new DirectoryInfo(s);
}
[System.Security.SecuritySafeCritical]
public static DirectoryInfo CreateDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("path");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.CreateDirectory(fullPath);
return new DirectoryInfo(fullPath, null);
}
// Input to this method should already be fullpath. This method will ensure that we append
// the trailing slash only when appropriate.
internal static String EnsureTrailingDirectorySeparator(string fullPath)
{
String fullPathWithTrailingDirectorySeparator;
if (!PathHelpers.EndsInDirectorySeparator(fullPath))
fullPathWithTrailingDirectorySeparator = fullPath + PathHelpers.DirectorySeparatorCharAsString;
else
fullPathWithTrailingDirectorySeparator = fullPath;
return fullPathWithTrailingDirectorySeparator;
}
// Tests if the given path refers to an existing DirectoryInfo on disk.
//
// Your application must have Read permission to the directory's
// contents.
//
[System.Security.SecuritySafeCritical] // auto-generated
public static bool Exists(String path)
{
try
{
if (path == null)
return false;
if (path.Length == 0)
return false;
String fullPath = PathHelpers.GetFullPathInternal(path);
return FileSystem.Current.DirectoryExists(fullPath);
}
catch (ArgumentException) { }
catch (NotSupportedException) { } // Security can throw this on ":"
catch (SecurityException) { }
catch (IOException) { }
catch (UnauthorizedAccessException) { }
return false;
}
public static void SetCreationTime(String path, DateTime creationTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCreationTime(fullPath, creationTime, asDirectory: true);
}
public static void SetCreationTimeUtc(String path, DateTime creationTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCreationTime(fullPath, File.GetUtcDateTimeOffset(creationTimeUtc), asDirectory: true);
}
public static DateTime GetCreationTime(String path)
{
return File.GetCreationTime(path);
}
public static DateTime GetCreationTimeUtc(String path)
{
return File.GetCreationTimeUtc(path);
}
public static void SetLastWriteTime(String path, DateTime lastWriteTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastWriteTime(fullPath, lastWriteTime, asDirectory: true);
}
public static void SetLastWriteTimeUtc(String path, DateTime lastWriteTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastWriteTime(fullPath, File.GetUtcDateTimeOffset(lastWriteTimeUtc), asDirectory: true);
}
public static DateTime GetLastWriteTime(String path)
{
return File.GetLastWriteTime(path);
}
public static DateTime GetLastWriteTimeUtc(String path)
{
return File.GetLastWriteTimeUtc(path);
}
public static void SetLastAccessTime(String path, DateTime lastAccessTime)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastAccessTime(fullPath, lastAccessTime, asDirectory: true);
}
public static void SetLastAccessTimeUtc(String path, DateTime lastAccessTimeUtc)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetLastAccessTime(fullPath, File.GetUtcDateTimeOffset(lastAccessTimeUtc), asDirectory: true);
}
public static DateTime GetLastAccessTime(String path)
{
return File.GetLastAccessTime(path);
}
public static DateTime GetLastAccessTimeUtc(String path)
{
return File.GetLastAccessTimeUtc(path);
}
// Returns an array of filenames in the DirectoryInfo specified by path
public static String[] GetFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt").
public static String[] GetFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
public static String[] GetFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFiles(path, searchPattern, searchOption);
}
// Returns an array of Files in the current DirectoryInfo matching the
// given search pattern (ie, "*.txt") and search option
private static String[] InternalGetFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, false, searchOption);
}
// Returns an array of Directories in the current directory.
public static String[] GetDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
public static String[] GetDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetDirectories(path, searchPattern, searchOption);
}
// Returns an array of Directories in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
private static String[] InternalGetDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<String[]>() != null);
return InternalGetFileDirectoryNames(path, path, searchPattern, false, true, searchOption);
}
// Returns an array of strongly typed FileSystemInfo entries in the path
public static String[] GetFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
// Returns an array of strongly typed FileSystemInfo entries in the path with the
// given search criteria (ie, "*.txt"). We disallow .. as a part of the search criteria
public static String[] GetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<String[]>() != null);
Contract.EndContractBlock();
return InternalGetFileSystemEntries(path, searchPattern, searchOption);
}
private static String[] InternalGetFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return InternalGetFileDirectoryNames(path, path, searchPattern, true, true, searchOption);
}
// Returns fully qualified user path of dirs/files that matches the search parameters.
// For recursive search this method will search through all the sub dirs and execute
// the given search criteria against every dir.
// For all the dirs/files returned, it will then demand path discovery permission for
// their parent folders (it will avoid duplicate permission checks)
internal static String[] InternalGetFileDirectoryNames(String path, String userPathOriginal, String searchPattern, bool includeFiles, bool includeDirs, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(userPathOriginal != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<String> enumerable = FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
return EnumerableHelpers.ToArray(enumerable);
}
public static IEnumerable<String> EnumerateDirectories(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.EndContractBlock();
return InternalEnumerateDirectories(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateDirectories(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
return EnumerateFileSystemNames(path, searchPattern, searchOption, false, true);
}
public static IEnumerable<String> EnumerateFiles(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFiles(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFiles(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, false);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, "*", SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, SearchOption.TopDirectoryOnly);
}
public static IEnumerable<String> EnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
if (path == null)
throw new ArgumentNullException("path");
if (searchPattern == null)
throw new ArgumentNullException("searchPattern");
if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories))
throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
Contract.EndContractBlock();
return InternalEnumerateFileSystemEntries(path, searchPattern, searchOption);
}
private static IEnumerable<String> InternalEnumerateFileSystemEntries(String path, String searchPattern, SearchOption searchOption)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return EnumerateFileSystemNames(path, searchPattern, searchOption, true, true);
}
private static IEnumerable<String> EnumerateFileSystemNames(String path, String searchPattern, SearchOption searchOption,
bool includeFiles, bool includeDirs)
{
Contract.Requires(path != null);
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
Contract.Ensures(Contract.Result<IEnumerable<String>>() != null);
return FileSystem.Current.EnumeratePaths(path, searchPattern, searchOption,
(includeFiles ? SearchTarget.Files : 0) | (includeDirs ? SearchTarget.Directories : 0));
}
[System.Security.SecuritySafeCritical]
public static String GetDirectoryRoot(String path)
{
if (path == null)
throw new ArgumentNullException("path");
Contract.EndContractBlock();
String fullPath = PathHelpers.GetFullPathInternal(path);
String root = fullPath.Substring(0, PathHelpers.GetRootLength(fullPath));
return root;
}
internal static String InternalGetDirectoryRoot(String path)
{
if (path == null) return null;
return path.Substring(0, PathHelpers.GetRootLength(path));
}
/*===============================CurrentDirectory===============================
**Action: Provides a getter and setter for the current directory. The original
** current DirectoryInfo is the one from which the process was started.
**Returns: The current DirectoryInfo (from the getter). Void from the setter.
**Arguments: The current DirectoryInfo to which to switch to the setter.
**Exceptions:
==============================================================================*/
[System.Security.SecuritySafeCritical]
public static String GetCurrentDirectory()
{
return FileSystem.Current.GetCurrentDirectory();
}
[System.Security.SecurityCritical] // auto-generated
public static void SetCurrentDirectory(String path)
{
if (path == null)
throw new ArgumentNullException("value");
if (path.Length == 0)
throw new ArgumentException(SR.Argument_PathEmpty, "path");
Contract.EndContractBlock();
if (path.Length >= FileSystem.Current.MaxPath)
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.SetCurrentDirectory(fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Move(String sourceDirName, String destDirName)
{
if (sourceDirName == null)
throw new ArgumentNullException("sourceDirName");
if (sourceDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "sourceDirName");
if (destDirName == null)
throw new ArgumentNullException("destDirName");
if (destDirName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName");
Contract.EndContractBlock();
String fullsourceDirName = PathHelpers.GetFullPathInternal(sourceDirName);
String sourcePath = EnsureTrailingDirectorySeparator(fullsourceDirName);
int maxDirectoryPath = FileSystem.Current.MaxDirectoryPath;
if (sourcePath.Length >= maxDirectoryPath)
throw new PathTooLongException(SR.IO_PathTooLong);
String fulldestDirName = PathHelpers.GetFullPathInternal(destDirName);
String destPath = EnsureTrailingDirectorySeparator(fulldestDirName);
if (destPath.Length >= maxDirectoryPath)
throw new PathTooLongException(SR.IO_PathTooLong);
StringComparison pathComparison = PathInternal.GetComparison();
if (String.Equals(sourcePath, destPath, pathComparison))
throw new IOException(SR.IO_SourceDestMustBeDifferent);
String sourceRoot = Path.GetPathRoot(sourcePath);
String destinationRoot = Path.GetPathRoot(destPath);
if (!String.Equals(sourceRoot, destinationRoot, pathComparison))
throw new IOException(SR.IO_SourceDestMustHaveSameRoot);
FileSystem.Current.MoveDirectory(fullsourceDirName, fulldestDirName);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.RemoveDirectory(fullPath, false);
}
[System.Security.SecuritySafeCritical]
public static void Delete(String path, bool recursive)
{
String fullPath = PathHelpers.GetFullPathInternal(path);
FileSystem.Current.RemoveDirectory(fullPath, recursive);
}
}
}
| |
#pragma warning disable 1591 // Ignore "Missing XML Comment" warning
namespace Data.Entities
{
using System.Linq;
// ************************************************************************
// Fake DbSet
// Implementing Find:
// The Find method is difficult to implement in a generic fashion. If
// you need to test code that makes use of the Find method it is
// easiest to create a test DbSet for each of the entity types that
// need to support find. You can then write logic to find that
// particular type of entity, as shown below:
// public class FakeBlogDbSet : FakeDbSet<Blog>
// {
// public override Blog Find(params object[] keyValues)
// {
// var id = (int) keyValues.Single();
// return this.SingleOrDefault(b => b.BlogId == id);
// }
// }
// Read more about it here: https://msdn.microsoft.com/en-us/data/dn314431.aspx
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.28.0.0")]
public partial class FakeDbSet<TEntity> : System.Data.Entity.DbSet<TEntity>, IQueryable, System.Collections.Generic.IEnumerable<TEntity>, System.Data.Entity.Infrastructure.IDbAsyncEnumerable<TEntity> where TEntity : class
{
private readonly System.Reflection.PropertyInfo[] _primaryKeys;
private readonly System.Collections.ObjectModel.ObservableCollection<TEntity> _data;
private readonly IQueryable _query;
public FakeDbSet()
{
_data = new System.Collections.ObjectModel.ObservableCollection<TEntity>();
_query = _data.AsQueryable();
InitializePartial();
}
public FakeDbSet(params string[] primaryKeys)
{
_primaryKeys = typeof(TEntity).GetProperties().Where(x => primaryKeys.Contains(x.Name)).ToArray();
_data = new System.Collections.ObjectModel.ObservableCollection<TEntity>();
_query = _data.AsQueryable();
InitializePartial();
}
public override TEntity Find(params object[] keyValues)
{
if (_primaryKeys == null)
throw new System.ArgumentException("No primary keys defined");
if (keyValues.Length != _primaryKeys.Length)
throw new System.ArgumentException("Incorrect number of keys passed to Find method");
var keyQuery = this.AsQueryable();
keyQuery = keyValues
.Select((t, i) => i)
.Aggregate(keyQuery,
(current, x) =>
current.Where(entity => _primaryKeys[x].GetValue(entity, null).Equals(keyValues[x])));
return keyQuery.SingleOrDefault();
}
public override System.Threading.Tasks.Task<TEntity> FindAsync(System.Threading.CancellationToken cancellationToken, params object[] keyValues)
{
return System.Threading.Tasks.Task<TEntity>.Factory.StartNew(() => Find(keyValues), cancellationToken);
}
public override System.Threading.Tasks.Task<TEntity> FindAsync(params object[] keyValues)
{
return System.Threading.Tasks.Task<TEntity>.Factory.StartNew(() => Find(keyValues));
}
public override System.Collections.Generic.IEnumerable<TEntity> AddRange(System.Collections.Generic.IEnumerable<TEntity> entities)
{
if (entities == null) throw new System.ArgumentNullException("entities");
var items = entities.ToList();
foreach (var entity in items)
{
_data.Add(entity);
}
return items;
}
public override TEntity Add(TEntity item)
{
if (item == null) throw new System.ArgumentNullException("item");
_data.Add(item);
return item;
}
public override System.Collections.Generic.IEnumerable<TEntity> RemoveRange(System.Collections.Generic.IEnumerable<TEntity> entities)
{
if (entities == null) throw new System.ArgumentNullException("entities");
var items = entities.ToList();
foreach (var entity in items)
{
_data.Remove(entity);
}
return items;
}
public override TEntity Remove(TEntity item)
{
if (item == null) throw new System.ArgumentNullException("item");
_data.Remove(item);
return item;
}
public override TEntity Attach(TEntity item)
{
if (item == null) throw new System.ArgumentNullException("item");
_data.Add(item);
return item;
}
public override TEntity Create()
{
return System.Activator.CreateInstance<TEntity>();
}
public override TDerivedEntity Create<TDerivedEntity>()
{
return System.Activator.CreateInstance<TDerivedEntity>();
}
public override System.Collections.ObjectModel.ObservableCollection<TEntity> Local
{
get { return _data; }
}
System.Type IQueryable.ElementType
{
get { return _query.ElementType; }
}
System.Linq.Expressions.Expression IQueryable.Expression
{
get { return _query.Expression; }
}
IQueryProvider IQueryable.Provider
{
get { return new FakeDbAsyncQueryProvider<TEntity>(_query.Provider); }
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return _data.GetEnumerator();
}
System.Collections.Generic.IEnumerator<TEntity> System.Collections.Generic.IEnumerable<TEntity>.GetEnumerator()
{
return _data.GetEnumerator();
}
System.Data.Entity.Infrastructure.IDbAsyncEnumerator<TEntity> System.Data.Entity.Infrastructure.IDbAsyncEnumerable<TEntity>.GetAsyncEnumerator()
{
return new FakeDbAsyncEnumerator<TEntity>(_data.GetEnumerator());
}
partial void InitializePartial();
}
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.28.0.0")]
public class FakeDbAsyncQueryProvider<TEntity> : System.Data.Entity.Infrastructure.IDbAsyncQueryProvider
{
private readonly IQueryProvider _inner;
public FakeDbAsyncQueryProvider(IQueryProvider inner)
{
_inner = inner;
}
public IQueryable CreateQuery(System.Linq.Expressions.Expression expression)
{
return new FakeDbAsyncEnumerable<TEntity>(expression);
}
public IQueryable<TElement> CreateQuery<TElement>(System.Linq.Expressions.Expression expression)
{
return new FakeDbAsyncEnumerable<TElement>(expression);
}
public object Execute(System.Linq.Expressions.Expression expression)
{
return _inner.Execute(expression);
}
public TResult Execute<TResult>(System.Linq.Expressions.Expression expression)
{
return _inner.Execute<TResult>(expression);
}
public System.Threading.Tasks.Task<object> ExecuteAsync(System.Linq.Expressions.Expression expression, System.Threading.CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.FromResult(Execute(expression));
}
public System.Threading.Tasks.Task<TResult> ExecuteAsync<TResult>(System.Linq.Expressions.Expression expression, System.Threading.CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.FromResult(Execute<TResult>(expression));
}
}
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.28.0.0")]
public class FakeDbAsyncEnumerable<T> : EnumerableQuery<T>, System.Data.Entity.Infrastructure.IDbAsyncEnumerable<T>, IQueryable<T>
{
public FakeDbAsyncEnumerable(System.Collections.Generic.IEnumerable<T> enumerable)
: base(enumerable)
{ }
public FakeDbAsyncEnumerable(System.Linq.Expressions.Expression expression)
: base(expression)
{ }
public System.Data.Entity.Infrastructure.IDbAsyncEnumerator<T> GetAsyncEnumerator()
{
return new FakeDbAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
}
System.Data.Entity.Infrastructure.IDbAsyncEnumerator System.Data.Entity.Infrastructure.IDbAsyncEnumerable.GetAsyncEnumerator()
{
return GetAsyncEnumerator();
}
IQueryProvider IQueryable.Provider
{
get { return new FakeDbAsyncQueryProvider<T>(this); }
}
}
[System.CodeDom.Compiler.GeneratedCode("EF.Reverse.POCO.Generator", "2.28.0.0")]
public class FakeDbAsyncEnumerator<T> : System.Data.Entity.Infrastructure.IDbAsyncEnumerator<T>
{
private readonly System.Collections.Generic.IEnumerator<T> _inner;
public FakeDbAsyncEnumerator(System.Collections.Generic.IEnumerator<T> inner)
{
_inner = inner;
}
public void Dispose()
{
_inner.Dispose();
}
public System.Threading.Tasks.Task<bool> MoveNextAsync(System.Threading.CancellationToken cancellationToken)
{
return System.Threading.Tasks.Task.FromResult(_inner.MoveNext());
}
public T Current
{
get { return _inner.Current; }
}
object System.Data.Entity.Infrastructure.IDbAsyncEnumerator.Current
{
get { return Current; }
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="DefaultValueConverter.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Provide default conversion between source values and
// target values, for data binding. The default ValueConverter
// typically wraps a type converter.
//
//---------------------------------------------------------------------------
using System;
using System.Globalization;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Navigation; // BaseUriHelper
using System.Windows.Baml2006; // WpfKnownType
using System.Windows.Markup; // IUriContext
using MS.Internal; // Invariant.Assert
using System.Diagnostics;
namespace MS.Internal.Data
{
#region DefaultValueConverter
internal class DefaultValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
protected DefaultValueConverter(TypeConverter typeConverter, Type sourceType, Type targetType,
bool shouldConvertFrom, bool shouldConvertTo, DataBindEngine engine)
{
_typeConverter = typeConverter;
_sourceType = sourceType;
_targetType = targetType;
_shouldConvertFrom = shouldConvertFrom;
_shouldConvertTo = shouldConvertTo;
_engine = engine;
}
//------------------------------------------------------
//
// Internal static API
//
//------------------------------------------------------
// static constructor - returns a ValueConverter suitable for converting between
// the source and target. The flag indicates whether targetToSource
// conversions are actually needed.
// if no Converter is needed, return DefaultValueConverter.ValueConverterNotNeeded marker.
// if unable to create a DefaultValueConverter, return null to indicate error.
internal static IValueConverter Create(Type sourceType,
Type targetType,
bool targetToSource,
DataBindEngine engine)
{
TypeConverter typeConverter;
Type innerType;
bool canConvertTo, canConvertFrom;
bool sourceIsNullable = false;
bool targetIsNullable = false;
// sometimes, no conversion is necessary
if (sourceType == targetType ||
(!targetToSource && targetType.IsAssignableFrom(sourceType)))
{
return ValueConverterNotNeeded;
}
// the type convert for System.Object is useless. It claims it can
// convert from string, but then throws an exception when asked to do
// so. So we work around it.
if (targetType == typeof(object))
{
// The sourceType here might be a Nullable type: consider using
// NullableConverter when appropriate. (uncomment following lines)
//Type innerType = Nullable.GetUnderlyingType(sourceType);
//if (innerType != null)
//{
// return new NullableConverter(new ObjectTargetConverter(innerType),
// innerType, targetType, true, false);
//}
//
return new ObjectTargetConverter(sourceType, engine);
}
else if (sourceType == typeof(object))
{
// The targetType here might be a Nullable type: consider using
// NullableConverter when appropriate. (uncomment following lines)
//Type innerType = Nullable.GetUnderlyingType(targetType);
// if (innerType != null)
// {
// return new NullableConverter(new ObjectSourceConverter(innerType),
// sourceType, innerType, false, true);
// }
//
return new ObjectSourceConverter(targetType, engine);
}
// use System.Convert for well-known base types
if (SystemConvertConverter.CanConvert(sourceType, targetType))
{
return new SystemConvertConverter(sourceType, targetType);
}
// Need to check for nullable types first, since NullableConverter is a bit over-eager;
// TypeConverter for Nullable can convert e.g. Nullable<DateTime> to string
// but it ends up doing a different conversion than the TypeConverter for the
// generic's inner type, e.g. bug 1361977
innerType = Nullable.GetUnderlyingType(sourceType);
if (innerType != null)
{
sourceType = innerType;
sourceIsNullable = true;
}
innerType = Nullable.GetUnderlyingType(targetType);
if (innerType != null)
{
targetType = innerType;
targetIsNullable = true;
}
if (sourceIsNullable || targetIsNullable)
{
// single-level recursive call to try to find a converter for basic value types
return Create(sourceType, targetType, targetToSource, engine);
}
// special case for converting IListSource to IList
if (typeof(IListSource).IsAssignableFrom(sourceType) &&
targetType.IsAssignableFrom(typeof(IList)))
{
return new ListSourceConverter();
}
// Interfaces are best handled on a per-instance basis. The type may
// not implement the interface, but an instance of a derived type may.
if (sourceType.IsInterface || targetType.IsInterface)
{
return new InterfaceConverter(sourceType, targetType);
}
// try using the source's type converter
typeConverter = GetConverter(sourceType);
canConvertTo = (typeConverter != null) ? typeConverter.CanConvertTo(targetType) : false;
canConvertFrom = (typeConverter != null) ? typeConverter.CanConvertFrom(targetType) : false;
if ((canConvertTo || targetType.IsAssignableFrom(sourceType)) &&
(!targetToSource || canConvertFrom || sourceType.IsAssignableFrom(targetType)))
{
return new SourceDefaultValueConverter(typeConverter, sourceType, targetType,
targetToSource && canConvertFrom, canConvertTo, engine);
}
// if that doesn't work, try using the target's type converter
typeConverter = GetConverter(targetType);
canConvertTo = (typeConverter != null) ? typeConverter.CanConvertTo(sourceType) : false;
canConvertFrom = (typeConverter != null) ? typeConverter.CanConvertFrom(sourceType) : false;
if ((canConvertFrom || targetType.IsAssignableFrom(sourceType)) &&
(!targetToSource || canConvertTo || sourceType.IsAssignableFrom(targetType)))
{
return new TargetDefaultValueConverter(typeConverter, sourceType, targetType,
canConvertFrom, targetToSource && canConvertTo, engine);
}
// nothing worked, give up
return null;
}
internal static TypeConverter GetConverter(Type type)
{
TypeConverter typeConverter = null;
WpfKnownType knownType = XamlReader.BamlSharedSchemaContext.GetKnownXamlType(type) as WpfKnownType;
if (knownType != null && knownType.TypeConverter != null)
{
typeConverter = knownType.TypeConverter.ConverterInstance;
}
if (typeConverter == null)
{
typeConverter = TypeDescriptor.GetConverter(type);
}
return typeConverter;
}
// some types have Parse methods that are more successful than their
// type converters at converting strings.
// [This code is lifted from [....] - formatter.cs]
internal static object TryParse(object o, Type targetType, CultureInfo culture)
{
object result = DependencyProperty.UnsetValue;
string stringValue = o as String;
if (stringValue != null)
{
try
{
MethodInfo mi;
if (culture != null && (mi = targetType.GetMethod("Parse",
BindingFlags.Public | BindingFlags.Static,
null,
new Type[] {StringType, typeof(System.Globalization.NumberStyles), typeof(System.IFormatProvider)},
null))
!= null)
{
result = mi.Invoke(null, new object [] {stringValue, NumberStyles.Any, culture});
}
else if (culture != null && (mi = targetType.GetMethod("Parse",
BindingFlags.Public | BindingFlags.Static,
null,
new Type[] {StringType, typeof(System.IFormatProvider)},
null))
!= null)
{
result = mi.Invoke(null, new object [] {stringValue, culture});
}
else if ((mi = targetType.GetMethod("Parse",
BindingFlags.Public | BindingFlags.Static,
null,
new Type[] {StringType},
null))
!= null)
{
result = mi.Invoke(null, new object [] {stringValue});
}
}
catch (TargetInvocationException)
{
}
}
return result;
}
internal static readonly IValueConverter ValueConverterNotNeeded = new ObjectTargetConverter(typeof(object), null);
//------------------------------------------------------
//
// Protected API
//
//------------------------------------------------------
protected object ConvertFrom(object o, Type destinationType, DependencyObject targetElement, CultureInfo culture)
{
return ConvertHelper(o, destinationType, targetElement, culture, false);
}
protected object ConvertTo(object o, Type destinationType, DependencyObject targetElement, CultureInfo culture)
{
return ConvertHelper(o, destinationType, targetElement, culture, true);
}
// for lazy creation of the type converter, since GetConverter is expensive
protected void EnsureConverter(Type type)
{
if (_typeConverter == null)
{
_typeConverter = GetConverter(type);
}
}
//------------------------------------------------------
//
// Private API
//
//------------------------------------------------------
private object ConvertHelper(object o, Type destinationType, DependencyObject targetElement, CultureInfo culture, bool isForward)
{
object value = DependencyProperty.UnsetValue;
bool needAssignment = (isForward ? !_shouldConvertTo : !_shouldConvertFrom);
NotSupportedException savedEx = null;
if (!needAssignment)
{
value = TryParse(o, destinationType, culture);
if (value == DependencyProperty.UnsetValue)
{
ValueConverterContext ctx = Engine.ValueConverterContext;
// The fixed VCContext object is usually available for re-use.
// In the rare cases when a second conversion is requested while
// a previous conversion is still in progress, we allocate a temporary
// context object to handle the re-entrant request. (See Dev10 bugs
// 809846 and 817353 for situations where this can happen.)
if (ctx.IsInUse)
{
ctx = new ValueConverterContext();
}
try
{
ctx.SetTargetElement(targetElement);
if (isForward)
{
value = _typeConverter.ConvertTo(ctx, culture, o, destinationType);
}
else
{
value = _typeConverter.ConvertFrom(ctx, culture, o);
}
}
catch (NotSupportedException ex)
{
needAssignment = true;
savedEx = ex;
}
finally
{
ctx.SetTargetElement(null);
}
}
}
if (needAssignment &&
( (o != null && destinationType.IsAssignableFrom(o.GetType())) ||
(o == null && !destinationType.IsValueType) ))
{
value = o;
needAssignment = false;
}
if (TraceData.IsEnabled)
{
if ((culture != null) && (savedEx != null))
{
TraceData.Trace(TraceEventType.Error,
TraceData.DefaultValueConverterFailedForCulture(
AvTrace.ToStringHelper(o),
AvTrace.TypeName(o),
destinationType.ToString(),
culture),
savedEx);
}
else if (needAssignment)
{
TraceData.Trace(TraceEventType.Error,
TraceData.DefaultValueConverterFailed(
AvTrace.ToStringHelper(o),
AvTrace.TypeName(o),
destinationType.ToString()),
savedEx);
}
}
if (needAssignment && savedEx != null)
throw savedEx;
return value;
}
protected DataBindEngine Engine { get { return _engine; } }
protected Type _sourceType;
protected Type _targetType;
private TypeConverter _typeConverter;
private bool _shouldConvertFrom;
private bool _shouldConvertTo;
private DataBindEngine _engine;
static Type StringType = typeof(String);
}
#endregion DefaultValueConverter
#region SourceDefaultValueConverter
internal class SourceDefaultValueConverter : DefaultValueConverter, IValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
public SourceDefaultValueConverter(TypeConverter typeConverter, Type sourceType, Type targetType,
bool shouldConvertFrom, bool shouldConvertTo, DataBindEngine engine)
: base(typeConverter, sourceType, targetType, shouldConvertFrom, shouldConvertTo, engine)
{
}
//------------------------------------------------------
//
// Interfaces (IValueConverter)
//
//------------------------------------------------------
public object Convert(object o, Type type, object parameter, CultureInfo culture)
{
return ConvertTo(o, _targetType, parameter as DependencyObject, culture);
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
{
return ConvertFrom(o, _sourceType, parameter as DependencyObject, culture);
}
}
#endregion SourceDefaultValueConverter
#region TargetDefaultValueConverter
internal class TargetDefaultValueConverter : DefaultValueConverter, IValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
public TargetDefaultValueConverter(TypeConverter typeConverter, Type sourceType, Type targetType,
bool shouldConvertFrom, bool shouldConvertTo, DataBindEngine engine)
: base(typeConverter, sourceType, targetType, shouldConvertFrom, shouldConvertTo, engine)
{
}
//------------------------------------------------------
//
// Interfaces (IValueConverter)
//
//------------------------------------------------------
public object Convert(object o, Type type, object parameter, CultureInfo culture)
{
return ConvertFrom(o, _targetType, parameter as DependencyObject, culture);
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
{
return ConvertTo(o, _sourceType, parameter as DependencyObject, culture);
}
}
#endregion TargetDefaultValueConverter
#region SystemConvertConverter
internal class SystemConvertConverter : IValueConverter
{
public SystemConvertConverter(Type sourceType, Type targetType)
{
_sourceType = sourceType;
_targetType = targetType;
}
public object Convert(object o, Type type, object parameter, CultureInfo culture)
{
return System.Convert.ChangeType(o, _targetType, culture);
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
{
object parsedValue = DefaultValueConverter.TryParse(o, _sourceType, culture);
return (parsedValue != DependencyProperty.UnsetValue)
? parsedValue
: System.Convert.ChangeType(o, _sourceType, culture);
}
// ASSUMPTION: sourceType != targetType
public static bool CanConvert(Type sourceType, Type targetType)
{
// This assert is not Invariant.Assert because this will not cause
// harm; It would just be odd.
Debug.Assert(sourceType != targetType);
// DateTime can only be converted to and from String type
if (sourceType == typeof(DateTime))
return (targetType == typeof(String));
if (targetType == typeof(DateTime))
return (sourceType == typeof(String));
// Char can only be converted to a subset of supported types
if (sourceType == typeof(Char))
return CanConvertChar(targetType);
if (targetType == typeof(Char))
return CanConvertChar(sourceType);
// Using nested loops is up to 40% more efficient than using one loop
for (int i = 0; i < SupportedTypes.Length; ++i)
{
if (sourceType == SupportedTypes[i])
{
++i; // assuming (sourceType != targetType), start at next type
for (; i < SupportedTypes.Length; ++i)
{
if (targetType == SupportedTypes[i])
return true;
}
}
else if (targetType == SupportedTypes[i])
{
++i; // assuming (sourceType != targetType), start at next type
for (; i < SupportedTypes.Length; ++i)
{
if (sourceType == SupportedTypes[i])
return true;
}
}
}
return false;
}
private static bool CanConvertChar(Type type)
{
for (int i = 0; i < CharSupportedTypes.Length; ++i)
{
if (type == CharSupportedTypes[i])
return true;
}
return false;
}
Type _sourceType, _targetType;
// list of types supported by System.Convert (from the SDK)
static readonly Type[] SupportedTypes = {
typeof(String), // put common types up front
typeof(Int32), typeof(Int64), typeof(Single), typeof(Double),
typeof(Decimal),typeof(Boolean),
typeof(Byte), typeof(Int16),
typeof(UInt32), typeof(UInt64), typeof(UInt16), typeof(SByte), // non-CLS compliant types
};
// list of types supported by System.Convert for Char Type(from the SDK)
static readonly Type[] CharSupportedTypes = {
typeof(String), // put common types up front
typeof(Int32), typeof(Int64), typeof(Byte), typeof(Int16),
typeof(UInt32), typeof(UInt64), typeof(UInt16), typeof(SByte), // non-CLS compliant types
};
}
#endregion SystemConvertConverter
#region ObjectConverter
//
internal class ObjectTargetConverter : DefaultValueConverter, IValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
public ObjectTargetConverter(Type sourceType, DataBindEngine engine) :
base(null, sourceType, typeof(object),
true /* shouldConvertFrom */, false /* shouldConvertTo */, engine)
{
}
//------------------------------------------------------
//
// Interfaces (IValueConverter)
//
//------------------------------------------------------
public object Convert(object o, Type type, object parameter, CultureInfo culture)
{
// conversion from any type to object is easy
return o;
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
{
// if types are compatible, just pass the value through
if (o == null && !_sourceType.IsValueType)
return o;
if (o != null && _sourceType.IsAssignableFrom(o.GetType()))
return o;
// if source type is string, use String.Format (string's type converter doesn't
// do it for us - boo!)
if (_sourceType == typeof(String))
return String.Format(culture, "{0}", o);
// otherwise, use system converter
EnsureConverter(_sourceType);
return ConvertFrom(o, _sourceType, parameter as DependencyObject, culture);
}
}
//
internal class ObjectSourceConverter : DefaultValueConverter, IValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
public ObjectSourceConverter(Type targetType, DataBindEngine engine) :
base(null, typeof(object), targetType,
true /* shouldConvertFrom */, false /* shouldConvertTo */, engine)
{
}
//------------------------------------------------------
//
// Interfaces (IValueConverter)
//
//------------------------------------------------------
public object Convert(object o, Type type, object parameter, CultureInfo culture)
{
// if types are compatible, just pass the value through
if ((o != null && _targetType.IsAssignableFrom(o.GetType())) ||
(o == null && !_targetType.IsValueType))
return o;
// if target type is string, use String.Format (string's type converter doesn't
// do it for us - boo!)
if (_targetType == typeof(String))
return String.Format(culture, "{0}", o);
// otherwise, use system converter
EnsureConverter(_targetType);
return ConvertFrom(o, _targetType, parameter as DependencyObject, culture);
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
{
// conversion from any type to object is easy
return o;
}
}
#endregion ObjectConverter
#region ListSourceConverter
internal class ListSourceConverter : IValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
//------------------------------------------------------
//
// Interfaces (IValueConverter)
//
//------------------------------------------------------
public object Convert(object o, Type type, object parameter, CultureInfo culture)
{
IList il = null;
IListSource ils = o as IListSource;
if (ils != null)
{
il = ils.GetList();
}
return il;
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
{
return null;
}
}
#endregion ListSourceConverter
#region InterfaceConverter
internal class InterfaceConverter : IValueConverter
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
internal InterfaceConverter(Type sourceType, Type targetType)
{
_sourceType = sourceType;
_targetType = targetType;
}
//------------------------------------------------------
//
// Interfaces (IValueConverter)
//
//------------------------------------------------------
public object Convert(object o, Type type, object parameter, CultureInfo culture)
{
return ConvertTo(o, _targetType);
}
public object ConvertBack(object o, Type type, object parameter, CultureInfo culture)
{
return ConvertTo(o, _sourceType);
}
private object ConvertTo(object o, Type type)
{
return type.IsInstanceOfType(o) ? o : null;
}
Type _sourceType;
Type _targetType;
}
#endregion InterfaceConverter
// TypeDescriptor context to provide TypeConverters with the app's BaseUri
internal class ValueConverterContext : ITypeDescriptorContext, IUriContext
{
// redirect to IUriContext service
virtual public object GetService(Type serviceType)
{
if (serviceType == typeof(IUriContext))
{
return this as IUriContext;
}
return null;
}
// call BaseUriHelper.GetBaseUri() if the target element is known.
// It does a tree walk trying to find a IUriContext implementer or a root element which has BaseUri explicitly set
// This get_BaseUri is only called from a TypeConverter which in turn
// is called from one of our DefaultConverters in this source file.
public Uri BaseUri
{
get
{
if (_cachedBaseUri == null)
{
if (_targetElement != null)
{
// GetBaseUri looks for a optional BaseUriProperty attached DP.
// This can cause a re-entrancy if that BaseUri is also data bound.
// Ideally the BaseUri DP should be flagged as NotDataBindable but
// unfortunately that DP is a core DP and not aware of the framework metadata
//
// GetBaseUri can raise SecurityExceptions if e.g. the app doesn't have
// the correct FileIO permission.
// Any security exception is initially caught in BindingExpression.ConvertHelper/.ConvertBackHelper
// but then rethrown since it is a critical exception.
_cachedBaseUri = BaseUriHelper.GetBaseUri(_targetElement);
}
else
{
_cachedBaseUri = BaseUriHelper.BaseUri;
}
}
return _cachedBaseUri;
}
set { throw new NotSupportedException(); }
}
internal void SetTargetElement(DependencyObject target)
{
if (target != null)
_nestingLevel++;
else
{
if (_nestingLevel > 0)
_nestingLevel--;
}
Invariant.Assert((_nestingLevel <= 1), "illegal to recurse/reenter ValueConverterContext.SetTargetElement()");
_targetElement = target;
_cachedBaseUri = null;
}
internal bool IsInUse
{
get { return (_nestingLevel > 0); }
}
// empty default implementation of interface ITypeDescriptorContext
public IContainer Container { get { return null; } }
public object Instance { get { return null; } }
public PropertyDescriptor PropertyDescriptor { get { return null;} }
public void OnComponentChanged() { }
public bool OnComponentChanging() { return false; }
// fields
private DependencyObject _targetElement;
private int _nestingLevel;
private Uri _cachedBaseUri;
}
}
| |
namespace Boxed.AspNetCore
{
using System;
using Boxed.AspNetCore.Filters;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.Rewrite;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
/// <summary>
/// To improve Search Engine Optimization SEO, there should only be a single URL for each resource. Case
/// differences and/or URL's with/without trailing slashes are treated as different URL's by search engines. This
/// rewrite rule redirects all non-canonical URL's based on the settings specified to their canonical equivalent.
/// Note: Non-canonical URL's are not generated by this site template, it is usually external sites which are
/// linking to your site but have changed the URL case or added/removed trailing slashes.
/// (See Google's comments at http://googlewebmastercentral.blogspot.co.uk/2010/04/to-slash-or-not-to-slash.html
/// and Bing's at http://blogs.bing.com/webmaster/2012/01/26/moving-content-think-301-not-relcanonical).
/// </summary>
public class RedirectToCanonicalUrlRule : IRule
{
private const char SlashCharacter = '/';
/// <summary>
/// Initializes a new instance of the <see cref="RedirectToCanonicalUrlRule"/> class.
/// </summary>
/// <param name="options">The route options.</param>
public RedirectToCanonicalUrlRule(IOptions<RouteOptions> options)
{
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
this.AppendTrailingSlash = options.Value.AppendTrailingSlash;
this.LowercaseUrls = options.Value.LowercaseUrls;
}
/// <summary>
/// Initializes a new instance of the <see cref="RedirectToCanonicalUrlRule" /> class.
/// </summary>
/// <param name="appendTrailingSlash">If set to <c>true</c> append trailing slashes, otherwise strip trailing
/// slashes.</param>
/// <param name="lowercaseUrls">If set to <c>true</c> lower-case all URL's.</param>
public RedirectToCanonicalUrlRule(
bool appendTrailingSlash,
bool lowercaseUrls)
{
this.AppendTrailingSlash = appendTrailingSlash;
this.LowercaseUrls = lowercaseUrls;
}
/// <summary>
/// Gets a value indicating whether to append trailing slashes.
/// </summary>
/// <value>
/// <c>true</c> if appending trailing slashes; otherwise, strip trailing slashes.
/// </value>
public bool AppendTrailingSlash { get; }
/// <summary>
/// Gets a value indicating whether to lower-case all URL's.
/// </summary>
/// <value>
/// <c>true</c> if lower-casing URL's; otherwise, <c>false</c>.
/// </value>
public bool LowercaseUrls { get; }
/// <inheritdoc/>
public void ApplyRule(RewriteContext context)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (HttpMethods.IsGet(context.HttpContext.Request.Method))
{
if (!this.TryGetCanonicalUrl(context, out var canonicalUrl))
{
this.HandleNonCanonicalRequest(context, canonicalUrl);
}
}
}
/// <summary>
/// Determines whether the specified URl is canonical and if it is not, outputs the canonical URL.
/// </summary>
/// <param name="context">The <see cref="RewriteContext" />.</param>
/// <param name="canonicalUrl">The canonical URL.</param>
/// <returns><c>true</c> if the URL is canonical, otherwise <c>false</c>.</returns>
protected virtual bool TryGetCanonicalUrl(RewriteContext context, out Uri canonicalUrl)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var isCanonical = true;
var request = context.HttpContext.Request;
var hasPath = request.Path.HasValue && (request.Path.Value.Length > 1);
// If we are not dealing with the home page. Note, the home page is a special case and it doesn't matter
// if there is a trailing slash or not. Both will be treated as the same by search engines.
if (hasPath)
{
var hasTrailingSlash = request.Path.Value[^1] == SlashCharacter;
if (this.AppendTrailingSlash)
{
// Append a trailing slash to the end of the URL.
if (!hasTrailingSlash && !this.HasAttribute<NoTrailingSlashAttribute>(context))
{
request.Path = new PathString(request.Path.Value + SlashCharacter);
isCanonical = false;
}
}
else
{
// Trim a trailing slash from the end of the URL.
if (hasTrailingSlash)
{
request.Path = new PathString(request.Path.Value.TrimEnd(SlashCharacter));
isCanonical = false;
}
}
}
if (hasPath || request.QueryString.HasValue)
{
if (this.LowercaseUrls && !this.HasAttribute<NoTrailingSlashAttribute>(context))
{
foreach (var character in request.Path.Value)
{
if (char.IsUpper(character))
{
#pragma warning disable CA1308 // Normalize strings to uppercase
request.Path = new PathString(request.Path.Value.ToLowerInvariant());
#pragma warning restore CA1308 // Normalize strings to uppercase
isCanonical = false;
break;
}
}
if (request.QueryString.HasValue && !this.HasAttribute<NoLowercaseQueryStringAttribute>(context))
{
foreach (var character in request.QueryString.Value)
{
if (char.IsUpper(character))
{
#pragma warning disable CA1308 // Normalize strings to uppercase
request.QueryString = new QueryString(request.QueryString.Value.ToLowerInvariant());
#pragma warning restore CA1308 // Normalize strings to uppercase
isCanonical = false;
break;
}
}
}
}
}
if (isCanonical)
{
canonicalUrl = null;
}
else
{
canonicalUrl = new Uri(UriHelper.GetEncodedUrl(request), UriKind.Absolute);
}
return isCanonical;
}
/// <summary>
/// Handles HTTP requests for URL's that are not canonical. Performs a 301 Permanent Redirect to the canonical URL.
/// </summary>
/// <param name="context">The <see cref="RewriteContext" />.</param>
/// <param name="canonicalUrl">The canonical URL.</param>
protected virtual void HandleNonCanonicalRequest(RewriteContext context, Uri canonicalUrl)
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
if (canonicalUrl is null)
{
throw new ArgumentNullException(nameof(canonicalUrl));
}
var response = context.HttpContext.Response;
response.StatusCode = StatusCodes.Status301MovedPermanently;
context.Result = RuleResult.EndResponse;
response.Headers[HeaderNames.Location] = canonicalUrl.ToString();
}
/// <summary>
/// Determines whether the specified action or its controller has the attribute with the specified type
/// <typeparamref name="T"/>.
/// </summary>
/// <typeparam name="T">The type of the attribute.</typeparam>
/// <param name="context">The <see cref="RewriteContext" />.</param>
/// <returns><c>true</c> if a <typeparamref name="T"/> attribute is specified, otherwise <c>false</c>.</returns>
protected virtual bool HasAttribute<T>(RewriteContext context)
where T : class
{
if (context is null)
{
throw new ArgumentNullException(nameof(context));
}
var endpoint = context.HttpContext.GetEndpoint();
return endpoint.Metadata.GetMetadata<T>() is object;
}
}
}
| |
//
// Copyright 2012 Hakan Kjellerstrand
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Linq;
using Google.OrTools.ConstraintSolver;
public class APuzzle
{
/**
*
* From "God plays dice"
* "A puzzle"
* http://gottwurfelt.wordpress.com/2012/02/22/a-puzzle/
* And the sequel "Answer to a puzzle"
* http://gottwurfelt.wordpress.com/2012/02/24/an-answer-to-a-puzzle/
*
* This problem instance was taken from the latter blog post.
* (Problem 1)
*
* """
* 8809 = 6
* 7111 = 0
* 2172 = 0
* 6666 = 4
* 1111 = 0
* 3213 = 0
* 7662 = 2
* 9312 = 1
* 0000 = 4
* 2222 = 0
* 3333 = 0
* 5555 = 0
* 8193 = 3
* 8096 = 5
* 7777 = 0
* 9999 = 4
* 7756 = 1
* 6855 = 3
* 9881 = 5
* 5531 = 0
*
* 2581 = ?
* """
*
* Note:
* This model yields 10 solutions, since x4 is not
* restricted in the constraints.
* All solutions has x assigned to the correct result.
*
*
* (Problem 2)
* The problem stated in "A puzzle"
* http://gottwurfelt.wordpress.com/2012/02/22/a-puzzle/
* is
* """
* 8809 = 6
* 7662 = 2
* 9312 = 1
* 8193 = 3
* 8096 = 5
* 7756 = 1
* 6855 = 3
* 9881 = 5
*
* 2581 = ?
* """
* This problem instance yields two different solutions of x,
* one is the same (correct) as for the above problem instance,
* and one is not.
* This is because here x0,x1,x4 and x9 are underdefined.
*
*
*/
private static void Solve(int p = 1)
{
Solver solver = new Solver("APuzzle");
Console.WriteLine("\nSolving p{0}", p);
//
// Data
//
int n = 10;
//
// Decision variables
//
IntVar x0 = solver.MakeIntVar(0, n - 1, "x0");
IntVar x1 = solver.MakeIntVar(0, n - 1, "x1");
IntVar x2 = solver.MakeIntVar(0, n - 1, "x2");
IntVar x3 = solver.MakeIntVar(0, n - 1, "x3");
IntVar x4 = solver.MakeIntVar(0, n - 1, "x4");
IntVar x5 = solver.MakeIntVar(0, n - 1, "x5");
IntVar x6 = solver.MakeIntVar(0, n - 1, "x6");
IntVar x7 = solver.MakeIntVar(0, n - 1, "x7");
IntVar x8 = solver.MakeIntVar(0, n - 1, "x8");
IntVar x9 = solver.MakeIntVar(0, n - 1, "x9");
IntVar[] all = { x0, x1, x2, x3, x4, x5, x6, x7, x8, x9 };
// The unknown, i.e. 2581 = x
IntVar x = solver.MakeIntVar(0, n - 1, "x");
//
// Constraints
//
// Both problem are here shown in two
// approaches:
// - using equations
// - using a a matrix and Sum of each row
if (p == 1)
{
// Problem 1
solver.Add(x8 + x8 + x0 + x9 == 6);
solver.Add(x7 + x1 + x1 + x1 == 0);
solver.Add(x2 + x1 + x7 + x2 == 0);
solver.Add(x6 + x6 + x6 + x6 == 4);
solver.Add(x1 + x1 + x1 + x1 == 0);
solver.Add(x3 + x2 + x1 + x3 == 0);
solver.Add(x7 + x6 + x6 + x2 == 2);
solver.Add(x9 + x3 + x1 + x2 == 1);
solver.Add(x0 + x0 + x0 + x0 == 4);
solver.Add(x2 + x2 + x2 + x2 == 0);
solver.Add(x3 + x3 + x3 + x3 == 0);
solver.Add(x5 + x5 + x5 + x5 == 0);
solver.Add(x8 + x1 + x9 + x3 == 3);
solver.Add(x8 + x0 + x9 + x6 == 5);
solver.Add(x7 + x7 + x7 + x7 == 0);
solver.Add(x9 + x9 + x9 + x9 == 4);
solver.Add(x7 + x7 + x5 + x6 == 1);
solver.Add(x6 + x8 + x5 + x5 == 3);
solver.Add(x9 + x8 + x8 + x1 == 5);
solver.Add(x5 + x5 + x3 + x1 == 0);
// The unknown
solver.Add(x2 + x5 + x8 + x1 == x);
}
else if (p == 2)
{
// Another representation of Problem 1
int[,] problem1 = { { 8, 8, 0, 9, 6 }, { 7, 1, 1, 1, 0 }, { 2, 1, 7, 2, 0 }, { 6, 6, 6, 6, 4 },
{ 1, 1, 1, 1, 0 }, { 3, 2, 1, 3, 0 }, { 7, 6, 6, 2, 2 }, { 9, 3, 1, 2, 1 },
{ 0, 0, 0, 0, 4 }, { 2, 2, 2, 2, 0 }, { 3, 3, 3, 3, 0 }, { 5, 5, 5, 5, 0 },
{ 8, 1, 9, 3, 3 }, { 8, 0, 9, 6, 5 }, { 7, 7, 7, 7, 0 }, { 9, 9, 9, 9, 4 },
{ 7, 7, 5, 6, 1 }, { 6, 8, 5, 5, 3 }, { 9, 8, 8, 1, 5 }, { 5, 5, 3, 1, 0 } };
for (int i = 0; i < problem1.GetLength(0); i++)
{
solver.Add((from j in Enumerable.Range(0, 4) select all[problem1[i, j]]).ToArray().Sum() ==
problem1[i, 4]);
}
solver.Add(all[2] + all[5] + all[8] + all[1] == x);
}
else if (p == 3)
{
// Problem 2
solver.Add(x8 + x8 + x0 + x9 == 6);
solver.Add(x7 + x6 + x6 + x2 == 2);
solver.Add(x9 + x3 + x1 + x2 == 1);
solver.Add(x8 + x1 + x9 + x3 == 3);
solver.Add(x8 + x0 + x9 + x6 == 5);
solver.Add(x7 + x7 + x5 + x6 == 1);
solver.Add(x6 + x8 + x5 + x5 == 3);
solver.Add(x9 + x8 + x8 + x1 == 5);
// The unknown
solver.Add(x2 + x5 + x8 + x1 == x);
}
else
{
// Another representation of Problem 2
int[,] problem2 = { { 8, 8, 0, 9, 6 }, { 7, 6, 6, 2, 2 }, { 9, 3, 1, 2, 1 }, { 8, 1, 9, 3, 3 },
{ 8, 0, 9, 6, 5 }, { 7, 7, 5, 6, 1 }, { 6, 8, 5, 5, 3 }, { 9, 8, 8, 1, 5 } };
for (int i = 0; i < problem2.GetLength(0); i++)
{
solver.Add((from j in Enumerable.Range(0, 4) select all[problem2[i, j]]).ToArray().Sum() ==
problem2[i, 4]);
}
solver.Add(all[2] + all[5] + all[8] + all[1] == x);
}
//
// Search
//
DecisionBuilder db = solver.MakePhase(all, Solver.INT_VAR_DEFAULT, Solver.INT_VALUE_DEFAULT);
solver.NewSearch(db);
while (solver.NextSolution())
{
Console.Write("x: {0} x0..x9: ", x.Value());
for (int i = 0; i < n; i++)
{
Console.Write(all[i].Value() + " ");
}
Console.WriteLine();
}
Console.WriteLine("\nSolutions: {0}", solver.Solutions());
Console.WriteLine("WallTime: {0}ms", solver.WallTime());
Console.WriteLine("Failures: {0}", solver.Failures());
Console.WriteLine("Branches: {0} ", solver.Branches());
solver.EndSearch();
}
public static void Main(String[] args)
{
for (int p = 1; p <= 4; p++)
{
Solve(p);
}
}
}
| |
#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;
#if !(NET20 || NET35 || PORTABLE)
using System.Numerics;
#endif
using System.Text;
using Newtonsoft.Json.Converters;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;
#endif
using Newtonsoft.Json.Linq;
using System.IO;
#if NET20
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
using Newtonsoft.Json.Utilities;
#endif
namespace Newtonsoft.Json.Tests.Linq
{
[TestFixture]
public class JTokenTests : TestFixtureBase
{
[Test]
public void DeepEqualsObjectOrder()
{
string ob1 = @"{""key1"":""1"",""key2"":""2""}";
string ob2 = @"{""key2"":""2"",""key1"":""1""}";
JObject j1 = JObject.Parse(ob1);
JObject j2 = JObject.Parse(ob2);
Assert.IsTrue(j1.DeepEquals(j2));
}
[Test]
public void ReadFrom()
{
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
JArray a = (JArray)JToken.ReadFrom(new JsonTextReader(new StringReader("[1,2,3]")));
Assert.AreEqual(1, (int)a[0]);
Assert.AreEqual(2, (int)a[1]);
Assert.AreEqual(3, (int)a[2]);
JsonReader reader = new JsonTextReader(new StringReader("{'pie':true}"));
reader.Read();
reader.Read();
JProperty p = (JProperty)JToken.ReadFrom(reader);
Assert.AreEqual("pie", p.Name);
Assert.AreEqual(true, (bool)p.Value);
JConstructor c = (JConstructor)JToken.ReadFrom(new JsonTextReader(new StringReader("new Date(1)")));
Assert.AreEqual("Date", c.Name);
Assert.IsTrue(JToken.DeepEquals(new JValue(1), c.Values().ElementAt(0)));
JValue v;
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""stringvalue""")));
Assert.AreEqual("stringvalue", (string)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1")));
Assert.AreEqual(1, (int)v);
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"1.1")));
Assert.AreEqual(1.1, (double)v);
#if !NET20
v = (JValue)JToken.ReadFrom(new JsonTextReader(new StringReader(@"""1970-01-01T00:00:00+12:31"""))
{
DateParseHandling = DateParseHandling.DateTimeOffset
});
Assert.AreEqual(typeof(DateTimeOffset), v.Value.GetType());
Assert.AreEqual(new DateTimeOffset(DateTimeUtils.InitialJavaScriptDateTicks, new TimeSpan(12, 31, 0)), v.Value);
#endif
}
[Test]
public void Load()
{
JObject o = (JObject)JToken.Load(new JsonTextReader(new StringReader("{'pie':true}")));
Assert.AreEqual(true, (bool)o["pie"]);
}
[Test]
public void Parse()
{
JObject o = (JObject)JToken.Parse("{'pie':true}");
Assert.AreEqual(true, (bool)o["pie"]);
}
[Test]
public void Parent()
{
JArray v = new JArray(new JConstructor("TestConstructor"), new JValue(new DateTime(2000, 12, 20)));
Assert.AreEqual(null, v.Parent);
JObject o =
new JObject(
new JProperty("Test1", v),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", "Test3Value"),
new JProperty("Test4", null)
);
Assert.AreEqual(o.Property("Test1"), v.Parent);
JProperty p = new JProperty("NewProperty", v);
// existing value should still have same parent
Assert.AreEqual(o.Property("Test1"), v.Parent);
// new value should be cloned
Assert.AreNotSame(p.Value, v);
Assert.AreEqual((DateTime)((JValue)p.Value[1]).Value, (DateTime)((JValue)v[1]).Value);
Assert.AreEqual(v, o["Test1"]);
Assert.AreEqual(null, o.Parent);
JProperty o1 = new JProperty("O1", o);
Assert.AreEqual(o, o1.Value);
Assert.AreNotEqual(null, o.Parent);
JProperty o2 = new JProperty("O2", o);
Assert.AreNotSame(o1.Value, o2.Value);
Assert.AreEqual(o1.Value.Children().Count(), o2.Value.Children().Count());
Assert.AreEqual(false, JToken.DeepEquals(o1, o2));
Assert.AreEqual(true, JToken.DeepEquals(o1.Value, o2.Value));
}
[Test]
public void Next()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken next = a[0].Next;
Assert.AreEqual(6, (int)next);
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), next));
next = next.Next;
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), next));
next = next.Next;
Assert.IsNull(next);
}
[Test]
public void Previous()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
JToken previous = a[3].Previous;
Assert.IsTrue(JToken.DeepEquals(new JArray(7, 8), previous));
previous = previous.Previous;
Assert.AreEqual(6, (int)previous);
previous = previous.Previous;
Assert.AreEqual(5, (int)previous);
previous = previous.Previous;
Assert.IsNull(previous);
}
[Test]
public void Children()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.AreEqual(4, a.Count());
Assert.AreEqual(3, a.Children<JArray>().Count());
}
[Test]
public void BeforeAfter()
{
JArray a =
new JArray(
5,
new JArray(1, 2, 3),
new JArray(1, 2, 3),
new JArray(1, 2, 3)
);
Assert.AreEqual(5, (int)a[1].Previous);
Assert.AreEqual(2, a[2].BeforeSelf().Count());
//Assert.AreEqual(2, a[2].AfterSelf().Count());
}
[Test]
public void Casting()
{
Assert.AreEqual(1L, (long)(new JValue(1)));
Assert.AreEqual(2L, (long)new JArray(1, 2, 3)[1]);
Assert.AreEqual(new DateTime(2000, 12, 20), (DateTime)new JValue(new DateTime(2000, 12, 20)));
#if !NET20
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 0, 0, 0, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTime(2000, 12, 20, 0, 0, 0, DateTimeKind.Utc)));
Assert.AreEqual(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero), (DateTimeOffset)new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.AreEqual(null, (DateTimeOffset?)new JValue((DateTimeOffset?)null));
Assert.AreEqual(null, (DateTimeOffset?)(JValue)null);
#endif
Assert.AreEqual(true, (bool)new JValue(true));
Assert.AreEqual(true, (bool?)new JValue(true));
Assert.AreEqual(null, (bool?)((JValue)null));
Assert.AreEqual(null, (bool?)JValue.CreateNull());
Assert.AreEqual(10, (long)new JValue(10));
Assert.AreEqual(null, (long?)new JValue((long?)null));
Assert.AreEqual(null, (long?)(JValue)null);
Assert.AreEqual(null, (int?)new JValue((int?)null));
Assert.AreEqual(null, (int?)(JValue)null);
Assert.AreEqual(null, (DateTime?)new JValue((DateTime?)null));
Assert.AreEqual(null, (DateTime?)(JValue)null);
Assert.AreEqual(null, (short?)new JValue((short?)null));
Assert.AreEqual(null, (short?)(JValue)null);
Assert.AreEqual(null, (float?)new JValue((float?)null));
Assert.AreEqual(null, (float?)(JValue)null);
Assert.AreEqual(null, (double?)new JValue((double?)null));
Assert.AreEqual(null, (double?)(JValue)null);
Assert.AreEqual(null, (decimal?)new JValue((decimal?)null));
Assert.AreEqual(null, (decimal?)(JValue)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(null, (sbyte?)new JValue((sbyte?)null));
Assert.AreEqual(null, (sbyte?)(JValue)null);
Assert.AreEqual(null, (byte?)new JValue((byte?)null));
Assert.AreEqual(null, (byte?)(JValue)null);
Assert.AreEqual(null, (ulong?)new JValue((ulong?)null));
Assert.AreEqual(null, (ulong?)(JValue)null);
Assert.AreEqual(null, (uint?)new JValue((uint?)null));
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(11.1f, (float)new JValue(11.1));
Assert.AreEqual(float.MinValue, (float)new JValue(float.MinValue));
Assert.AreEqual(1.1, (double)new JValue(1.1));
Assert.AreEqual(uint.MaxValue, (uint)new JValue(uint.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JValue(ulong.MaxValue));
Assert.AreEqual(ulong.MaxValue, (ulong)new JProperty("Test", new JValue(ulong.MaxValue)));
Assert.AreEqual(null, (string)new JValue((string)null));
Assert.AreEqual(5m, (decimal)(new JValue(5L)));
Assert.AreEqual(5m, (decimal?)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5L)));
Assert.AreEqual(5f, (float)(new JValue(5m)));
Assert.AreEqual(5f, (float?)(new JValue(5m)));
Assert.AreEqual(5, (byte)(new JValue(5)));
Assert.AreEqual(SByte.MinValue, (sbyte?)(new JValue(SByte.MinValue)));
Assert.AreEqual(SByte.MinValue, (sbyte)(new JValue(SByte.MinValue)));
Assert.AreEqual(null, (sbyte?)JValue.CreateNull());
Assert.AreEqual("1", (string)(new JValue(1)));
Assert.AreEqual("1", (string)(new JValue(1.0)));
Assert.AreEqual("1.0", (string)(new JValue(1.0m)));
Assert.AreEqual("True", (string)(new JValue(true)));
Assert.AreEqual(null, (string)(JValue.CreateNull()));
Assert.AreEqual(null, (string)(JValue)null);
Assert.AreEqual("12/12/2000 12:12:12", (string)(new JValue(new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc))));
#if !NET20
Assert.AreEqual("12/12/2000 12:12:12 +00:00", (string)(new JValue(new DateTimeOffset(2000, 12, 12, 12, 12, 12, TimeSpan.Zero))));
#endif
Assert.AreEqual(true, (bool)(new JValue(1)));
Assert.AreEqual(true, (bool)(new JValue(1.0)));
Assert.AreEqual(true, (bool)(new JValue("true")));
Assert.AreEqual(true, (bool)(new JValue(true)));
Assert.AreEqual(1, (int)(new JValue(1)));
Assert.AreEqual(1, (int)(new JValue(1.0)));
Assert.AreEqual(1, (int)(new JValue("1")));
Assert.AreEqual(1, (int)(new JValue(true)));
Assert.AreEqual(1m, (decimal)(new JValue(1)));
Assert.AreEqual(1m, (decimal)(new JValue(1.0)));
Assert.AreEqual(1m, (decimal)(new JValue("1")));
Assert.AreEqual(1m, (decimal)(new JValue(true)));
Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue(TimeSpan.FromMinutes(1))));
Assert.AreEqual("00:01:00", (string)(new JValue(TimeSpan.FromMinutes(1))));
Assert.AreEqual(TimeSpan.FromMinutes(1), (TimeSpan)(new JValue("00:01:00")));
Assert.AreEqual("46efe013-b56a-4e83-99e4-4dce7678a5bc", (string)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))));
Assert.AreEqual("http://www.google.com/", (string)(new JValue(new Uri("http://www.google.com"))));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"))));
Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue("http://www.google.com")));
Assert.AreEqual(new Uri("http://www.google.com"), (Uri)(new JValue(new Uri("http://www.google.com"))));
Assert.AreEqual(null, (Uri)(JValue.CreateNull()));
Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")), (string)(new JValue(Encoding.UTF8.GetBytes("hi"))));
CollectionAssert.AreEquivalent((byte[])Encoding.UTF8.GetBytes("hi"), (byte[])(new JValue(Convert.ToBase64String(Encoding.UTF8.GetBytes("hi")))));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray())));
Assert.AreEqual(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC"), (Guid?)(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC").ToByteArray())));
Assert.AreEqual((sbyte?)1, (sbyte?)(new JValue((short?)1)));
Assert.AreEqual(null, (Uri)(JValue)null);
Assert.AreEqual(null, (int?)(JValue)null);
Assert.AreEqual(null, (uint?)(JValue)null);
Assert.AreEqual(null, (Guid?)(JValue)null);
Assert.AreEqual(null, (TimeSpan?)(JValue)null);
Assert.AreEqual(null, (byte[])(JValue)null);
Assert.AreEqual(null, (bool?)(JValue)null);
Assert.AreEqual(null, (char?)(JValue)null);
Assert.AreEqual(null, (DateTime?)(JValue)null);
#if !NET20
Assert.AreEqual(null, (DateTimeOffset?)(JValue)null);
#endif
Assert.AreEqual(null, (short?)(JValue)null);
Assert.AreEqual(null, (ushort?)(JValue)null);
Assert.AreEqual(null, (byte?)(JValue)null);
Assert.AreEqual(null, (byte?)(JValue)null);
Assert.AreEqual(null, (sbyte?)(JValue)null);
Assert.AreEqual(null, (sbyte?)(JValue)null);
Assert.AreEqual(null, (long?)(JValue)null);
Assert.AreEqual(null, (ulong?)(JValue)null);
Assert.AreEqual(null, (double?)(JValue)null);
Assert.AreEqual(null, (float?)(JValue)null);
byte[] data = new byte[0];
Assert.AreEqual(data, (byte[])(new JValue(data)));
Assert.AreEqual(5, (int)(new JValue(StringComparison.OrdinalIgnoreCase)));
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
string bigIntegerText = "1234567899999999999999999999999999999999999999999999999999999999999990";
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(BigInteger.Parse(bigIntegerText))).Value);
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(bigIntegerText)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(long.MaxValue), (new JValue(long.MaxValue)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(4.5d), (new JValue((4.5d))).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(4.5f), (new JValue((4.5f))).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(byte.MaxValue), (new JValue(byte.MaxValue)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger>());
Assert.AreEqual(new BigInteger(123), (new JValue(123)).ToObject<BigInteger?>());
Assert.AreEqual(null, (JValue.CreateNull()).ToObject<BigInteger?>());
byte[] intData = BigInteger.Parse(bigIntegerText).ToByteArray();
Assert.AreEqual(BigInteger.Parse(bigIntegerText), (new JValue(intData)).ToObject<BigInteger>());
Assert.AreEqual(4.0d, (double)(new JValue(new BigInteger(4.5d))));
Assert.AreEqual(true, (bool)(new JValue(new BigInteger(1))));
Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(long.MaxValue))));
Assert.AreEqual(long.MaxValue, (long)(new JValue(new BigInteger(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }))));
Assert.AreEqual("9223372036854775807", (string)(new JValue(new BigInteger(long.MaxValue))));
intData = (byte[])(new JValue(new BigInteger(long.MaxValue)));
CollectionAssert.AreEqual(new byte[] { 255, 255, 255, 255, 255, 255, 255, 127 }, intData);
#endif
}
[Test]
public void FailedCasting()
{
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(true); }, "Can not convert Boolean to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1); }, "Can not convert Integer to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(1.1m); }, "Can not convert Float to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)JValue.CreateNull(); }, "Can not convert Null to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTime)new JValue(Guid.NewGuid()); }, "Can not convert Guid to DateTime.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1); }, "Can not convert Integer to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(1.1m); }, "Can not convert Float to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(TimeSpan.Zero); }, "Can not convert TimeSpan to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(Guid.NewGuid()); }, "Can not convert Guid to Uri.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTime.Now); }, "Can not convert Date to Uri.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Uri.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(true); }, "Can not convert Boolean to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1); }, "Can not convert Integer to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(1.1m); }, "Can not convert Float to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)JValue.CreateNull(); }, "Can not convert Null to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(Guid.NewGuid()); }, "Can not convert Guid to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTime.Now); }, "Can not convert Date to TimeSpan.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(DateTimeOffset.Now); }, "Can not convert Date to TimeSpan.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (TimeSpan)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to TimeSpan.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(true); }, "Can not convert Boolean to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1); }, "Can not convert Integer to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(1.1m); }, "Can not convert Float to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)JValue.CreateNull(); }, "Can not convert Null to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTime.Now); }, "Can not convert Date to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(DateTimeOffset.Now); }, "Can not convert Date to Guid.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(TimeSpan.FromMinutes(1)); }, "Can not convert TimeSpan to Guid.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Guid)new JValue(new Uri("http://www.google.com")); }, "Can not convert Uri to Guid.");
#if !NET20
ExceptionAssert.Throws<ArgumentException>(() => { var i = (DateTimeOffset)new JValue(true); }, "Can not convert Boolean to DateTimeOffset.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (Uri)new JValue(true); }, "Can not convert Boolean to Uri.");
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(new Uri("http://www.google.com"))).ToObject<BigInteger>(); }, "Can not convert Uri to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (JValue.CreateNull()).ToObject<BigInteger>(); }, "Can not convert Null to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger>(); }, "Can not convert Guid to BigInteger.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue(Guid.NewGuid())).ToObject<BigInteger?>(); }, "Can not convert Guid to BigInteger.");
#endif
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte?)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (sbyte)new JValue(DateTime.Now); }, "Can not convert Date to SByte.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison>(); }, "Could not convert 'Ordinal1' to StringComparison.");
ExceptionAssert.Throws<ArgumentException>(() => { var i = (new JValue("Ordinal1")).ToObject<StringComparison?>(); }, "Could not convert 'Ordinal1' to StringComparison.");
}
[Test]
public void ToObject()
{
#if !(NET20 || NET35 || PORTABLE)
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger))));
Assert.AreEqual((BigInteger)1, (new JValue(1).ToObject(typeof(BigInteger?))));
Assert.AreEqual((BigInteger?)null, (JValue.CreateNull().ToObject(typeof(BigInteger?))));
#endif
Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort))));
Assert.AreEqual((ushort)1, (new JValue(1).ToObject(typeof(ushort?))));
Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint))));
Assert.AreEqual((uint)1L, (new JValue(1).ToObject(typeof(uint?))));
Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong))));
Assert.AreEqual((ulong)1L, (new JValue(1).ToObject(typeof(ulong?))));
Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte))));
Assert.AreEqual((sbyte)1L, (new JValue(1).ToObject(typeof(sbyte?))));
Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte))));
Assert.AreEqual((byte)1L, (new JValue(1).ToObject(typeof(byte?))));
Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short))));
Assert.AreEqual((short)1L, (new JValue(1).ToObject(typeof(short?))));
Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int))));
Assert.AreEqual(1, (new JValue(1).ToObject(typeof(int?))));
Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long))));
Assert.AreEqual(1L, (new JValue(1).ToObject(typeof(long?))));
Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float))));
Assert.AreEqual((float)1, (new JValue(1.0).ToObject(typeof(float?))));
Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double))));
Assert.AreEqual((double)1, (new JValue(1.0).ToObject(typeof(double?))));
Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal))));
Assert.AreEqual(1m, (new JValue(1).ToObject(typeof(decimal?))));
Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool))));
Assert.AreEqual(true, (new JValue(true).ToObject(typeof(bool?))));
Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char))));
Assert.AreEqual('b', (new JValue('b').ToObject(typeof(char?))));
Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan))));
Assert.AreEqual(TimeSpan.MaxValue, (new JValue(TimeSpan.MaxValue).ToObject(typeof(TimeSpan?))));
Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime))));
Assert.AreEqual(DateTime.MaxValue, (new JValue(DateTime.MaxValue).ToObject(typeof(DateTime?))));
#if !NET20
Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset))));
Assert.AreEqual(DateTimeOffset.MaxValue, (new JValue(DateTimeOffset.MaxValue).ToObject(typeof(DateTimeOffset?))));
#endif
Assert.AreEqual("b", (new JValue("b").ToObject(typeof(string))));
Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid))));
Assert.AreEqual(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C"), (new JValue(new Guid("A34B2080-B5F0-488E-834D-45D44ECB9E5C")).ToObject(typeof(Guid?))));
Assert.AreEqual(new Uri("http://www.google.com/"), (new JValue(new Uri("http://www.google.com/")).ToObject(typeof(Uri))));
Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison))));
Assert.AreEqual(StringComparison.Ordinal, (new JValue("Ordinal").ToObject(typeof(StringComparison?))));
Assert.AreEqual(null, (JValue.CreateNull().ToObject(typeof(StringComparison?))));
}
[Test]
public void ImplicitCastingTo()
{
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTime(2000, 12, 20)), (JValue)new DateTime(2000, 12, 20)));
#if !NET20
Assert.IsTrue(JToken.DeepEquals(new JValue(new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)), (JValue)new DateTimeOffset(2000, 12, 20, 23, 50, 10, TimeSpan.Zero)));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTimeOffset?)null), (JValue)(DateTimeOffset?)null));
#endif
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
// had to remove implicit casting to avoid user reference to System.Numerics.dll
Assert.IsTrue(JToken.DeepEquals(new JValue(new BigInteger(1)), new JValue(new BigInteger(1))));
Assert.IsTrue(JToken.DeepEquals(new JValue((BigInteger?)null), new JValue((BigInteger?)null)));
#endif
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)true));
Assert.IsTrue(JToken.DeepEquals(new JValue(true), (JValue)(bool?)true));
Assert.IsTrue(JToken.DeepEquals(new JValue((bool?)null), (JValue)(bool?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(10), (JValue)10));
Assert.IsTrue(JToken.DeepEquals(new JValue((long?)null), (JValue)(long?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(long.MaxValue), (JValue)long.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((int?)null), (JValue)(int?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((short?)null), (JValue)(short?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((double?)null), (JValue)(double?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((uint?)null), (JValue)(uint?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((decimal?)null), (JValue)(decimal?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((ulong?)null), (JValue)(ulong?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte?)null), (JValue)(sbyte?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((sbyte)1), (JValue)(sbyte)1));
Assert.IsTrue(JToken.DeepEquals(new JValue((byte?)null), (JValue)(byte?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((byte)1), (JValue)(byte)1));
Assert.IsTrue(JToken.DeepEquals(new JValue((ushort?)null), (JValue)(ushort?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(short.MaxValue), (JValue)short.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ushort.MaxValue), (JValue)ushort.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(11.1f), (JValue)11.1f));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MinValue), (JValue)float.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MinValue), (JValue)double.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(uint.MaxValue), (JValue)uint.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MaxValue), (JValue)ulong.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(ulong.MinValue), (JValue)ulong.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue((string)null), (JValue)(string)null));
Assert.IsTrue(JToken.DeepEquals(new JValue((DateTime?)null), (JValue)(DateTime?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MaxValue), (JValue)(decimal?)decimal.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(decimal.MinValue), (JValue)decimal.MinValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(float.MaxValue), (JValue)(float?)float.MaxValue));
Assert.IsTrue(JToken.DeepEquals(new JValue(double.MaxValue), (JValue)(double?)double.MaxValue));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(double?)null));
Assert.IsFalse(JToken.DeepEquals(new JValue(true), (JValue)(bool?)null));
Assert.IsFalse(JToken.DeepEquals(JValue.CreateNull(), (JValue)(object)null));
byte[] emptyData = new byte[0];
Assert.IsTrue(JToken.DeepEquals(new JValue(emptyData), (JValue)emptyData));
Assert.IsFalse(JToken.DeepEquals(new JValue(emptyData), (JValue)new byte[1]));
Assert.IsTrue(JToken.DeepEquals(new JValue(Encoding.UTF8.GetBytes("Hi")), (JValue)Encoding.UTF8.GetBytes("Hi")));
Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)TimeSpan.FromMinutes(1)));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(TimeSpan?)null));
Assert.IsTrue(JToken.DeepEquals(new JValue(TimeSpan.FromMinutes(1)), (JValue)(TimeSpan?)TimeSpan.FromMinutes(1)));
Assert.IsTrue(JToken.DeepEquals(new JValue(new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")), (JValue)new Guid("46EFE013-B56A-4E83-99E4-4DCE7678A5BC")));
Assert.IsTrue(JToken.DeepEquals(new JValue(new Uri("http://www.google.com")), (JValue)new Uri("http://www.google.com")));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Uri)null));
Assert.IsTrue(JToken.DeepEquals(JValue.CreateNull(), (JValue)(Guid?)null));
}
[Test]
public void Root()
{
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
Assert.AreEqual(a, a.Root);
Assert.AreEqual(a, a[0].Root);
Assert.AreEqual(a, ((JArray)a[2])[0].Root);
}
[Test]
public void Remove()
{
JToken t;
JArray a =
new JArray(
5,
6,
new JArray(7, 8),
new JArray(9, 10)
);
a[0].Remove();
Assert.AreEqual(6, (int)a[0]);
a[1].Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(9, 10), a[1]));
Assert.AreEqual(2, a.Count());
t = a[1];
t.Remove();
Assert.AreEqual(6, (int)a[0]);
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
t = a[0];
t.Remove();
Assert.AreEqual(0, a.Count());
Assert.IsNull(t.Next);
Assert.IsNull(t.Previous);
Assert.IsNull(t.Parent);
}
[Test]
public void AfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1];
List<JToken> afterTokens = t.AfterSelf().ToList();
Assert.AreEqual(2, afterTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2), afterTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), afterTokens[1]));
}
[Test]
public void BeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[2];
List<JToken> beforeTokens = t.BeforeSelf().ToList();
Assert.AreEqual(2, beforeTokens.Count);
Assert.IsTrue(JToken.DeepEquals(new JValue(5), beforeTokens[0]));
Assert.IsTrue(JToken.DeepEquals(new JArray(1), beforeTokens[1]));
}
[Test]
public void HasValues()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
Assert.IsTrue(a.HasValues);
}
[Test]
public void Ancestors()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1][0];
List<JToken> ancestors = t.Ancestors().ToList();
Assert.AreEqual(2, ancestors.Count());
Assert.AreEqual(a[1], ancestors[0]);
Assert.AreEqual(a, ancestors[1]);
}
[Test]
public void AncestorsAndSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken t = a[1][0];
List<JToken> ancestors = t.AncestorsAndSelf().ToList();
Assert.AreEqual(3, ancestors.Count());
Assert.AreEqual(t, ancestors[0]);
Assert.AreEqual(a[1], ancestors[1]);
Assert.AreEqual(a, ancestors[2]);
}
[Test]
public void AncestorsAndSelf_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
JToken t1 = a[1][0];
JToken t2 = o["prop1"];
List<JToken> source = new List<JToken> { t1, t2 };
List<JToken> ancestors = source.AncestorsAndSelf().ToList();
Assert.AreEqual(6, ancestors.Count());
Assert.AreEqual(t1, ancestors[0]);
Assert.AreEqual(a[1], ancestors[1]);
Assert.AreEqual(a, ancestors[2]);
Assert.AreEqual(t2, ancestors[3]);
Assert.AreEqual(o.Property("prop1"), ancestors[4]);
Assert.AreEqual(o, ancestors[5]);
}
[Test]
public void Ancestors_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
JToken t1 = a[1][0];
JToken t2 = o["prop1"];
List<JToken> source = new List<JToken> { t1, t2 };
List<JToken> ancestors = source.Ancestors().ToList();
Assert.AreEqual(4, ancestors.Count());
Assert.AreEqual(a[1], ancestors[0]);
Assert.AreEqual(a, ancestors[1]);
Assert.AreEqual(o.Property("prop1"), ancestors[2]);
Assert.AreEqual(o, ancestors[3]);
}
[Test]
public void Descendants()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
List<JToken> descendants = a.Descendants().ToList();
Assert.AreEqual(10, descendants.Count());
Assert.AreEqual(5, (int)descendants[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 4]));
Assert.AreEqual(1, (int)descendants[descendants.Count - 3]);
Assert.AreEqual(2, (int)descendants[descendants.Count - 2]);
Assert.AreEqual(3, (int)descendants[descendants.Count - 1]);
}
[Test]
public void Descendants_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
List<JContainer> source = new List<JContainer> { a, o };
List<JToken> descendants = source.Descendants().ToList();
Assert.AreEqual(12, descendants.Count());
Assert.AreEqual(5, (int)descendants[0]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendants[descendants.Count - 6]));
Assert.AreEqual(1, (int)descendants[descendants.Count - 5]);
Assert.AreEqual(2, (int)descendants[descendants.Count - 4]);
Assert.AreEqual(3, (int)descendants[descendants.Count - 3]);
Assert.AreEqual(o.Property("prop1"), descendants[descendants.Count - 2]);
Assert.AreEqual(o["prop1"], descendants[descendants.Count - 1]);
}
[Test]
public void DescendantsAndSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
List<JToken> descendantsAndSelf = a.DescendantsAndSelf().ToList();
Assert.AreEqual(11, descendantsAndSelf.Count());
Assert.AreEqual(a, descendantsAndSelf[0]);
Assert.AreEqual(5, (int)descendantsAndSelf[1]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendantsAndSelf[descendantsAndSelf.Count - 4]));
Assert.AreEqual(1, (int)descendantsAndSelf[descendantsAndSelf.Count - 3]);
Assert.AreEqual(2, (int)descendantsAndSelf[descendantsAndSelf.Count - 2]);
Assert.AreEqual(3, (int)descendantsAndSelf[descendantsAndSelf.Count - 1]);
}
[Test]
public void DescendantsAndSelf_Many()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JObject o = new JObject
{
{ "prop1", "value1" }
};
List<JContainer> source = new List<JContainer> { a, o };
List<JToken> descendantsAndSelf = source.DescendantsAndSelf().ToList();
Assert.AreEqual(14, descendantsAndSelf.Count());
Assert.AreEqual(a, descendantsAndSelf[0]);
Assert.AreEqual(5, (int)descendantsAndSelf[1]);
Assert.IsTrue(JToken.DeepEquals(new JArray(1, 2, 3), descendantsAndSelf[descendantsAndSelf.Count - 7]));
Assert.AreEqual(1, (int)descendantsAndSelf[descendantsAndSelf.Count - 6]);
Assert.AreEqual(2, (int)descendantsAndSelf[descendantsAndSelf.Count - 5]);
Assert.AreEqual(3, (int)descendantsAndSelf[descendantsAndSelf.Count - 4]);
Assert.AreEqual(o, descendantsAndSelf[descendantsAndSelf.Count - 3]);
Assert.AreEqual(o.Property("prop1"), descendantsAndSelf[descendantsAndSelf.Count - 2]);
Assert.AreEqual(o["prop1"], descendantsAndSelf[descendantsAndSelf.Count - 1]);
}
[Test]
public void CreateWriter()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JsonWriter writer = a.CreateWriter();
Assert.IsNotNull(writer);
Assert.AreEqual(4, a.Count());
writer.WriteValue("String");
Assert.AreEqual(5, a.Count());
Assert.AreEqual("String", (string)a[4]);
writer.WriteStartObject();
writer.WritePropertyName("Property");
writer.WriteValue("PropertyValue");
writer.WriteEnd();
Assert.AreEqual(6, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JObject(new JProperty("Property", "PropertyValue")), a[5]));
}
[Test]
public void AddFirst()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a.AddFirst("First");
Assert.AreEqual("First", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(5, a.Count());
a.AddFirst("NewFirst");
Assert.AreEqual("NewFirst", (string)a[0]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
Assert.AreEqual(a[0], a[0].Next.Previous);
}
[Test]
public void RemoveAll()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
JToken first = a.First;
Assert.AreEqual(5, (int)first);
a.RemoveAll();
Assert.AreEqual(0, a.Count());
Assert.IsNull(first.Parent);
Assert.IsNull(first.Next);
}
[Test]
public void AddPropertyToArray()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JArray a = new JArray();
a.Add(new JProperty("PropertyName"));
}, "Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray.");
}
[Test]
public void AddValueToObject()
{
ExceptionAssert.Throws<ArgumentException>(() =>
{
JObject o = new JObject();
o.Add(5);
}, "Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.");
}
[Test]
public void Replace()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[0].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[0]);
Assert.AreEqual(4, a.Count());
a[1][0].Replace(new JValue("Test"));
Assert.AreEqual("Test", (string)a[1][0]);
a[2].Replace(new JValue(int.MaxValue));
Assert.AreEqual(int.MaxValue, (int)a[2]);
Assert.AreEqual(4, a.Count());
Assert.IsTrue(JToken.DeepEquals(new JArray(int.MaxValue, new JArray("Test"), int.MaxValue, new JArray(1, 2, 3)), a));
}
[Test]
public void ToStringWithConverters()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.Indented, new IsoDateTimeConverter());
StringAssert.AreEqual(@"[
""2009-02-15T00:00:00Z""
]", json);
json = JsonConvert.SerializeObject(a, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void ToStringWithNoIndenting()
{
JArray a =
new JArray(
new JValue(new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc))
);
string json = a.ToString(Formatting.None, new IsoDateTimeConverter());
Assert.AreEqual(@"[""2009-02-15T00:00:00Z""]", json);
}
[Test]
public void AddAfterSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddAfterSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual(1, a[1].Count());
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(5, a.Count());
a[4].AddAfterSelf("lastpie");
Assert.AreEqual("lastpie", (string)a[5]);
Assert.AreEqual("lastpie", (string)a.Last);
}
[Test]
public void AddBeforeSelf()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3)
);
a[1].AddBeforeSelf("pie");
Assert.AreEqual(5, (int)a[0]);
Assert.AreEqual("pie", (string)a[1]);
Assert.AreEqual(a, a[1].Parent);
Assert.AreEqual(a[2], a[1].Next);
Assert.AreEqual(5, a.Count());
a[0].AddBeforeSelf("firstpie");
Assert.AreEqual("firstpie", (string)a[0]);
Assert.AreEqual(5, (int)a[1]);
Assert.AreEqual("pie", (string)a[2]);
Assert.AreEqual(a, a[0].Parent);
Assert.AreEqual(a[1], a[0].Next);
Assert.AreEqual(6, a.Count());
a.Last.AddBeforeSelf("secondlastpie");
Assert.AreEqual("secondlastpie", (string)a[5]);
Assert.AreEqual(7, a.Count());
}
[Test]
public void DeepClone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
JArray a2 = (JArray)a.DeepClone();
StringAssert.AreEqual(@"[
5,
[
1
],
[
1,
2
],
[
1,
2,
3
],
{
""First"": ""SGk="",
""Second"": 1,
""Third"": null,
""Fourth"": new Date(
12345
),
""Fifth"": ""Infinity"",
""Sixth"": ""NaN""
}
]", a2.ToString(Formatting.Indented));
Assert.IsTrue(a.DeepEquals(a2));
}
#if !(NETFX_CORE || PORTABLE || DNXCORE50 || PORTABLE40)
[Test]
public void Clone()
{
JArray a =
new JArray(
5,
new JArray(1),
new JArray(1, 2),
new JArray(1, 2, 3),
new JObject(
new JProperty("First", new JValue(Encoding.UTF8.GetBytes("Hi"))),
new JProperty("Second", 1),
new JProperty("Third", null),
new JProperty("Fourth", new JConstructor("Date", 12345)),
new JProperty("Fifth", double.PositiveInfinity),
new JProperty("Sixth", double.NaN)
)
);
ICloneable c = a;
JArray a2 = (JArray)c.Clone();
Assert.IsTrue(a.DeepEquals(a2));
}
#endif
[Test]
public void DoubleDeepEquals()
{
JArray a =
new JArray(
double.NaN,
double.PositiveInfinity,
double.NegativeInfinity
);
JArray a2 = (JArray)a.DeepClone();
Assert.IsTrue(a.DeepEquals(a2));
double d = 1 + 0.1 + 0.1 + 0.1;
JValue v1 = new JValue(d);
JValue v2 = new JValue(1.3);
Assert.IsTrue(v1.DeepEquals(v2));
}
[Test]
public void ParseAdditionalContent()
{
ExceptionAssert.Throws<JsonReaderException>(() =>
{
string json = @"[
""Small"",
""Medium"",
""Large""
],";
JToken.Parse(json);
}, "Additional text encountered after finished reading JSON content: ,. Path '', line 5, position 1.");
}
[Test]
public void Path()
{
JObject o =
new JObject(
new JProperty("Test1", new JArray(1, 2, 3)),
new JProperty("Test2", "Test2Value"),
new JProperty("Test3", new JObject(new JProperty("Test1", new JArray(1, new JObject(new JProperty("Test1", 1)), 3)))),
new JProperty("Test4", new JConstructor("Date", new JArray(1, 2, 3)))
);
JToken t = o.SelectToken("Test1[0]");
Assert.AreEqual("Test1[0]", t.Path);
t = o.SelectToken("Test2");
Assert.AreEqual("Test2", t.Path);
t = o.SelectToken("");
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test4[0][0]");
Assert.AreEqual("Test4[0][0]", t.Path);
t = o.SelectToken("Test4[0]");
Assert.AreEqual("Test4[0]", t.Path);
t = t.DeepClone();
Assert.AreEqual("", t.Path);
t = o.SelectToken("Test3.Test1[1].Test1");
Assert.AreEqual("Test3.Test1[1].Test1", t.Path);
JArray a = new JArray(1);
Assert.AreEqual("", a.Path);
Assert.AreEqual("[0]", a[0].Path);
}
[Test]
public void Parse_NoComments()
{
string json = "{'prop':[1,2/*comment*/,3]}";
JToken o = JToken.Parse(json, new JsonLoadSettings
{
CommentHandling = CommentHandling.Ignore
});
Assert.AreEqual(3, o["prop"].Count());
Assert.AreEqual(1, (int)o["prop"][0]);
Assert.AreEqual(2, (int)o["prop"][1]);
Assert.AreEqual(3, (int)o["prop"][2]);
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.UnitTests.Config
{
using System.IO;
using MyExtensionNamespace;
using NLog.Filters;
using NLog.Layouts;
using NLog.Targets;
using Xunit;
public class ExtensionTests : NLogTestBase
{
private string extensionAssemblyName1 = "SampleExtensions";
#if SILVERLIGHT
private string extensionAssemblyFullPath1 = "SampleExtensions.dll";
#else
private string extensionAssemblyFullPath1 = Path.GetFullPath("SampleExtensions.dll");
#endif
[Fact]
public void ExtensionTest1()
{
Assert.NotNull(typeof(FooLayout));
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<extensions>
<add assemblyFile='" + this.extensionAssemblyFullPath1 + @"' />
</extensions>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Equal(1, layout.Renderers.Count);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void ExtensionTest2()
{
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<extensions>
<add assembly='" + this.extensionAssemblyName1 + @"' />
</extensions>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
<when condition='myrandom(10)==3' action='Log' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Equal(1, layout.Renderers.Count);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(2, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
var cbf = configuration.LoggingRules[0].Filters[1] as ConditionBasedFilter;
Assert.NotNull(cbf);
Assert.Equal("(myrandom(10) == 3)", cbf.Condition.ToString());
}
[Fact]
public void ExtensionWithPrefixTest()
{
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<extensions>
<add prefix='myprefix' assemblyFile='" + this.extensionAssemblyFullPath1 + @"' />
</extensions>
<targets>
<target name='t' type='myprefix.MyTarget' />
<target name='d1' type='Debug' layout='${myprefix.foo}' />
<target name='d2' type='Debug'>
<layout type='myprefix.FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<myprefix.whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Equal(1, layout.Renderers.Count);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void ExtensionTest4()
{
Assert.NotNull(typeof(FooLayout));
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<extensions>
<add type='" + typeof(MyTarget).AssemblyQualifiedName + @"' />
<add type='" + typeof(FooLayout).AssemblyQualifiedName + @"' />
<add type='" + typeof(FooLayoutRenderer).AssemblyQualifiedName + @"' />
<add type='" + typeof(WhenFooFilter).AssemblyQualifiedName + @"' />
</extensions>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Equal(1, layout.Renderers.Count);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void ExtensionTest_extensions_not_top_and_used()
{
Assert.NotNull(typeof(FooLayout));
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets>
<target name='t' type='MyTarget' />
<target name='d1' type='Debug' layout='${foo}' />
<target name='d2' type='Debug'>
<layout type='FooLayout' x='1'>
</layout>
</target>
</targets>
<rules>
<logger name='*' writeTo='t'>
<filters>
<whenFoo x='44' action='Ignore' />
</filters>
</logger>
</rules>
<extensions>
<add assemblyFile='" + this.extensionAssemblyFullPath1 + @"' />
</extensions>
</nlog>");
Target myTarget = configuration.FindTargetByName("t");
Assert.Equal("MyExtensionNamespace.MyTarget", myTarget.GetType().FullName);
var d1Target = (DebugTarget)configuration.FindTargetByName("d1");
var layout = d1Target.Layout as SimpleLayout;
Assert.NotNull(layout);
Assert.Equal(1, layout.Renderers.Count);
Assert.Equal("MyExtensionNamespace.FooLayoutRenderer", layout.Renderers[0].GetType().FullName);
var d2Target = (DebugTarget)configuration.FindTargetByName("d2");
Assert.Equal("MyExtensionNamespace.FooLayout", d2Target.Layout.GetType().FullName);
Assert.Equal(1, configuration.LoggingRules[0].Filters.Count);
Assert.Equal("MyExtensionNamespace.WhenFooFilter", configuration.LoggingRules[0].Filters[0].GetType().FullName);
}
[Fact]
public void CustomXmlNamespaceTest()
{
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true' xmlns:foo='http://bar'>
<targets>
<target name='d' type='foo:Debug' />
</targets>
</nlog>");
var d1Target = (DebugTarget)configuration.FindTargetByName("d");
Assert.NotNull(d1Target);
}
#if !SILVERLIGHT
[Fact]
public void Extension_should_be_auto_loaded_when_following_NLog_dll_format()
{
var configuration = CreateConfigurationFromString(@"
<nlog throwExceptions='true'>
<targets>
<target name='t' type='AutoLoadTarget' />
</targets>
<rules>
<logger name='*' writeTo='t'>
</logger>
</rules>
</nlog>");
var autoLoadedTarget = configuration.FindTargetByName("t");
Assert.Equal("NLogAutloadExtension.AutoLoadTarget", autoLoadedTarget.GetType().FullName);
}
#endif
}
}
| |
//Sony Computer Entertainment Confidential
using System.Collections.Generic;
using System.Xml;
using Sce.Atf.Dom;
namespace LevelEditorCore
{
/// <summary>
/// Standard annotations</summary>
public static class Annotations
{
/// <summary>
/// Gets shape annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>shape annotation</returns>
public static string GetShape(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, ShapeAttribute);
return annotation;
}
/// <summary>
/// Gets width annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>width annotation</returns>
public static string GetWidth(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, WidthAttribute);
return annotation;
}
/// <summary>
/// Gets height annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>height annotation</returns>
public static string GetHeight(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, HeightAttribute);
return annotation;
}
/// <summary>
/// Gets radius annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>radius annotation</returns>
public static string GetRadius(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, RadiusAttribute);
return annotation;
}
/// <summary>
/// Gets translation annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>translation annotation</returns>
public static string GetTranslation(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, TranslationAttribute);
return annotation;
}
/// <summary>
/// Gets rotation annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>rotation annotation</returns>
public static string GetRotation(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, RotationAttribute);
return annotation;
}
/// <summary>
/// Gets wireframe color annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>wireframe color annotation</returns>
public static string GetWireColor(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, WireColorAttribute);
return annotation;
}
/// <summary>
/// Gets smooth-shading color annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>smooth-shading color annotation</returns>
public static string GetSmoothColor(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, SmoothColorAttribute);
return annotation;
}
/// <summary>
/// Gets render mode annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>render mode annotation</returns>
public static string GetRenderMode(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, RenderModeAttribute);
return annotation;
}
/// <summary>
/// Gets bounding box element name annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>bounding box element name annotation</returns>
public static string GetBoundingBoxElementName(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, BoundingBoxElementNameAttribute);
return annotation;
}
/// <summary>
/// Gets billboard texture name annotation</summary>
/// <param name="type">Annotated type</param>
/// <returns>billboard texture name annotation</returns>
public static string GetBillboardTextureName(DomNodeType type)
{
string annotation = FindAnnotation(type, DisplayElement, BillboardTextureNameAttribute);
return annotation;
}
public const string DisplayElement = "scea.games.editors.display";
public const string ElementElement = "scea.games.editors.element";
// General attributes
public const string NameAttribute = "name";
// Rendering attributes
public const string RenderAttribute = "render";
// Proxy object attributes
public const string BoundingBoxElementNameAttribute = "boundingBoxElementName";
public const string ShapeAttribute = "shape";
public const string WidthAttribute = "width";
public const string HeightAttribute = "height";
public const string RadiusAttribute = "radius";
public const string RotationAttribute = "rotation";
public const string TranslationAttribute = "translation";
public const string WireColorAttribute = "wireColor";
public const string SmoothColorAttribute = "solidColor";
public const string RenderModeAttribute = "renderMode";
public const string BillboardTextureNameAttribute = "billboardTexture";
/// <summary>
/// Gets the Xml node with the given local name, searching the type
/// and all of its base types</summary>
/// <param name="type">DomNodeType whose Tag contains an IEnumerable of XmlNodes</param>
/// <param name="name">Node's local name</param>
/// <returns>Xml node with the given local name, or null</returns>
public static XmlNode FindAnnotation(this DomNodeType type, string name)
{
foreach (XmlNode xmlNode in FindAnnotations(type, name))
{
return xmlNode;
}
return null;
}
/// <summary>
/// Finds annotation with the given element and attribute, searching the type
/// and all of its base types</summary>
/// <param name="type">DomNodeType whose Tag contains an IEnumerable of XmlNodes</param>
/// <param name="elementName">Annotation element local name</param>
/// <param name="attributeName">Annotation attribute local name</param>
/// <returns>Annotation with the given element and attribute, or null</returns>
public static string FindAnnotation(this DomNodeType type, string elementName, string attributeName)
{
foreach (XmlNode xmlNode in FindAnnotations(type, elementName))
{
XmlAttribute attribute = xmlNode.Attributes[attributeName];
if (attribute != null)
return attribute.Value;
}
return null;
}
/// <summary>
/// Gets the Xml nodes with the given local name, searching the type and all of its base types</summary>
/// <param name="type">DomNodeType whose Tag contains an IEnumerable of XmlNodes</param>
/// <param name="elementName">Nodes' local name</param>
/// <returns>Xml nodes with the given local name, or null</returns>
public static IEnumerable<XmlNode> FindAnnotations(this DomNodeType type, string elementName)
{
Dictionary<string, List<XmlNode>> namesToNodes;
if (!s_cachedAnnotations.TryGetValue(type, out namesToNodes))
{
namesToNodes = new Dictionary<string, List<XmlNode>>();
s_cachedAnnotations.Add(type, namesToNodes);
}
List<XmlNode> cache;
if (!namesToNodes.TryGetValue(elementName, out cache))
{
cache = CreateCachedAnnotations(type, elementName);
namesToNodes.Add(elementName, cache);
}
return cache;
}
private static List<XmlNode> CreateCachedAnnotations(DomNodeType derivedType, string elementName)
{
var cache = new List<XmlNode>();
foreach (DomNodeType type in derivedType.Lineage)
{
IEnumerable<XmlNode> xmlNodes = type.GetTag<IEnumerable<XmlNode>>();
if (xmlNodes != null)
{
foreach (XmlNode xmlNode in xmlNodes)
{
if (xmlNode.LocalName == elementName)
{
cache.Add(xmlNode);
}
}
}
}
return cache;
}
// For each DomNodeType, we need to keep a mapping of element names to the list of XmlNodes
// on that DomNodeType whose LocalName matches the element name.
private static readonly Dictionary<DomNodeType, Dictionary<string, List<XmlNode>>> s_cachedAnnotations =
new Dictionary<DomNodeType, Dictionary<string, List<XmlNode>>>();
}
}
| |
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.Core.WebApi;
using Microsoft.VisualStudio.Services.Graph.Client;
using Microsoft.VisualStudio.Services.WebApi;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Services.Notifications.WebApi.Clients;
using Microsoft.VisualStudio.Services.Notifications.WebApi;
using System;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.Identity.Client;
using Microsoft.VisualStudio.Services.Identity;
using System.Threading;
using System.Linq;
namespace NotificationConfiguration.Services
{
/// <summary>
/// Provides access to DevOps entities
/// </summary>
public class AzureDevOpsService
{
private readonly VssConnection connection;
private readonly ILogger<AzureDevOpsService> logger;
private Dictionary<Type, VssHttpClientBase> clientCache = new Dictionary<Type, VssHttpClientBase>();
private SemaphoreSlim clientCacheSemaphore = new SemaphoreSlim(1);
public static AzureDevOpsService CreateAzureDevOpsService(string token, string url, ILogger<AzureDevOpsService> logger)
{
var devOpsCreds = new VssBasicCredential("nobody", token);
var devOpsConnection = new VssConnection(new Uri(url), devOpsCreds);
var result = new AzureDevOpsService(devOpsConnection, logger);
return result;
}
/// <summary>
/// Creates a new AzureDevOpsService
/// </summary>
/// <param name="connection">VssConnection to use</param>
/// <param name="logger">Logger</param>
public AzureDevOpsService(VssConnection connection, ILogger<AzureDevOpsService> logger)
{
this.connection = connection;
this.logger = logger;
}
private async Task<T> GetClientAsync<T>()
where T : VssHttpClientBase
{
var type = typeof(T);
T result;
await clientCacheSemaphore.WaitAsync();
if (clientCache.ContainsKey(type))
{
result = (T)clientCache[type];
}
else
{
result = await connection.GetClientAsync<T>();
clientCache.Add(type, result);
}
clientCacheSemaphore.Release();
return result;
}
/// <summary>
/// Gets build definitions
/// </summary>
/// <param name="projectName">Name of the project</param>
/// <param name="pathPrefix">Prefix of the path in the build folder tree</param>
/// <returns>IEnumerable of build definitions that satisfy the given criteria</returns>
public async Task<IEnumerable<BuildDefinition>> GetPipelinesAsync(string projectName, string pathPrefix = null)
{
var client = await GetClientAsync<BuildHttpClient>();
logger.LogInformation("GetScheduledPipelinesAsync ProjectName = {0} PathPrefix = {1}", projectName, pathPrefix);
var definitions = await client.GetFullDefinitionsAsync2(project: projectName, path: pathPrefix);
return definitions;
}
/// <summary>
/// Gets a build definition for the given ID
/// </summary>
/// <param name="pipelineId"></param>
/// <returns></returns>
public async Task<BuildDefinition> GetPipelineAsync(string projectName, int pipelineId)
{
var client = await GetClientAsync<BuildHttpClient>();
BuildDefinition result;
try
{
result = await client.GetDefinitionAsync(projectName, pipelineId);
}
catch (DefinitionNotFoundException)
{
result = default;
}
return result;
}
/// <summary>
/// Returns teams in the given project
/// </summary>
/// <param name="projectName">Name of the project</param>
/// <param name="skip">Number of entries to skip</param>
/// <param name="top">Maximum number of entries to return</param>
/// <returns>Teams that satisfy given criteria</returns>
public async Task<IEnumerable<WebApiTeam>> GetTeamsAsync(string projectName, int skip = 0, int top = int.MaxValue)
{
var client = await GetClientAsync<TeamHttpClient>();
logger.LogInformation("GetTeamsAsync ProjectName = {0}, skip = {1}", projectName, skip);
var teams = await client.GetTeamsAsync(projectName, skip: skip, top: top);
return teams;
}
/// <summary>
/// Creates a team in the given project
/// </summary>
/// <param name="projectId">ID of project to associate with team</param>
/// <param name="team">Team to create</param>
/// <returns>Team with properties set from creation</returns>
public async Task<WebApiTeam> CreateTeamForProjectAsync(string projectId, WebApiTeam team)
{
var client = await GetClientAsync<TeamHttpClient>();
logger.LogInformation("CreateTeamForProjectAsync TeamName = {0} ProjectId = {1}", team.Name, projectId);
var result = await client.CreateTeamAsync(team, projectId);
return result;
}
/// <summary>
/// Checks whether a child is a member of the parent entity
/// </summary>
/// <param name="parent">Parent descriptor</param>
/// <param name="child">Child descriptor</param>
/// <returns>True if the child is a member of the parent</returns>
public async Task<bool> CheckMembershipAsync(string parent, string child)
{
var client = await GetClientAsync<GraphHttpClient>();
logger.LogInformation("CheckMembership ParentId = {0} ChildId = {1}", parent, child);
var result = await client.CheckMembershipExistenceAsync(child, parent);
return result;
}
/// <summary>
/// Gets the descriptor for an object
/// </summary>
/// <param name="id">GUID of the object</param>
/// <returns>A descriptor string suitable for use in some Graph queries</returns>
public async Task<string> GetDescriptorAsync(Guid id)
{
var client = await GetClientAsync<GraphHttpClient>();
logger.LogInformation("GetDescriptor Id = {0}", id);
var descriptor = await client.GetDescriptorAsync(id);
return descriptor.Value;
}
/// <summary>
/// Gets the descriptor for a given User Principal
/// </summary>
/// <param name="userPrincipal">User Principal (e.g. alias@contoso.com)</param>
/// <returns></returns>
public async Task<string> GetDescriptorForPrincipal(string userPrincipal)
{
var client = await GetClientAsync<GraphHttpClient>();
logger.LogInformation("GetDescriptorForAlias UserPrincipal = {0}", userPrincipal);
var context = new GraphUserPrincipalNameCreationContext()
{
PrincipalName = userPrincipal,
};
var user = await client.CreateUserAsync(context);
return user.Descriptor;
}
/// <summary>
/// Gets a list of TeamMembers
/// </summary>
/// <param name="team">Team</param>
/// <returns>List of TeamMembers for the given team</returns>
public async Task<List<TeamMember>> GetMembersAsync(WebApiTeam team)
{
var client = await GetClientAsync<TeamHttpClient>();
logger.LogInformation("GetMembersAsync TeamId = {0}, TeamName = {1}", team.Id, team.Name);
var members = await client.GetTeamMembersWithExtendedPropertiesAsync(
team.ProjectId.ToString(),
team.Id.ToString()
);
return members;
}
/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<Identity> GetUserFromId(Guid id)
{
var client = await GetClientAsync<IdentityHttpClient>();
logger.LogInformation("GetUserFromId Id = {0}", id);
var result = await client.ReadIdentityAsync(id);
return result;
}
public async Task RemoveMember(string groupDescriptor, string memberDescriptor)
{
var client = await GetClientAsync<GraphHttpClient>();
logger.LogInformation("RemoveMember GroupDescriptor = {0}, MemberDescriptor = {1}");
await client.RemoveMembershipAsync(memberDescriptor, groupDescriptor);
}
/// <summary>
/// Adds a child item to a parent item
/// </summary>
/// <param name="parent">Parent descriptor</param>
/// <param name="child">Child descriptor</param>
/// <returns>GraphMembership object resulting from adding the child to the parent</returns>
public async Task<GraphMembership> AddToTeamAsync(string parent, string child)
{
var client = await GetClientAsync<GraphHttpClient>();
logger.LogInformation("AddTeamToTeamAsync ParentId = {0} ChildId = {1}", parent, child);
var result = await client.AddMembershipAsync(child, parent);
return result;
}
/// <summary>
/// Gets subscriptions for a given target GUID
/// </summary>
/// <remarks>
/// Some properties of the NotificationSubscription (like "Filter") are
/// not resolved in this API call. Expansion with a followup call may
/// be required
/// </remarks>
/// <param name="targetId">GUID of the subscription target</param>
/// <returns>Complete subscription objects</returns>
public async Task<IEnumerable<NotificationSubscription>> GetSubscriptionsAsync(Guid targetId)
{
var client = await GetClientAsync<NotificationHttpClient>();
logger.LogInformation("GetSubscriptionsAsync TargetId = {0}", targetId);
var result = await client.ListSubscriptionsAsync(targetId);
return result;
}
/// <summary>
/// Creates a subscription
/// </summary>
/// <param name="newSubscription">Subscription to create</param>
/// <returns>The newly created subscription</returns>
public async Task<NotificationSubscription> CreateSubscriptionAsync(NotificationSubscriptionCreateParameters newSubscription)
{
var client = await GetClientAsync<NotificationHttpClient>();
logger.LogInformation("CreateSubscriptionAsync Description = {0}", newSubscription.Description);
var result = await client.CreateSubscriptionAsync(newSubscription);
return result;
}
}
}
| |
using System;
using System.Linq;
using System.Reactive.Disposables;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives.PopupPositioning;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.LogicalTree;
using Avalonia.Metadata;
using Avalonia.Platform;
using Avalonia.VisualTree;
#nullable enable
namespace Avalonia.Controls.Primitives
{
/// <summary>
/// Displays a popup window.
/// </summary>
public class Popup : Control, IVisualTreeHost
{
public static readonly StyledProperty<bool> WindowManagerAddShadowHintProperty =
AvaloniaProperty.Register<PopupRoot, bool>(nameof(WindowManagerAddShadowHint), true);
/// <summary>
/// Defines the <see cref="Child"/> property.
/// </summary>
public static readonly StyledProperty<Control?> ChildProperty =
AvaloniaProperty.Register<Popup, Control?>(nameof(Child));
/// <summary>
/// Defines the <see cref="IsOpen"/> property.
/// </summary>
public static readonly DirectProperty<Popup, bool> IsOpenProperty =
AvaloniaProperty.RegisterDirect<Popup, bool>(
nameof(IsOpen),
o => o.IsOpen,
(o, v) => o.IsOpen = v);
/// <summary>
/// Defines the <see cref="PlacementAnchor"/> property.
/// </summary>
public static readonly StyledProperty<PopupAnchor> PlacementAnchorProperty =
AvaloniaProperty.Register<Popup, PopupAnchor>(nameof(PlacementAnchor));
/// <summary>
/// Defines the <see cref="PlacementConstraintAdjustment"/> property.
/// </summary>
public static readonly StyledProperty<PopupPositionerConstraintAdjustment> PlacementConstraintAdjustmentProperty =
AvaloniaProperty.Register<Popup, PopupPositionerConstraintAdjustment>(
nameof(PlacementConstraintAdjustment),
PopupPositionerConstraintAdjustment.FlipX | PopupPositionerConstraintAdjustment.FlipY |
PopupPositionerConstraintAdjustment.ResizeX | PopupPositionerConstraintAdjustment.ResizeY);
/// <summary>
/// Defines the <see cref="PlacementGravity"/> property.
/// </summary>
public static readonly StyledProperty<PopupGravity> PlacementGravityProperty =
AvaloniaProperty.Register<Popup, PopupGravity>(nameof(PlacementGravity));
/// <summary>
/// Defines the <see cref="PlacementMode"/> property.
/// </summary>
public static readonly StyledProperty<PlacementMode> PlacementModeProperty =
AvaloniaProperty.Register<Popup, PlacementMode>(nameof(PlacementMode), defaultValue: PlacementMode.Bottom);
/// <summary>
/// Defines the <see cref="PlacementRect"/> property.
/// </summary>
public static readonly StyledProperty<Rect?> PlacementRectProperty =
AvaloniaProperty.Register<Popup, Rect?>(nameof(PlacementRect));
/// <summary>
/// Defines the <see cref="PlacementTarget"/> property.
/// </summary>
public static readonly StyledProperty<Control?> PlacementTargetProperty =
AvaloniaProperty.Register<Popup, Control?>(nameof(PlacementTarget));
#pragma warning disable 618
/// <summary>
/// Defines the <see cref="ObeyScreenEdges"/> property.
/// </summary>
public static readonly StyledProperty<bool> ObeyScreenEdgesProperty =
AvaloniaProperty.Register<Popup, bool>(nameof(ObeyScreenEdges), true);
#pragma warning restore 618
public static readonly StyledProperty<bool> OverlayDismissEventPassThroughProperty =
AvaloniaProperty.Register<Popup, bool>(nameof(OverlayDismissEventPassThrough));
public static readonly DirectProperty<Popup, IInputElement> OverlayInputPassThroughElementProperty =
AvaloniaProperty.RegisterDirect<Popup, IInputElement>(
nameof(OverlayInputPassThroughElement),
o => o.OverlayInputPassThroughElement,
(o, v) => o.OverlayInputPassThroughElement = v);
/// <summary>
/// Defines the <see cref="HorizontalOffset"/> property.
/// </summary>
public static readonly StyledProperty<double> HorizontalOffsetProperty =
AvaloniaProperty.Register<Popup, double>(nameof(HorizontalOffset));
/// <summary>
/// Defines the <see cref="IsLightDismissEnabled"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsLightDismissEnabledProperty =
AvaloniaProperty.Register<Popup, bool>(nameof(IsLightDismissEnabled));
/// <summary>
/// Defines the <see cref="VerticalOffset"/> property.
/// </summary>
public static readonly StyledProperty<double> VerticalOffsetProperty =
AvaloniaProperty.Register<Popup, double>(nameof(VerticalOffset));
/// <summary>
/// Defines the <see cref="StaysOpen"/> property.
/// </summary>
[Obsolete("Use IsLightDismissEnabledProperty")]
public static readonly DirectProperty<Popup, bool> StaysOpenProperty =
AvaloniaProperty.RegisterDirect<Popup, bool>(
nameof(StaysOpen),
o => o.StaysOpen,
(o, v) => o.StaysOpen = v,
true);
/// <summary>
/// Defines the <see cref="Topmost"/> property.
/// </summary>
public static readonly StyledProperty<bool> TopmostProperty =
AvaloniaProperty.Register<Popup, bool>(nameof(Topmost));
private bool _isOpenRequested = false;
private bool _isOpen;
private bool _ignoreIsOpenChanged;
private PopupOpenState? _openState;
private IInputElement _overlayInputPassThroughElement;
/// <summary>
/// Initializes static members of the <see cref="Popup"/> class.
/// </summary>
static Popup()
{
IsHitTestVisibleProperty.OverrideDefaultValue<Popup>(false);
ChildProperty.Changed.AddClassHandler<Popup>((x, e) => x.ChildChanged(e));
IsOpenProperty.Changed.AddClassHandler<Popup>((x, e) => x.IsOpenChanged((AvaloniaPropertyChangedEventArgs<bool>)e));
}
/// <summary>
/// Raised when the popup closes.
/// </summary>
public event EventHandler<EventArgs>? Closed;
/// <summary>
/// Raised when the popup opens.
/// </summary>
public event EventHandler? Opened;
public IPopupHost? Host => _openState?.PopupHost;
public bool WindowManagerAddShadowHint
{
get { return GetValue(WindowManagerAddShadowHintProperty); }
set { SetValue(WindowManagerAddShadowHintProperty, value); }
}
/// <summary>
/// Gets or sets the control to display in the popup.
/// </summary>
[Content]
public Control? Child
{
get { return GetValue(ChildProperty); }
set { SetValue(ChildProperty, value); }
}
/// <summary>
/// Gets or sets a dependency resolver for the <see cref="PopupRoot"/>.
/// </summary>
/// <remarks>
/// This property allows a client to customize the behaviour of the popup by injecting
/// a specialized dependency resolver into the <see cref="PopupRoot"/>'s constructor.
/// </remarks>
public IAvaloniaDependencyResolver? DependencyResolver
{
get;
set;
}
/// <summary>
/// Gets or sets a value that determines how the <see cref="Popup"/> can be dismissed.
/// </summary>
/// <remarks>
/// Light dismiss is when the user taps on any area other than the popup.
/// </remarks>
public bool IsLightDismissEnabled
{
get => GetValue(IsLightDismissEnabledProperty);
set => SetValue(IsLightDismissEnabledProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the popup is currently open.
/// </summary>
public bool IsOpen
{
get { return _isOpen; }
set { SetAndRaise(IsOpenProperty, ref _isOpen, value); }
}
/// <summary>
/// Gets or sets the anchor point on the <see cref="PlacementRect"/> when <see cref="PlacementMode"/>
/// is <see cref="PlacementMode.AnchorAndGravity"/>.
/// </summary>
public PopupAnchor PlacementAnchor
{
get { return GetValue(PlacementAnchorProperty); }
set { SetValue(PlacementAnchorProperty, value); }
}
/// <summary>
/// Gets or sets a value describing how the popup position will be adjusted if the
/// unadjusted position would result in the popup being partly constrained.
/// </summary>
public PopupPositionerConstraintAdjustment PlacementConstraintAdjustment
{
get { return GetValue(PlacementConstraintAdjustmentProperty); }
set { SetValue(PlacementConstraintAdjustmentProperty, value); }
}
/// <summary>
/// Gets or sets a value which defines in what direction the popup should open
/// when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>.
/// </summary>
public PopupGravity PlacementGravity
{
get { return GetValue(PlacementGravityProperty); }
set { SetValue(PlacementGravityProperty, value); }
}
/// <summary>
/// Gets or sets the placement mode of the popup in relation to the <see cref="PlacementTarget"/>.
/// </summary>
public PlacementMode PlacementMode
{
get { return GetValue(PlacementModeProperty); }
set { SetValue(PlacementModeProperty, value); }
}
/// <summary>
/// Gets or sets the the anchor rectangle within the parent that the popup will be placed
/// relative to when <see cref="PlacementMode"/> is <see cref="PlacementMode.AnchorAndGravity"/>.
/// </summary>
/// <remarks>
/// The placement rect defines a rectangle relative to <see cref="PlacementTarget"/> around
/// which the popup will be opened, with <see cref="PlacementAnchor"/> determining which edge
/// of the placement target is used.
///
/// If unset, the anchor rectangle will be the bounds of the <see cref="PlacementTarget"/>.
/// </remarks>
public Rect? PlacementRect
{
get { return GetValue(PlacementRectProperty); }
set { SetValue(PlacementRectProperty, value); }
}
/// <summary>
/// Gets or sets the control that is used to determine the popup's position.
/// </summary>
[ResolveByName]
public Control? PlacementTarget
{
get { return GetValue(PlacementTargetProperty); }
set { SetValue(PlacementTargetProperty, value); }
}
[Obsolete("This property has no effect")]
public bool ObeyScreenEdges
{
get => GetValue(ObeyScreenEdgesProperty);
set => SetValue(ObeyScreenEdgesProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the event that closes the popup is passed
/// through to the parent window.
/// </summary>
/// <remarks>
/// When <see cref="IsLightDismissEnabled"/> is set to true, clicks outside the the popup
/// cause the popup to close. When <see cref="OverlayDismissEventPassThrough"/> is set to
/// false, these clicks will be handled by the popup and not be registered by the parent
/// window. When set to true, the events will be passed through to the parent window.
/// </remarks>
public bool OverlayDismissEventPassThrough
{
get => GetValue(OverlayDismissEventPassThroughProperty);
set => SetValue(OverlayDismissEventPassThroughProperty, value);
}
/// <summary>
/// Gets or sets an element that should receive pointer input events even when underneath
/// the popup's overlay.
/// </summary>
public IInputElement OverlayInputPassThroughElement
{
get => _overlayInputPassThroughElement;
set => SetAndRaise(OverlayInputPassThroughElementProperty, ref _overlayInputPassThroughElement, value);
}
/// <summary>
/// Gets or sets the Horizontal offset of the popup in relation to the <see cref="PlacementTarget"/>.
/// </summary>
public double HorizontalOffset
{
get { return GetValue(HorizontalOffsetProperty); }
set { SetValue(HorizontalOffsetProperty, value); }
}
/// <summary>
/// Gets or sets the Vertical offset of the popup in relation to the <see cref="PlacementTarget"/>.
/// </summary>
public double VerticalOffset
{
get { return GetValue(VerticalOffsetProperty); }
set { SetValue(VerticalOffsetProperty, value); }
}
/// <summary>
/// Gets or sets a value indicating whether the popup should stay open when the popup is
/// pressed or loses focus.
/// </summary>
[Obsolete("Use IsLightDismissEnabled")]
public bool StaysOpen
{
get => !IsLightDismissEnabled;
set => IsLightDismissEnabled = !value;
}
/// <summary>
/// Gets or sets whether this popup appears on top of all other windows
/// </summary>
public bool Topmost
{
get { return GetValue(TopmostProperty); }
set { SetValue(TopmostProperty, value); }
}
/// <summary>
/// Gets the root of the popup window.
/// </summary>
IVisual? IVisualTreeHost.Root => _openState?.PopupHost.HostedVisualTreeRoot;
/// <summary>
/// Opens the popup.
/// </summary>
public void Open()
{
// Popup is currently open
if (_openState != null)
{
return;
}
var placementTarget = PlacementTarget ?? this.FindLogicalAncestorOfType<IControl>();
if (placementTarget == null)
{
_isOpenRequested = true;
return;
}
var topLevel = placementTarget.VisualRoot as TopLevel;
if (topLevel == null)
{
_isOpenRequested = true;
return;
}
_isOpenRequested = false;
var popupHost = OverlayPopupHost.CreatePopupHost(placementTarget, DependencyResolver);
var handlerCleanup = new CompositeDisposable(5);
void DeferCleanup(IDisposable? disposable)
{
if (disposable is null)
{
return;
}
handlerCleanup.Add(disposable);
}
DeferCleanup(popupHost.BindConstraints(this, WidthProperty, MinWidthProperty, MaxWidthProperty,
HeightProperty, MinHeightProperty, MaxHeightProperty, TopmostProperty));
popupHost.SetChild(Child);
((ISetLogicalParent)popupHost).SetParent(this);
popupHost.ConfigurePosition(
placementTarget,
PlacementMode,
new Point(HorizontalOffset, VerticalOffset),
PlacementAnchor,
PlacementGravity,
PlacementConstraintAdjustment,
PlacementRect);
DeferCleanup(SubscribeToEventHandler<IPopupHost, EventHandler<TemplateAppliedEventArgs>>(popupHost, RootTemplateApplied,
(x, handler) => x.TemplateApplied += handler,
(x, handler) => x.TemplateApplied -= handler));
if (topLevel is Window window)
{
DeferCleanup(SubscribeToEventHandler<Window, EventHandler>(window, WindowDeactivated,
(x, handler) => x.Deactivated += handler,
(x, handler) => x.Deactivated -= handler));
DeferCleanup(SubscribeToEventHandler<IWindowImpl, Action>(window.PlatformImpl, WindowLostFocus,
(x, handler) => x.LostFocus += handler,
(x, handler) => x.LostFocus -= handler));
}
else
{
var parentPopupRoot = topLevel as PopupRoot;
if (parentPopupRoot?.Parent is Popup popup)
{
DeferCleanup(SubscribeToEventHandler<Popup, EventHandler<EventArgs>>(popup, ParentClosed,
(x, handler) => x.Closed += handler,
(x, handler) => x.Closed -= handler));
}
}
DeferCleanup(InputManager.Instance?.Process.Subscribe(ListenForNonClientClick));
var cleanupPopup = Disposable.Create((popupHost, handlerCleanup), state =>
{
state.handlerCleanup.Dispose();
state.popupHost.SetChild(null);
state.popupHost.Hide();
((ISetLogicalParent)state.popupHost).SetParent(null);
state.popupHost.Dispose();
});
if (IsLightDismissEnabled)
{
var dismissLayer = LightDismissOverlayLayer.GetLightDismissOverlayLayer(placementTarget);
if (dismissLayer != null)
{
dismissLayer.IsVisible = true;
dismissLayer.InputPassThroughElement = _overlayInputPassThroughElement;
DeferCleanup(Disposable.Create(() =>
{
dismissLayer.IsVisible = false;
dismissLayer.InputPassThroughElement = null;
}));
DeferCleanup(SubscribeToEventHandler<LightDismissOverlayLayer, EventHandler<PointerPressedEventArgs>>(
dismissLayer,
PointerPressedDismissOverlay,
(x, handler) => x.PointerPressed += handler,
(x, handler) => x.PointerPressed -= handler));
}
}
_openState = new PopupOpenState(topLevel, popupHost, cleanupPopup);
WindowManagerAddShadowHintChanged(popupHost, WindowManagerAddShadowHint);
popupHost.Show();
using (BeginIgnoringIsOpen())
{
IsOpen = true;
}
Opened?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Closes the popup.
/// </summary>
public void Close() => CloseCore();
/// <summary>
/// Measures the control.
/// </summary>
/// <param name="availableSize">The available size for the control.</param>
/// <returns>A size of 0,0 as Popup itself takes up no space.</returns>
protected override Size MeasureCore(Size availableSize)
{
return new Size();
}
/// <inheritdoc/>
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
if (_isOpenRequested)
{
Open();
}
}
/// <inheritdoc/>
protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e)
{
base.OnDetachedFromLogicalTree(e);
Close();
}
private static IDisposable SubscribeToEventHandler<T, TEventHandler>(T target, TEventHandler handler, Action<T, TEventHandler> subscribe, Action<T, TEventHandler> unsubscribe)
{
subscribe(target, handler);
return Disposable.Create((unsubscribe, target, handler), state => state.unsubscribe(state.target, state.handler));
}
private void WindowManagerAddShadowHintChanged(IPopupHost host, bool hint)
{
if(host is PopupRoot pr)
{
pr.PlatformImpl.SetWindowManagerAddShadowHint(hint);
}
}
/// <summary>
/// Called when the <see cref="IsOpen"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private void IsOpenChanged(AvaloniaPropertyChangedEventArgs<bool> e)
{
if (!_ignoreIsOpenChanged)
{
if (e.NewValue.Value)
{
Open();
}
else
{
Close();
}
}
}
/// <summary>
/// Called when the <see cref="Child"/> property changes.
/// </summary>
/// <param name="e">The event args.</param>
private void ChildChanged(AvaloniaPropertyChangedEventArgs e)
{
LogicalChildren.Clear();
((ISetLogicalParent?)e.OldValue)?.SetParent(null);
if (e.NewValue != null)
{
((ISetLogicalParent)e.NewValue).SetParent(this);
LogicalChildren.Add((ILogical)e.NewValue);
}
}
private void CloseCore()
{
_isOpenRequested = false;
if (_openState is null)
{
using (BeginIgnoringIsOpen())
{
IsOpen = false;
}
return;
}
_openState.Dispose();
_openState = null;
using (BeginIgnoringIsOpen())
{
IsOpen = false;
}
Closed?.Invoke(this, EventArgs.Empty);
var focusCheck = FocusManager.Instance?.Current;
// Focus is set to null as part of popup closing, so we only want to
// set focus to PlacementTarget if this is the case
if (focusCheck == null)
{
if (PlacementTarget != null)
{
FocusManager.Instance?.Focus(PlacementTarget);
}
else
{
var anc = this.FindLogicalAncestorOfType<IControl>();
if (anc != null)
{
FocusManager.Instance?.Focus(anc);
}
}
}
}
private void ListenForNonClientClick(RawInputEventArgs e)
{
var mouse = e as RawPointerEventArgs;
if (IsLightDismissEnabled && mouse?.Type == RawPointerEventType.NonClientLeftButtonDown)
{
CloseCore();
}
}
private void PointerPressedDismissOverlay(object sender, PointerPressedEventArgs e)
{
if (IsLightDismissEnabled && e.Source is IVisual v && !IsChildOrThis(v))
{
CloseCore();
if (OverlayDismissEventPassThrough)
{
PassThroughEvent(e);
}
}
}
private void PassThroughEvent(PointerPressedEventArgs e)
{
if (e.Source is LightDismissOverlayLayer layer &&
layer.GetVisualRoot() is IInputElement root)
{
var p = e.GetCurrentPoint(root);
var hit = root.InputHitTest(p.Position, x => x != layer);
if (hit != null)
{
e.Pointer.Capture(hit);
hit.RaiseEvent(e);
e.Handled = true;
}
}
}
private void RootTemplateApplied(object sender, TemplateAppliedEventArgs e)
{
if (_openState is null)
{
return;
}
var popupHost = _openState.PopupHost;
popupHost.TemplateApplied -= RootTemplateApplied;
_openState.SetPresenterSubscription(null);
// If the Popup appears in a control template, then the child controls
// that appear in the popup host need to have their TemplatedParent
// properties set.
if (TemplatedParent != null && popupHost.Presenter != null)
{
popupHost.Presenter.ApplyTemplate();
var presenterSubscription = popupHost.Presenter.GetObservable(ContentPresenter.ChildProperty)
.Subscribe(SetTemplatedParentAndApplyChildTemplates);
_openState.SetPresenterSubscription(presenterSubscription);
}
}
private void SetTemplatedParentAndApplyChildTemplates(IControl control)
{
if (control != null)
{
var templatedParent = TemplatedParent;
if (control.TemplatedParent == null)
{
control.SetValue(TemplatedParentProperty, templatedParent);
}
control.ApplyTemplate();
if (!(control is IPresenter) && control.TemplatedParent == templatedParent)
{
foreach (IControl child in control.VisualChildren)
{
SetTemplatedParentAndApplyChildTemplates(child);
}
}
}
}
private bool IsChildOrThis(IVisual child)
{
if (_openState is null)
{
return false;
}
var popupHost = _openState.PopupHost;
IVisual? root = child.VisualRoot;
while (root is IHostedVisualTreeRoot hostedRoot)
{
if (root == popupHost)
{
return true;
}
root = hostedRoot.Host?.VisualRoot;
}
return false;
}
public bool IsInsidePopup(IVisual visual)
{
if (_openState is null)
{
return false;
}
var popupHost = _openState.PopupHost;
return popupHost != null && ((IVisual)popupHost).IsVisualAncestorOf(visual);
}
public bool IsPointerOverPopup => ((IInputElement?)_openState?.PopupHost)?.IsPointerOver ?? false;
private void WindowDeactivated(object sender, EventArgs e)
{
if (IsLightDismissEnabled)
{
Close();
}
}
private void ParentClosed(object sender, EventArgs e)
{
if (IsLightDismissEnabled)
{
Close();
}
}
private void WindowLostFocus()
{
if (IsLightDismissEnabled)
Close();
}
private IgnoreIsOpenScope BeginIgnoringIsOpen()
{
return new IgnoreIsOpenScope(this);
}
private readonly struct IgnoreIsOpenScope : IDisposable
{
private readonly Popup _owner;
public IgnoreIsOpenScope(Popup owner)
{
_owner = owner;
_owner._ignoreIsOpenChanged = true;
}
public void Dispose()
{
_owner._ignoreIsOpenChanged = false;
}
}
private class PopupOpenState : IDisposable
{
private readonly IDisposable _cleanup;
private IDisposable? _presenterCleanup;
public PopupOpenState(TopLevel topLevel, IPopupHost popupHost, IDisposable cleanup)
{
TopLevel = topLevel;
PopupHost = popupHost;
_cleanup = cleanup;
}
public TopLevel TopLevel { get; }
public IPopupHost PopupHost { get; }
public void SetPresenterSubscription(IDisposable? presenterCleanup)
{
_presenterCleanup?.Dispose();
_presenterCleanup = presenterCleanup;
}
public void Dispose()
{
_presenterCleanup?.Dispose();
_cleanup.Dispose();
}
}
}
}
| |
// 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;
namespace System.Globalization
{
/// <summary>
/// This class defines behaviors specific to a writing system.
/// A writing system is the collection of scripts and orthographic rules
/// required to represent a language as text.
/// </summary>
public class StringInfo
{
private string _str;
private int[] _indexes;
public StringInfo() : this(string.Empty)
{
}
public StringInfo(string value)
{
this.String = value;
}
public override bool Equals(object value)
{
return value is StringInfo otherStringInfo
&& _str.Equals(otherStringInfo._str);
}
public override int GetHashCode() => _str.GetHashCode();
/// <summary>
/// Our zero-based array of index values into the string. Initialize if
/// our private array is not yet, in fact, initialized.
/// </summary>
private int[] Indexes
{
get
{
if (_indexes == null && String.Length > 0)
{
_indexes = StringInfo.ParseCombiningCharacters(String);
}
return _indexes;
}
}
public string String
{
get => _str;
set
{
_str = value ?? throw new ArgumentNullException(nameof(value));
_indexes = null;
}
}
public int LengthInTextElements => Indexes?.Length ?? 0;
public string SubstringByTextElements(int startingTextElement)
{
// If the string is empty, no sense going further.
if (Indexes == null)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.ArgumentOutOfRange_NeedPosNum);
}
else
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.Arg_ArgumentOutOfRangeException);
}
}
return SubstringByTextElements(startingTextElement, Indexes.Length - startingTextElement);
}
public string SubstringByTextElements(int startingTextElement, int lengthInTextElements)
{
if (startingTextElement < 0)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.ArgumentOutOfRange_NeedPosNum);
}
if (String.Length == 0 || startingTextElement >= Indexes.Length)
{
throw new ArgumentOutOfRangeException(nameof(startingTextElement), startingTextElement, SR.Arg_ArgumentOutOfRangeException);
}
if (lengthInTextElements < 0)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), lengthInTextElements, SR.ArgumentOutOfRange_NeedPosNum);
}
if (startingTextElement > Indexes.Length - lengthInTextElements)
{
throw new ArgumentOutOfRangeException(nameof(lengthInTextElements), lengthInTextElements, SR.Arg_ArgumentOutOfRangeException);
}
int start = Indexes[startingTextElement];
if (startingTextElement + lengthInTextElements == Indexes.Length)
{
// We are at the last text element in the string and because of that
// must handle the call differently.
return String.Substring(start);
}
else
{
return String.Substring(start, Indexes[lengthInTextElements + startingTextElement] - start);
}
}
public static string GetNextTextElement(string str) => GetNextTextElement(str, 0);
/// <summary>
/// Get the code point count of the current text element.
///
/// A combining class is defined as:
/// A character/surrogate that has the following Unicode category:
/// * NonSpacingMark (e.g. U+0300 COMBINING GRAVE ACCENT)
/// * SpacingCombiningMark (e.g. U+ 0903 DEVANGARI SIGN VISARGA)
/// * EnclosingMark (e.g. U+20DD COMBINING ENCLOSING CIRCLE)
///
/// In the context of GetNextTextElement() and ParseCombiningCharacters(), a text element is defined as:
/// 1. If a character/surrogate is in the following category, it is a text element.
/// It can NOT further combine with characters in the combinging class to form a text element.
/// * one of the Unicode category in the combinging class
/// * UnicodeCategory.Format
/// * UnicodeCateogry.Control
/// * UnicodeCategory.OtherNotAssigned
/// 2. Otherwise, the character/surrogate can be combined with characters in the combinging class to form a text element.
/// </summary>
/// <returns>The length of the current text element</returns>
internal static int GetCurrentTextElementLen(string str, int index, int len, ref UnicodeCategory ucCurrent, ref int currentCharCount)
{
Debug.Assert(index >= 0 && len >= 0, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
Debug.Assert(index < len, "StringInfo.GetCurrentTextElementLen() : index = " + index + ", len = " + len);
if (index + currentCharCount == len)
{
// This is the last character/surrogate in the string.
return currentCharCount;
}
// Call an internal GetUnicodeCategory, which will tell us both the unicode category, and also tell us if it is a surrogate pair or not.
int nextCharCount;
UnicodeCategory ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index + currentCharCount, out nextCharCount);
if (CharUnicodeInfo.IsCombiningCategory(ucNext))
{
// The next element is a combining class.
// Check if the current text element to see if it is a valid base category (i.e. it should not be a combining category,
// not a format character, and not a control character).
if (CharUnicodeInfo.IsCombiningCategory(ucCurrent)
|| (ucCurrent == UnicodeCategory.Format)
|| (ucCurrent == UnicodeCategory.Control)
|| (ucCurrent == UnicodeCategory.OtherNotAssigned)
|| (ucCurrent == UnicodeCategory.Surrogate)) // An unpair high surrogate or low surrogate
{
// Will fall thru and return the currentCharCount
}
else
{
// Remember the current index.
int startIndex = index;
// We have a valid base characters, and we have a character (or surrogate) that is combining.
// Check if there are more combining characters to follow.
// Check if the next character is a nonspacing character.
index += currentCharCount + nextCharCount;
while (index < len)
{
ucNext = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out nextCharCount);
if (!CharUnicodeInfo.IsCombiningCategory(ucNext))
{
ucCurrent = ucNext;
currentCharCount = nextCharCount;
break;
}
index += nextCharCount;
}
return index - startIndex;
}
}
// The return value will be the currentCharCount.
int ret = currentCharCount;
ucCurrent = ucNext;
// Update currentCharCount.
currentCharCount = nextCharCount;
return ret;
}
/// <summary>
/// Returns the str containing the next text element in str starting at
/// index index. If index is not supplied, then it will start at the beginning
/// of str. It recognizes a base character plus one or more combining
/// characters or a properly formed surrogate pair as a text element.
/// See also the ParseCombiningCharacters() and the ParseSurrogates() methods.
/// </summary>
public static string GetNextTextElement(string str, int index)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
if (index < 0 || index >= len)
{
if (index == len)
{
return string.Empty;
}
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
int charLen;
UnicodeCategory uc = CharUnicodeInfo.InternalGetUnicodeCategory(str, index, out charLen);
return str.Substring(index, GetCurrentTextElementLen(str, index, len, ref uc, ref charLen));
}
public static TextElementEnumerator GetTextElementEnumerator(string str)
{
return GetTextElementEnumerator(str, 0);
}
public static TextElementEnumerator GetTextElementEnumerator(string str, int index)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
if (index < 0 || index > len)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
return new TextElementEnumerator(str, index, len);
}
/// <summary>
/// Returns the indices of each base character or properly formed surrogate
/// pair within the str. It recognizes a base character plus one or more
/// combining characters or a properly formed surrogate pair as a text
/// element and returns the index of the base character or high surrogate.
/// Each index is the beginning of a text element within a str. The length
/// of each element is easily computed as the difference between successive
/// indices. The length of the array will always be less than or equal to
/// the length of the str. For example, given the str
/// \u4f00\u302a\ud800\udc00\u4f01, this method would return the indices:
/// 0, 2, 4.
/// </summary>
public static int[] ParseCombiningCharacters(string str)
{
if (str == null)
{
throw new ArgumentNullException(nameof(str));
}
int len = str.Length;
int[] result = new int[len];
if (len == 0)
{
return (result);
}
int resultCount = 0;
int i = 0;
int currentCharLen;
UnicodeCategory currentCategory = CharUnicodeInfo.InternalGetUnicodeCategory(str, 0, out currentCharLen);
while (i < len)
{
result[resultCount++] = i;
i += GetCurrentTextElementLen(str, i, len, ref currentCategory, ref currentCharLen);
}
if (resultCount < len)
{
int[] returnArray = new int[resultCount];
Array.Copy(result, 0, returnArray, 0, resultCount);
return (returnArray);
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.AspNetCore.Razor.Language.Intermediate;
using Xunit;
using Xunit.Sdk;
namespace Microsoft.AspNetCore.Razor.Language.IntegrationTests
{
public static class IntermediateNodeVerifier
{
public static void Verify(IntermediateNode node, string[] baseline)
{
var walker = new Walker(baseline);
walker.Visit(node);
walker.AssertReachedEndOfBaseline();
}
private class Walker : IntermediateNodeWalker
{
private readonly string[] _baseline;
private readonly IntermediateNodeWriter _visitor;
private readonly StringWriter _writer;
private int _index;
public Walker(string[] baseline)
{
_writer = new StringWriter();
_visitor = new IntermediateNodeWriter(_writer);
_baseline = baseline;
}
public TextWriter Writer { get; }
public override void VisitDefault(IntermediateNode node)
{
var expected = _index < _baseline.Length ? _baseline[_index++] : null;
// Write the node as text for comparison
_writer.GetStringBuilder().Clear();
_visitor.Visit(node);
var actual = _writer.GetStringBuilder().ToString();
AssertNodeEquals(node, Ancestors, expected, actual);
_visitor.Depth++;
base.VisitDefault(node);
_visitor.Depth--;
}
public void AssertReachedEndOfBaseline()
{
// Since we're walking the nodes of our generated code there's the chance that our baseline is longer.
Assert.True(_baseline.Length == _index, "Not all lines of the baseline were visited!");
}
private void AssertNodeEquals(IntermediateNode node, IEnumerable<IntermediateNode> ancestors, string expected, string actual)
{
if (string.Equals(expected, actual))
{
// YAY!!! everything is great.
return;
}
if (expected == null)
{
var message = "The node is missing from baseline.";
throw new IntermediateNodeBaselineException(node, Ancestors.ToArray(), expected, actual, message);
}
int charsVerified = 0;
AssertNestingEqual(node, ancestors, expected, actual, ref charsVerified);
AssertNameEqual(node, ancestors, expected, actual, ref charsVerified);
AssertDelimiter(node, expected, actual, true, ref charsVerified);
AssertLocationEqual(node, ancestors, expected, actual, ref charsVerified);
AssertDelimiter(node, expected, actual, false, ref charsVerified);
AssertContentEqual(node, ancestors, expected, actual, ref charsVerified);
throw new InvalidOperationException("We can't figure out HOW these two things are different. This is a bug.");
}
private void AssertNestingEqual(IntermediateNode node, IEnumerable<IntermediateNode> ancestors, string expected, string actual, ref int charsVerified)
{
var i = 0;
for (; i < expected.Length; i++)
{
if (expected[i] != ' ')
{
break;
}
}
var failed = false;
var j = 0;
for (; j < i; j++)
{
if (actual.Length <= j || actual[j] != ' ')
{
failed = true;
break;
}
}
if (actual.Length <= j + 1 || actual[j] == ' ')
{
failed = true;
}
if (failed)
{
var message = "The node is at the wrong level of nesting. This usually means a child is missing.";
throw new IntermediateNodeBaselineException(node, ancestors.ToArray(), expected, actual, message);
}
charsVerified = j;
}
private void AssertNameEqual(IntermediateNode node, IEnumerable<IntermediateNode> ancestors, string expected, string actual, ref int charsVerified)
{
var expectedName = GetName(expected, charsVerified);
var actualName = GetName(actual, charsVerified);
if (!string.Equals(expectedName, actualName))
{
var message = "Node names are not equal.";
throw new IntermediateNodeBaselineException(node, ancestors.ToArray(), expected, actual, message);
}
charsVerified += expectedName.Length;
}
// Either both strings need to have a delimiter next or neither should.
private void AssertDelimiter(IntermediateNode node, string expected, string actual, bool required, ref int charsVerified)
{
if (charsVerified == expected.Length && required)
{
throw new InvalidOperationException($"Baseline text is not well-formed: '{expected}'.");
}
if (charsVerified == actual.Length && required)
{
throw new InvalidOperationException($"Baseline text is not well-formed: '{actual}'.");
}
if (charsVerified == expected.Length && charsVerified == actual.Length)
{
return;
}
var expectedDelimiter = expected.IndexOf(" - ", charsVerified, StringComparison.Ordinal);
if (expectedDelimiter != charsVerified && expectedDelimiter != -1)
{
throw new InvalidOperationException($"Baseline text is not well-formed: '{actual}'.");
}
var actualDelimiter = actual.IndexOf(" - ", charsVerified, StringComparison.Ordinal);
if (actualDelimiter != charsVerified && actualDelimiter != -1)
{
throw new InvalidOperationException($"Baseline text is not well-formed: '{actual}'.");
}
Assert.Equal(expectedDelimiter, actualDelimiter);
charsVerified += 3;
}
private void AssertLocationEqual(IntermediateNode node, IEnumerable<IntermediateNode> ancestors, string expected, string actual, ref int charsVerified)
{
var expectedLocation = GetLocation(expected, charsVerified);
var actualLocation = GetLocation(actual, charsVerified);
if (!string.Equals(expectedLocation, actualLocation))
{
var message = "Locations are not equal.";
throw new IntermediateNodeBaselineException(node, ancestors.ToArray(), expected, actual, message);
}
charsVerified += expectedLocation.Length;
}
private void AssertContentEqual(IntermediateNode node, IEnumerable<IntermediateNode> ancestors, string expected, string actual, ref int charsVerified)
{
var expectedContent = GetContent(expected, charsVerified);
var actualContent = GetContent(actual, charsVerified);
if (!string.Equals(expectedContent, actualContent))
{
var message = "Contents are not equal.";
throw new IntermediateNodeBaselineException(node, ancestors.ToArray(), expected, actual, message);
}
charsVerified += expectedContent.Length;
}
private string GetName(string text, int start)
{
var delimiter = text.IndexOf(" - ", start, StringComparison.Ordinal);
if (delimiter == -1)
{
throw new InvalidOperationException($"Baseline text is not well-formed: '{text}'.");
}
return text.Substring(start, delimiter - start);
}
private string GetLocation(string text, int start)
{
var delimiter = text.IndexOf(" - ", start, StringComparison.Ordinal);
return delimiter == -1 ? text.Substring(start) : text.Substring(start, delimiter - start);
}
private string GetContent(string text, int start)
{
return start == text.Length ? string.Empty : text.Substring(start);
}
private class IntermediateNodeBaselineException : XunitException
{
public IntermediateNodeBaselineException(IntermediateNode node, IntermediateNode[] ancestors, string expected, string actual, string userMessage)
: base(Format(node, ancestors, expected, actual, userMessage))
{
Node = node;
Expected = expected;
Actual = actual;
}
public IntermediateNode Node { get; }
public string Actual { get; }
public string Expected { get; }
private static string Format(IntermediateNode node, IntermediateNode[] ancestors, string expected, string actual, string userMessage)
{
var builder = new StringBuilder();
builder.AppendLine(userMessage);
builder.AppendLine();
if (expected != null)
{
builder.Append("Expected: ");
builder.AppendLine(expected);
}
if (actual != null)
{
builder.Append("Actual: ");
builder.AppendLine(actual);
}
if (ancestors != null)
{
builder.AppendLine();
builder.AppendLine("Path:");
foreach (var ancestor in ancestors)
{
builder.AppendLine(ancestor.ToString());
}
}
return builder.ToString();
}
}
}
}
}
| |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.Common;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using static System.FormattableString;
namespace ReactNative.Chakra.Executor
{
/// <summary>
/// JavaScript runtime wrapper.
/// </summary>
public sealed class ChakraJavaScriptExecutor : IJavaScriptExecutor
{
private const string MagicFileName = "UNBUNDLE";
private const uint MagicFileHeader = 0xFB0BD1E5;
private const string JsonName = "JSON";
private const string FBBatchedBridgeVariableName = "__fbBatchedBridge";
private readonly JavaScriptRuntime _runtime;
private IJavaScriptUnbundle _unbundle;
private JavaScriptSourceContext _context;
private JavaScriptNativeFunction _nativeLoggingHook;
private JavaScriptNativeFunction _nativeRequire;
private JavaScriptValue _globalObject;
private JavaScriptValue _callFunctionAndReturnFlushedQueueFunction;
private JavaScriptValue _invokeCallbackAndReturnFlushedQueueFunction;
private JavaScriptValue _flushedQueueFunction;
#if !NATIVE_JSON_MARSHALING
private JavaScriptValue _parseFunction;
private JavaScriptValue _stringifyFunction;
#endif
/// <summary>
/// Instantiates the <see cref="ChakraJavaScriptExecutor"/>.
/// </summary>
public ChakraJavaScriptExecutor()
{
_runtime = JavaScriptRuntime.Create();
_context = JavaScriptSourceContext.FromIntPtr(IntPtr.Zero);
InitializeChakra();
}
/// <summary>
/// Call the JavaScript method from the given module.
/// </summary>
/// <param name="moduleName">The module name.</param>
/// <param name="methodName">The method name.</param>
/// <param name="arguments">The arguments.</param>
/// <returns>The flushed queue of native operations.</returns>
public JToken CallFunctionReturnFlushedQueue(string moduleName, string methodName, JArray arguments)
{
if (moduleName == null)
throw new ArgumentNullException(nameof(moduleName));
if (methodName == null)
throw new ArgumentNullException(nameof(methodName));
if (arguments == null)
throw new ArgumentNullException(nameof(arguments));
var moduleNameValue = JavaScriptValue.FromString(moduleName);
moduleNameValue.AddRef();
var methodNameValue = JavaScriptValue.FromString(methodName);
methodNameValue.AddRef();
var argumentsValue = ConvertJson(arguments);
argumentsValue.AddRef();
var callArguments = new JavaScriptValue[4];
callArguments[0] = EnsureGlobalObject();
callArguments[1] = moduleNameValue;
callArguments[2] = methodNameValue;
callArguments[3] = argumentsValue;
var method = EnsureCallFunction();
var flushedQueue = ConvertJson(method.CallFunction(callArguments));
argumentsValue.Release();
methodNameValue.Release();
moduleNameValue.Release();
return flushedQueue;
}
/// <summary>
/// Flush the queue.
/// </summary>
/// <returns>The flushed queue of native operations.</returns>
public JToken FlushedQueue()
{
var method = EnsureFlushedQueueFunction();
var callArguments = new JavaScriptValue[1];
callArguments[0] = EnsureGlobalObject();
return ConvertJson(method.CallFunction(callArguments));
}
/// <summary>
/// Invoke the JavaScript callback.
/// </summary>
/// <param name="callbackId">The callback identifier.</param>
/// <param name="arguments">The arguments.</param>
/// <returns>The flushed queue of native operations.</returns>
public JToken InvokeCallbackAndReturnFlushedQueue(int callbackId, JArray arguments)
{
if (arguments == null)
throw new ArgumentNullException(nameof(arguments));
var callbackIdValue = JavaScriptValue.FromInt32(callbackId);
callbackIdValue.AddRef();
var argumentsValue = ConvertJson(arguments);
argumentsValue.AddRef();
var callArguments = new JavaScriptValue[3];
callArguments[0] = EnsureGlobalObject();
callArguments[1] = callbackIdValue;
callArguments[2] = argumentsValue;
var method = EnsureInvokeFunction();
var flushedQueue = ConvertJson(method.CallFunction(callArguments));
argumentsValue.Release();
callbackIdValue.Release();
return flushedQueue;
}
/// <summary>
/// Runs the script at the given path.
/// </summary>
/// <param name="sourcePath">The source path.</param>
/// <param name="sourceUrl">The source URL.</param>
public void RunScript(string sourcePath, string sourceUrl)
{
if (sourcePath == null)
throw new ArgumentNullException(nameof(sourcePath));
if (sourceUrl == null)
throw new ArgumentNullException(nameof(sourceUrl));
var startupCode = default(string);
if (IsUnbundle(sourcePath))
{
_unbundle = new FileBasedJavaScriptUnbundle(sourcePath);
InstallNativeRequire();
startupCode = _unbundle.GetStartupCode();
}
else if (IsIndexedUnbundle(sourcePath))
{
_unbundle = new IndexedJavaScriptUnbundle(sourcePath);
InstallNativeRequire();
startupCode = _unbundle.GetStartupCode();
}
else
{
startupCode = LoadScript(sourcePath);
}
EvaluateScript(startupCode, sourceUrl);
}
/// <summary>
/// Sets a global variable in the JavaScript runtime.
/// </summary>
/// <param name="propertyName">The global variable name.</param>
/// <param name="value">The value.</param>
public void SetGlobalVariable(string propertyName, JToken value)
{
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
if (value == null)
throw new ArgumentNullException(nameof(value));
var javaScriptValue = ConvertJson(value);
var propertyId = JavaScriptPropertyId.FromString(propertyName);
EnsureGlobalObject().SetProperty(propertyId, javaScriptValue, true);
}
/// <summary>
/// Gets a global variable from the JavaScript runtime.
/// </summary>
/// <param name="propertyName">The global variable name.</param>
/// <returns>The value.</returns>
public JToken GetGlobalVariable(string propertyName)
{
if (propertyName == null)
throw new ArgumentNullException(nameof(propertyName));
var propertyId = JavaScriptPropertyId.FromString(propertyName);
return ConvertJson(EnsureGlobalObject().GetProperty(propertyId));
}
/// <summary>
/// Disposes the <see cref="ChakraJavaScriptExecutor"/> instance.
/// </summary>
public void Dispose()
{
JavaScriptContext.Current = JavaScriptContext.Invalid;
_runtime.Dispose();
}
private void InitializeChakra()
{
JavaScriptContext.Current = _runtime.CreateContext();
_nativeLoggingHook = NativeLoggingHook;
EnsureGlobalObject().SetProperty(
JavaScriptPropertyId.FromString("nativeLoggingHook"),
JavaScriptValue.CreateFunction(_nativeLoggingHook),
true);
}
private void EvaluateScript(string script, string sourceUrl)
{
try
{
_context = JavaScriptSourceContext.Increment(_context);
JavaScriptContext.RunScript(script, _context, sourceUrl);
}
catch (JavaScriptScriptException ex)
{
var jsonError = JavaScriptValueToJTokenConverter.Convert(ex.Error);
var message = jsonError.Value<string>("message");
var stackTrace = jsonError.Value<string>("stack");
throw new Modules.Core.JavaScriptException(message ?? ex.Message, stackTrace, ex);
}
}
#region JSON Marshaling
#if NATIVE_JSON_MARSHALING
private JavaScriptValue ConvertJson(JToken token)
{
return JTokenToJavaScriptValueConverter.Convert(token);
}
private JToken ConvertJson(JavaScriptValue value)
{
return JavaScriptValueToJTokenConverter.Convert(value);
}
#else
private JavaScriptValue ConvertJson(JToken token)
{
var jsonString = token.ToString(Formatting.None);
var jsonStringValue = JavaScriptValue.FromString(jsonString);
jsonStringValue.AddRef();
var parseFunction = EnsureParseFunction();
var jsonValue = parseFunction.CallFunction(_globalObject, jsonStringValue);
jsonStringValue.Release();
return jsonValue;
}
private JToken ConvertJson(JavaScriptValue value)
{
var stringifyFunction = EnsureStringifyFunction();
var jsonStringValue = stringifyFunction.CallFunction(_globalObject, value);
jsonStringValue.AddRef();
var jsonString = jsonStringValue.ToString();
jsonStringValue.Release();
return JToken.Parse(jsonString);
}
#endif
#endregion
#region Console Callbacks
private JavaScriptValue NativeLoggingHook(
JavaScriptValue callee,
bool isConstructCall,
JavaScriptValue[] arguments,
ushort argumentCount,
IntPtr callbackData)
{
try
{
var message = arguments[1].ToString();
var logLevel = (LogLevel)(int)arguments[2].ToDouble();
Debug.WriteLine($"[JS {logLevel}] {message}");
}
catch
{
Debug.WriteLine("Unable to process JavaScript console statement");
}
return JavaScriptValue.Undefined;
}
#endregion
#region Native Require
private void InstallNativeRequire()
{
_nativeRequire = NativeRequire;
EnsureGlobalObject().SetProperty(
JavaScriptPropertyId.FromString("nativeRequire"),
JavaScriptValue.CreateFunction(_nativeRequire),
true);
}
private JavaScriptValue NativeRequire(
JavaScriptValue callee,
bool isConstructCall,
JavaScriptValue[] arguments,
ushort argumentCount,
IntPtr callbackData)
{
if (argumentCount != 2)
{
throw new ArgumentOutOfRangeException(nameof(argumentCount), "Expected exactly two arguments (global and moduleId).");
}
var moduleId = arguments[1].ToDouble();
if (moduleId <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(arguments),
Invariant($"Received invalid module ID '{moduleId}'."));
}
var module = _unbundle.GetModule((int)moduleId);
EvaluateScript(module.Source, module.SourceUrl);
return JavaScriptValue.Invalid;
}
#endregion
#region Global Helpers
private JavaScriptValue EnsureGlobalObject()
{
if (!_globalObject.IsValid)
{
_globalObject = JavaScriptValue.GlobalObject;
}
return _globalObject;
}
private JavaScriptValue EnsureParseFunction()
{
if (!_parseFunction.IsValid)
{
var globalObject = EnsureGlobalObject();
var jsonObject = globalObject.GetProperty(JavaScriptPropertyId.FromString(JsonName));
_parseFunction = jsonObject.GetProperty(JavaScriptPropertyId.FromString("parse"));
}
return _parseFunction;
}
private JavaScriptValue EnsureBatchedBridge()
{
var globalObject = EnsureGlobalObject();
var propertyId = JavaScriptPropertyId.FromString(FBBatchedBridgeVariableName);
var fbBatchedBridge = globalObject.GetProperty(propertyId);
if (fbBatchedBridge.ValueType != JavaScriptValueType.Object)
{
throw new InvalidOperationException(
Invariant($"Could not resolve '{FBBatchedBridgeVariableName}' object. Check the JavaScript bundle to ensure it is generated correctly."));
}
return fbBatchedBridge;
}
private JavaScriptValue EnsureStringifyFunction()
{
if (!_stringifyFunction.IsValid)
{
var globalObject = EnsureGlobalObject();
var jsonObject = globalObject.GetProperty(JavaScriptPropertyId.FromString(JsonName));
_stringifyFunction = jsonObject.GetProperty(JavaScriptPropertyId.FromString("stringify"));
}
return _stringifyFunction;
}
private JavaScriptValue EnsureCallFunction()
{
if (!_callFunctionAndReturnFlushedQueueFunction.IsValid)
{
var fbBatchedBridge = EnsureBatchedBridge();
var functionPropertyId = JavaScriptPropertyId.FromString("callFunctionReturnFlushedQueue");
_callFunctionAndReturnFlushedQueueFunction = fbBatchedBridge.GetProperty(functionPropertyId);
}
return _callFunctionAndReturnFlushedQueueFunction;
}
private JavaScriptValue EnsureInvokeFunction()
{
if (!_invokeCallbackAndReturnFlushedQueueFunction.IsValid)
{
var fbBatchedBridge = EnsureBatchedBridge();
var functionPropertyId = JavaScriptPropertyId.FromString("invokeCallbackAndReturnFlushedQueue");
_invokeCallbackAndReturnFlushedQueueFunction = fbBatchedBridge.GetProperty(functionPropertyId);
}
return _invokeCallbackAndReturnFlushedQueueFunction;
}
private JavaScriptValue EnsureFlushedQueueFunction()
{
if (!_flushedQueueFunction.IsValid)
{
var fbBatchedBridge = EnsureBatchedBridge();
var functionPropertyId = JavaScriptPropertyId.FromString("flushedQueue");
_flushedQueueFunction = fbBatchedBridge.GetProperty(functionPropertyId);
}
return _flushedQueueFunction;
}
#endregion
#region File IO
private static string LoadScript(string fileName)
{
try
{
return File.ReadAllText(fileName);
}
catch (Exception ex)
{
var exceptionMessage = Invariant($"File read exception for asset '{fileName}'.");
throw new InvalidOperationException(exceptionMessage, ex);
}
}
#endregion
#region Unbundle
class JavaScriptUnbundleModule
{
public JavaScriptUnbundleModule(string source, string sourceUrl)
{
SourceUrl = sourceUrl;
Source = source;
}
public string SourceUrl { get; }
public string Source { get; }
}
interface IJavaScriptUnbundle : IDisposable
{
JavaScriptUnbundleModule GetModule(int index);
string GetStartupCode();
}
class FileBasedJavaScriptUnbundle : IJavaScriptUnbundle
{
private readonly string _sourcePath;
private readonly string _modulesPath;
public FileBasedJavaScriptUnbundle(string sourcePath)
{
_sourcePath = sourcePath;
_modulesPath = GetUnbundleModulesDirectory(sourcePath);
}
public JavaScriptUnbundleModule GetModule(int index)
{
var sourceUrl = index + ".js";
var fileName = Path.Combine(_modulesPath, sourceUrl);
var source = LoadScript(fileName);
return new JavaScriptUnbundleModule(source, sourceUrl);
}
public string GetStartupCode()
{
return LoadScript(_sourcePath);
}
public void Dispose()
{
}
}
class IndexedJavaScriptUnbundle : IJavaScriptUnbundle
{
private const int HeaderSize = 12;
private readonly string _sourcePath;
private Stream _stream;
private byte[] _moduleTable;
private int _baseOffset;
public IndexedJavaScriptUnbundle(string sourcePath)
{
_sourcePath = sourcePath;
}
public JavaScriptUnbundleModule GetModule(int index)
{
var offset = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(_moduleTable, index * 8));
var length = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(_moduleTable, index * 8 + 4));
_stream.Seek(_baseOffset + offset, SeekOrigin.Begin);
var moduleData = new byte[length];
if (_stream.Read(moduleData, 0, (int) length) < length)
{
throw new InvalidOperationException("Reached end of file before end of unbundle module.");
}
var source = Encoding.UTF8.GetString(moduleData);
var sourceUrl = index + ".js";
return new JavaScriptUnbundleModule(source, sourceUrl);
}
public string GetStartupCode()
{
_stream = File.OpenRead(_sourcePath);
var header = new byte[HeaderSize];
if (_stream.Read(header, 0, HeaderSize) < HeaderSize)
{
throw new InvalidOperationException("Reached end of file before end of indexed unbundle header.");
}
var numberOfTableEntries = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(header, 4));
var startupCodeSize = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(header, 8));
var moduleTableSize = numberOfTableEntries * 8 /* bytes per entry */;
_baseOffset = HeaderSize + (int)moduleTableSize;
_moduleTable = new byte[moduleTableSize];
if (_stream.Read(_moduleTable, 0, (int)moduleTableSize) < moduleTableSize)
{
throw new InvalidOperationException("Reached end of file before end of indexed unbundle module table.");
}
var startupCodeBuffer = new byte[startupCodeSize];
if (_stream.Read(startupCodeBuffer, 0, (int)startupCodeSize) < startupCodeSize)
{
throw new InvalidOperationException("Reached end of file before end of startup code.");
}
return Encoding.UTF8.GetString(startupCodeBuffer);
}
public void Dispose()
{
_stream.Dispose();
}
}
private static bool IsUnbundle(string sourcePath)
{
var magicFilePath = Path.Combine(GetUnbundleModulesDirectory(sourcePath), MagicFileName);
if (!File.Exists(magicFilePath))
{
return false;
}
using (var stream = File.OpenRead(magicFilePath))
{
var header = new byte[4];
var read = stream.Read(header, 0, 4);
if (read < 4)
{
return false;
}
var magicHeader = BitConverter.ToUInt32(header, 0);
return InetHelpers.LittleEndianToHost(magicHeader) == MagicFileHeader;
}
}
private static bool IsIndexedUnbundle(string sourcePath)
{
using (var stream = File.OpenRead(sourcePath))
{
var header = new byte[4];
var read = stream.Read(header, 0, 4);
if (read < 4)
{
return false;
}
var magic = InetHelpers.LittleEndianToHost(BitConverter.ToUInt32(header, 0));
return magic == MagicFileHeader;
}
}
private static string GetUnbundleModulesDirectory(string sourcePath)
{
return Path.Combine(Path.GetDirectoryName(sourcePath), "js-modules");
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Globalization;
namespace System.Xml
{
// Specifies formatting options for XmlTextWriter.
internal enum Formatting
{
// No special formatting is done (this is the default).
None,
//This option causes child elements to be indented using the Indentation and IndentChar properties.
// It only indents Element Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-element-content)
// and not Mixed Content (http://www.w3.org/TR/1998/REC-xml-19980210#sec-mixed-content)
// according to the XML 1.0 definitions of these terms.
Indented,
};
// Represents a writer that provides fast non-cached forward-only way of generating XML streams
// containing XML documents that conform to the W3CExtensible Markup Language (XML) 1.0 specification
// and the Namespaces in XML specification.
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
internal class XmlTextWriter : XmlWriter
{
//
// Private types
//
enum NamespaceState
{
Uninitialized,
NotDeclaredButInScope,
DeclaredButNotWrittenOut,
DeclaredAndWrittenOut
}
struct TagInfo
{
internal string name;
internal string prefix;
internal string defaultNs;
internal NamespaceState defaultNsState;
internal XmlSpace xmlSpace;
internal string xmlLang;
internal int prevNsTop;
internal int prefixCount;
internal bool mixed; // whether to pretty print the contents of this element.
internal void Init(int nsTop)
{
name = null;
defaultNs = String.Empty;
defaultNsState = NamespaceState.Uninitialized;
xmlSpace = XmlSpace.None;
xmlLang = null;
prevNsTop = nsTop;
prefixCount = 0;
mixed = false;
}
}
struct Namespace
{
internal string prefix;
internal string ns;
internal bool declared;
internal int prevNsIndex;
internal void Set(string prefix, string ns, bool declared)
{
this.prefix = prefix;
this.ns = ns;
this.declared = declared;
this.prevNsIndex = -1;
}
}
enum SpecialAttr
{
None,
XmlSpace,
XmlLang,
XmlNs
};
// State machine is working through autocomplete
private enum State
{
Start,
Prolog,
PostDTD,
Element,
Attribute,
Content,
AttrOnly,
Epilog,
Error,
Closed,
}
private enum Token
{
PI,
Doctype,
Comment,
CData,
StartElement,
EndElement,
LongEndElement,
StartAttribute,
EndAttribute,
Content,
Base64,
RawData,
Whitespace,
Empty
}
//
// Fields
//
// output
TextWriter textWriter;
XmlTextEncoder xmlEncoder;
Encoding encoding;
// formatting
Formatting formatting;
bool indented; // perf - faster to check a boolean.
int indentation;
char indentChar;
// element stack
TagInfo[] stack;
int top;
// state machine for AutoComplete
State[] stateTable;
State currentState;
Token lastToken;
// Base64 content
XmlTextWriterBase64Encoder base64Encoder;
// misc
char quoteChar;
char curQuoteChar;
bool namespaces;
SpecialAttr specialAttr;
string prefixForXmlNs;
bool flush;
// namespaces
Namespace[] nsStack;
int nsTop;
Dictionary<string, int> nsHashtable;
bool useNsHashtable;
// char types
XmlCharType xmlCharType = XmlCharType.Instance;
//
// Constants and constant tables
//
const int NamespaceStackInitialSize = 8;
#if DEBUG
const int MaxNamespacesWalkCount = 3;
#else
const int MaxNamespacesWalkCount = 16;
#endif
static string[] stateName = {
"Start",
"Prolog",
"PostDTD",
"Element",
"Attribute",
"Content",
"AttrOnly",
"Epilog",
"Error",
"Closed",
};
static string[] tokenName = {
"PI",
"Doctype",
"Comment",
"CData",
"StartElement",
"EndElement",
"LongEndElement",
"StartAttribute",
"EndAttribute",
"Content",
"Base64",
"RawData",
"Whitespace",
"Empty"
};
static readonly State[] stateTableDefault = {
// State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog
//
/* Token.PI */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.Doctype */ State.PostDTD, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error,
/* Token.Comment */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.CData */ State.Content, State.Content, State.Error, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.StartElement */ State.Element, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Element,
/* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartAttribute */ State.AttrOnly, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error,
/* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Epilog, State.Error,
/* Token.Content */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.Base64 */ State.Content, State.Content, State.Error, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.RawData */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
/* Token.Whitespace */ State.Prolog, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Attribute, State.Epilog,
};
static readonly State[] stateTableDocument = {
// State.Start State.Prolog State.PostDTD State.Element State.Attribute State.Content State.AttrOnly State.Epilog
//
/* Token.PI */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.Doctype */ State.Error, State.PostDTD, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error,
/* Token.Comment */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Content, State.Content, State.Error, State.Epilog,
/* Token.CData */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartElement */ State.Error, State.Element, State.Element, State.Element, State.Element, State.Element, State.Error, State.Error,
/* Token.EndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.LongEndElement */ State.Error, State.Error, State.Error, State.Content, State.Content, State.Content, State.Error, State.Error,
/* Token.StartAttribute */ State.Error, State.Error, State.Error, State.Attribute, State.Attribute, State.Error, State.Error, State.Error,
/* Token.EndAttribute */ State.Error, State.Error, State.Error, State.Error, State.Element, State.Error, State.Error, State.Error,
/* Token.Content */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error,
/* Token.Base64 */ State.Error, State.Error, State.Error, State.Content, State.Attribute, State.Content, State.Error, State.Error,
/* Token.RawData */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog,
/* Token.Whitespace */ State.Error, State.Prolog, State.PostDTD, State.Content, State.Attribute, State.Content, State.Error, State.Epilog,
};
//
// Constructors
//
internal XmlTextWriter()
{
namespaces = true;
formatting = Formatting.None;
indentation = 2;
indentChar = ' ';
// namespaces
nsStack = new Namespace[NamespaceStackInitialSize];
nsTop = -1;
// element stack
stack = new TagInfo[10];
top = 0;// 0 is an empty sentential element
stack[top].Init(-1);
quoteChar = '"';
stateTable = stateTableDefault;
currentState = State.Start;
lastToken = Token.Empty;
}
// Creates an instance of the XmlTextWriter class using the specified stream.
public XmlTextWriter(Stream w, Encoding encoding) : this()
{
this.encoding = encoding;
if (encoding != null)
textWriter = new StreamWriter(w, encoding);
else
textWriter = new StreamWriter(w);
xmlEncoder = new XmlTextEncoder(textWriter);
xmlEncoder.QuoteChar = this.quoteChar;
}
// Creates an instance of the XmlTextWriter class using the specified TextWriter.
public XmlTextWriter(TextWriter w) : this()
{
textWriter = w;
encoding = w.Encoding;
xmlEncoder = new XmlTextEncoder(w);
xmlEncoder.QuoteChar = this.quoteChar;
}
//
// XmlTextWriter properties
//
// Gets the XmlTextWriter base stream.
public Stream BaseStream
{
get
{
StreamWriter streamWriter = textWriter as StreamWriter;
return (streamWriter == null ? null : streamWriter.BaseStream);
}
}
// Gets or sets a value indicating whether to do namespace support.
public bool Namespaces
{
get { return this.namespaces; }
set
{
if (this.currentState != State.Start)
throw new InvalidOperationException(SR.Xml_NotInWriteState);
this.namespaces = value;
}
}
// Indicates how the output is formatted.
public Formatting Formatting
{
get { return this.formatting; }
set { this.formatting = value; this.indented = value == Formatting.Indented; }
}
// Gets or sets how many IndentChars to write for each level in the hierarchy when Formatting is set to "Indented".
public int Indentation
{
get { return this.indentation; }
set
{
if (value < 0)
throw new ArgumentException(SR.Xml_InvalidIndentation);
this.indentation = value;
}
}
// Gets or sets which character to use for indenting when Formatting is set to "Indented".
public char IndentChar
{
get { return this.indentChar; }
set { this.indentChar = value; }
}
// Gets or sets which character to use to quote attribute values.
public char QuoteChar
{
get { return this.quoteChar; }
set
{
if (value != '"' && value != '\'')
{
throw new ArgumentException(SR.Xml_InvalidQuote);
}
this.quoteChar = value;
this.xmlEncoder.QuoteChar = value;
}
}
//
// XmlWriter implementation
//
// Writes out the XML declaration with the version "1.0".
public override void WriteStartDocument()
{
StartDocument(-1);
}
// Writes out the XML declaration with the version "1.0" and the standalone attribute.
public override void WriteStartDocument(bool standalone)
{
StartDocument(standalone ? 1 : 0);
}
// Closes any open elements or attributes and puts the writer back in the Start state.
public override void WriteEndDocument()
{
try
{
AutoCompleteAll();
if (this.currentState != State.Epilog)
{
if (this.currentState == State.Closed)
{
throw new ArgumentException(SR.Xml_ClosedOrError);
}
else
{
throw new ArgumentException(SR.Xml_NoRoot);
}
}
this.stateTable = stateTableDefault;
this.currentState = State.Start;
this.lastToken = Token.Empty;
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
public override void WriteDocType(string name, string pubid, string sysid, string subset)
{
try
{
ValidateName(name, false);
AutoComplete(Token.Doctype);
textWriter.Write("<!DOCTYPE ");
textWriter.Write(name);
if (pubid != null)
{
textWriter.Write(" PUBLIC ");
textWriter.Write(quoteChar);
textWriter.Write(pubid);
textWriter.Write(quoteChar);
textWriter.Write(' ');
textWriter.Write(quoteChar);
textWriter.Write(sysid);
textWriter.Write(quoteChar);
}
else if (sysid != null)
{
textWriter.Write(" SYSTEM ");
textWriter.Write(quoteChar);
textWriter.Write(sysid);
textWriter.Write(quoteChar);
}
if (subset != null)
{
textWriter.Write('[');
textWriter.Write(subset);
textWriter.Write(']');
}
textWriter.Write('>');
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
public override void WriteStartElement(string prefix, string localName, string ns)
{
try
{
AutoComplete(Token.StartElement);
PushStack();
textWriter.Write('<');
if (this.namespaces)
{
// Propagate default namespace and mix model down the stack.
stack[top].defaultNs = stack[top - 1].defaultNs;
if (stack[top - 1].defaultNsState != NamespaceState.Uninitialized)
stack[top].defaultNsState = NamespaceState.NotDeclaredButInScope;
stack[top].mixed = stack[top - 1].mixed;
if (ns == null)
{
// use defined prefix
if (!string.IsNullOrEmpty(prefix) && (LookupNamespace(prefix) == -1))
{
throw new ArgumentException(SR.Xml_UndefPrefix);
}
}
else
{
if (prefix == null)
{
string definedPrefix = FindPrefix(ns);
if (definedPrefix != null)
{
prefix = definedPrefix;
}
else
{
PushNamespace(null, ns, false); // new default
}
}
else if (prefix.Length == 0)
{
PushNamespace(null, ns, false); // new default
}
else
{
if (ns.Length == 0)
{
prefix = null;
}
VerifyPrefixXml(prefix, ns);
PushNamespace(prefix, ns, false); // define
}
}
stack[top].prefix = null;
if (!string.IsNullOrEmpty(prefix))
{
stack[top].prefix = prefix;
textWriter.Write(prefix);
textWriter.Write(':');
}
}
else
{
if (!string.IsNullOrEmpty(ns) || !string.IsNullOrEmpty(prefix))
{
throw new ArgumentException(SR.Xml_NoNamespaces);
}
}
stack[top].name = localName;
textWriter.Write(localName);
}
catch
{
currentState = State.Error;
throw;
}
}
// Closes one element and pops the corresponding namespace scope.
public override void WriteEndElement()
{
InternalWriteEndElement(false);
}
// Closes one element and pops the corresponding namespace scope.
public override void WriteFullEndElement()
{
InternalWriteEndElement(true);
}
// Writes the start of an attribute.
public override void WriteStartAttribute(string prefix, string localName, string ns)
{
try
{
AutoComplete(Token.StartAttribute);
this.specialAttr = SpecialAttr.None;
if (this.namespaces)
{
if (prefix != null && prefix.Length == 0)
{
prefix = null;
}
if (ns == XmlConst.ReservedNsXmlNs && prefix == null && localName != "xmlns")
{
prefix = "xmlns";
}
if (prefix == "xml")
{
if (localName == "lang")
{
this.specialAttr = SpecialAttr.XmlLang;
}
else if (localName == "space")
{
this.specialAttr = SpecialAttr.XmlSpace;
}
}
else if (prefix == "xmlns")
{
if (XmlConst.ReservedNsXmlNs != ns && ns != null)
{
throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs);
}
if (string.IsNullOrEmpty(localName))
{
localName = prefix;
prefix = null;
this.prefixForXmlNs = null;
}
else
{
this.prefixForXmlNs = localName;
}
this.specialAttr = SpecialAttr.XmlNs;
}
else if (prefix == null && localName == "xmlns")
{
if (XmlConst.ReservedNsXmlNs != ns && ns != null)
{
// add the below line back in when DOM is fixed
throw new ArgumentException(SR.Xml_XmlnsBelongsToReservedNs);
}
this.specialAttr = SpecialAttr.XmlNs;
this.prefixForXmlNs = null;
}
else
{
if (ns == null)
{
// use defined prefix
if (prefix != null && (LookupNamespace(prefix) == -1))
{
throw new ArgumentException(SR.Xml_UndefPrefix);
}
}
else if (ns.Length == 0)
{
// empty namespace require null prefix
prefix = string.Empty;
}
else
{ // ns.Length != 0
VerifyPrefixXml(prefix, ns);
if (prefix != null && LookupNamespaceInCurrentScope(prefix) != -1)
{
prefix = null;
}
// Now verify prefix validity
string definedPrefix = FindPrefix(ns);
if (definedPrefix != null && (prefix == null || prefix == definedPrefix))
{
prefix = definedPrefix;
}
else
{
if (prefix == null)
{
prefix = GeneratePrefix(); // need a prefix if
}
PushNamespace(prefix, ns, false);
}
}
}
if (!string.IsNullOrEmpty(prefix))
{
textWriter.Write(prefix);
textWriter.Write(':');
}
}
else
{
if (!string.IsNullOrEmpty(ns) || !string.IsNullOrEmpty(prefix))
{
throw new ArgumentException(SR.Xml_NoNamespaces);
}
if (localName == "xml:lang")
{
this.specialAttr = SpecialAttr.XmlLang;
}
else if (localName == "xml:space")
{
this.specialAttr = SpecialAttr.XmlSpace;
}
}
xmlEncoder.StartAttribute(this.specialAttr != SpecialAttr.None);
textWriter.Write(localName);
textWriter.Write('=');
if (this.curQuoteChar != this.quoteChar)
{
this.curQuoteChar = this.quoteChar;
xmlEncoder.QuoteChar = this.quoteChar;
}
textWriter.Write(this.curQuoteChar);
}
catch
{
currentState = State.Error;
throw;
}
}
// Closes the attribute opened by WriteStartAttribute.
public override void WriteEndAttribute()
{
try
{
AutoComplete(Token.EndAttribute);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out a <![CDATA[...]]> block containing the specified text.
public override void WriteCData(string text)
{
try
{
AutoComplete(Token.CData);
if (null != text && text.IndexOf("]]>", StringComparison.Ordinal) >= 0)
{
throw new ArgumentException(SR.Xml_InvalidCDataChars);
}
textWriter.Write("<![CDATA[");
if (null != text)
{
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("]]>");
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out a comment <!--...--> containing the specified text.
public override void WriteComment(string text)
{
try
{
if (null != text && (text.IndexOf("--", StringComparison.Ordinal) >= 0 || (text.Length != 0 && text[text.Length - 1] == '-')))
{
throw new ArgumentException(SR.Xml_InvalidCommentChars);
}
AutoComplete(Token.Comment);
textWriter.Write("<!--");
if (null != text)
{
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("-->");
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
public override void WriteProcessingInstruction(string name, string text)
{
try
{
if (null != text && text.IndexOf("?>", StringComparison.Ordinal) >= 0)
{
throw new ArgumentException(SR.Xml_InvalidPiChars);
}
if (String.Equals(name, "xml", StringComparison.OrdinalIgnoreCase) && this.stateTable == stateTableDocument)
{
throw new ArgumentException(SR.Xml_DupXmlDecl);
}
AutoComplete(Token.PI);
InternalWriteProcessingInstruction(name, text);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out an entity reference as follows: "&"+name+";".
public override void WriteEntityRef(string name)
{
try
{
ValidateName(name, false);
AutoComplete(Token.Content);
xmlEncoder.WriteEntityRef(name);
}
catch
{
currentState = State.Error;
throw;
}
}
// Forces the generation of a character entity for the specified Unicode character value.
public override void WriteCharEntity(char ch)
{
try
{
AutoComplete(Token.Content);
xmlEncoder.WriteCharEntity(ch);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the given whitespace.
public override void WriteWhitespace(string ws)
{
try
{
if (null == ws)
{
ws = String.Empty;
}
if (!xmlCharType.IsOnlyWhitespace(ws))
{
throw new ArgumentException(SR.Xml_NonWhitespace);
}
AutoComplete(Token.Whitespace);
xmlEncoder.Write(ws);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified text content.
public override void WriteString(string text)
{
try
{
if (null != text && text.Length != 0)
{
AutoComplete(Token.Content);
xmlEncoder.Write(text);
}
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified surrogate pair as a character entity.
public override void WriteSurrogateCharEntity(char lowChar, char highChar)
{
try
{
AutoComplete(Token.Content);
xmlEncoder.WriteSurrogateCharEntity(lowChar, highChar);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified text content.
public override void WriteChars(Char[] buffer, int index, int count)
{
try
{
AutoComplete(Token.Content);
xmlEncoder.Write(buffer, index, count);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes raw markup from the specified character buffer.
public override void WriteRaw(Char[] buffer, int index, int count)
{
try
{
AutoComplete(Token.RawData);
xmlEncoder.WriteRaw(buffer, index, count);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes raw markup from the specified character string.
public override void WriteRaw(String data)
{
try
{
AutoComplete(Token.RawData);
xmlEncoder.WriteRawWithSurrogateChecking(data);
}
catch
{
currentState = State.Error;
throw;
}
}
// Encodes the specified binary bytes as base64 and writes out the resulting text.
public override void WriteBase64(byte[] buffer, int index, int count)
{
try
{
if (!this.flush)
{
AutoComplete(Token.Base64);
}
this.flush = true;
// No need for us to explicitly validate the args. The StreamWriter will do
// it for us.
if (null == this.base64Encoder)
{
this.base64Encoder = new XmlTextWriterBase64Encoder(xmlEncoder);
}
// Encode will call WriteRaw to write out the encoded characters
this.base64Encoder.Encode(buffer, index, count);
}
catch
{
currentState = State.Error;
throw;
}
}
// Encodes the specified binary bytes as binhex and writes out the resulting text.
public override void WriteBinHex(byte[] buffer, int index, int count)
{
try
{
AutoComplete(Token.Content);
BinHexEncoder.Encode(buffer, index, count, this);
}
catch
{
currentState = State.Error;
throw;
}
}
// Returns the state of the XmlWriter.
public override WriteState WriteState
{
get
{
switch (this.currentState)
{
case State.Start:
return WriteState.Start;
case State.Prolog:
case State.PostDTD:
return WriteState.Prolog;
case State.Element:
return WriteState.Element;
case State.Attribute:
case State.AttrOnly:
return WriteState.Attribute;
case State.Content:
case State.Epilog:
return WriteState.Content;
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
default:
Debug.Fail("Unmatched state in switch");
return WriteState.Error;
}
}
}
// Disposes the XmlWriter and the underlying stream/TextWriter.
protected override void Dispose(bool disposing)
{
if (disposing && this.currentState != State.Closed)
{
try
{
AutoCompleteAll();
}
catch
{ // never fail
}
finally
{
this.currentState = State.Closed;
textWriter.Dispose();
}
}
base.Dispose(disposing);
}
// Flushes whatever is in the buffer to the underlying stream/TextWriter and flushes the underlying stream/TextWriter.
public override void Flush()
{
textWriter.Flush();
}
// Writes out the specified name, ensuring it is a valid Name according to the XML specification
// (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name
public override void WriteName(string name)
{
try
{
AutoComplete(Token.Content);
InternalWriteName(name, false);
}
catch
{
currentState = State.Error;
throw;
}
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
public override void WriteQualifiedName(string localName, string ns)
{
try
{
AutoComplete(Token.Content);
if (this.namespaces)
{
if (!string.IsNullOrEmpty(ns) && ns != stack[top].defaultNs)
{
string prefix = FindPrefix(ns);
if (prefix == null)
{
if (this.currentState != State.Attribute)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
prefix = GeneratePrefix(); // need a prefix if
PushNamespace(prefix, ns, false);
}
if (prefix.Length != 0)
{
InternalWriteName(prefix, true);
textWriter.Write(':');
}
}
}
else if (!string.IsNullOrEmpty(ns))
{
throw new ArgumentException(SR.Xml_NoNamespaces);
}
InternalWriteName(localName, true);
}
catch
{
currentState = State.Error;
throw;
}
}
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
public override string LookupPrefix(string ns)
{
if (string.IsNullOrEmpty(ns))
{
throw new ArgumentException(SR.Xml_EmptyName);
}
string s = FindPrefix(ns);
if (s == null && ns == stack[top].defaultNs)
{
s = string.Empty;
}
return s;
}
// Gets an XmlSpace representing the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
for (int i = top; i > 0; i--)
{
XmlSpace xs = stack[i].xmlSpace;
if (xs != XmlSpace.None)
return xs;
}
return XmlSpace.None;
}
}
// Gets the current xml:lang scope.
public override string XmlLang
{
get
{
for (int i = top; i > 0; i--)
{
String xlang = stack[i].xmlLang;
if (xlang != null)
return xlang;
}
return null;
}
}
// Writes out the specified name, ensuring it is a valid NmToken
// according to the XML specification (http://www.w3.org/TR/1998/REC-xml-19980210#NT-Name).
public override void WriteNmToken(string name)
{
try
{
AutoComplete(Token.Content);
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.Xml_EmptyName);
}
if (!ValidateNames.IsNmtokenNoNamespaces(name))
{
throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name));
}
textWriter.Write(name);
}
catch
{
currentState = State.Error;
throw;
}
}
//
// Private implementation methods
//
void StartDocument(int standalone)
{
try
{
if (this.currentState != State.Start)
{
throw new InvalidOperationException(SR.Xml_NotTheFirst);
}
this.stateTable = stateTableDocument;
this.currentState = State.Prolog;
StringBuilder bufBld = new StringBuilder(128);
bufBld.Append("version=");
bufBld.Append(quoteChar);
bufBld.Append("1.0");
bufBld.Append(quoteChar);
if (this.encoding != null)
{
bufBld.Append(" encoding=");
bufBld.Append(quoteChar);
bufBld.Append(this.encoding.WebName);
bufBld.Append(quoteChar);
}
if (standalone >= 0)
{
bufBld.Append(" standalone=");
bufBld.Append(quoteChar);
bufBld.Append(standalone == 0 ? "no" : "yes");
bufBld.Append(quoteChar);
}
InternalWriteProcessingInstruction("xml", bufBld.ToString());
}
catch
{
currentState = State.Error;
throw;
}
}
void AutoComplete(Token token)
{
if (this.currentState == State.Closed)
{
throw new InvalidOperationException(SR.Xml_Closed);
}
else if (this.currentState == State.Error)
{
throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], stateName[(int)State.Error]));
}
State newState = this.stateTable[(int)token * 8 + (int)this.currentState];
if (newState == State.Error)
{
throw new InvalidOperationException(SR.Format(SR.Xml_WrongToken, tokenName[(int)token], stateName[(int)this.currentState]));
}
switch (token)
{
case Token.Doctype:
if (this.indented && this.currentState != State.Start)
{
Indent(false);
}
break;
case Token.StartElement:
case Token.Comment:
case Token.PI:
case Token.CData:
if (this.currentState == State.Attribute)
{
WriteEndAttributeQuote();
WriteEndStartTag(false);
}
else if (this.currentState == State.Element)
{
WriteEndStartTag(false);
}
if (token == Token.CData)
{
stack[top].mixed = true;
}
else if (this.indented && this.currentState != State.Start)
{
Indent(false);
}
break;
case Token.EndElement:
case Token.LongEndElement:
if (this.flush)
{
FlushEncoders();
}
if (this.currentState == State.Attribute)
{
WriteEndAttributeQuote();
}
if (this.currentState == State.Content)
{
token = Token.LongEndElement;
}
else
{
WriteEndStartTag(token == Token.EndElement);
}
if (stateTableDocument == this.stateTable && top == 1)
{
newState = State.Epilog;
}
break;
case Token.StartAttribute:
if (this.flush)
{
FlushEncoders();
}
if (this.currentState == State.Attribute)
{
WriteEndAttributeQuote();
textWriter.Write(' ');
}
else if (this.currentState == State.Element)
{
textWriter.Write(' ');
}
break;
case Token.EndAttribute:
if (this.flush)
{
FlushEncoders();
}
WriteEndAttributeQuote();
break;
case Token.Whitespace:
case Token.Content:
case Token.RawData:
case Token.Base64:
if (token != Token.Base64 && this.flush)
{
FlushEncoders();
}
if (this.currentState == State.Element && this.lastToken != Token.Content)
{
WriteEndStartTag(false);
}
if (newState == State.Content)
{
stack[top].mixed = true;
}
break;
default:
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
this.currentState = newState;
this.lastToken = token;
}
void AutoCompleteAll()
{
if (this.flush)
{
FlushEncoders();
}
while (top > 0)
{
WriteEndElement();
}
}
void InternalWriteEndElement(bool longFormat)
{
try
{
if (top <= 0)
{
throw new InvalidOperationException(SR.Xml_NoStartTag);
}
// if we are in the element, we need to close it.
AutoComplete(longFormat ? Token.LongEndElement : Token.EndElement);
if (this.lastToken == Token.LongEndElement)
{
if (this.indented)
{
Indent(true);
}
textWriter.Write('<');
textWriter.Write('/');
if (this.namespaces && stack[top].prefix != null)
{
textWriter.Write(stack[top].prefix);
textWriter.Write(':');
}
textWriter.Write(stack[top].name);
textWriter.Write('>');
}
// pop namespaces
int prevNsTop = stack[top].prevNsTop;
if (useNsHashtable && prevNsTop < nsTop)
{
PopNamespaces(prevNsTop + 1, nsTop);
}
nsTop = prevNsTop;
top--;
}
catch
{
currentState = State.Error;
throw;
}
}
void WriteEndStartTag(bool empty)
{
xmlEncoder.StartAttribute(false);
for (int i = nsTop; i > stack[top].prevNsTop; i--)
{
if (!nsStack[i].declared)
{
textWriter.Write(" xmlns");
textWriter.Write(':');
textWriter.Write(nsStack[i].prefix);
textWriter.Write('=');
textWriter.Write(this.quoteChar);
xmlEncoder.Write(nsStack[i].ns);
textWriter.Write(this.quoteChar);
}
}
// Default
if ((stack[top].defaultNs != stack[top - 1].defaultNs) &&
(stack[top].defaultNsState == NamespaceState.DeclaredButNotWrittenOut))
{
textWriter.Write(" xmlns");
textWriter.Write('=');
textWriter.Write(this.quoteChar);
xmlEncoder.Write(stack[top].defaultNs);
textWriter.Write(this.quoteChar);
stack[top].defaultNsState = NamespaceState.DeclaredAndWrittenOut;
}
xmlEncoder.EndAttribute();
if (empty)
{
textWriter.Write(" /");
}
textWriter.Write('>');
}
void WriteEndAttributeQuote()
{
if (this.specialAttr != SpecialAttr.None)
{
// Ok, now to handle xmlspace, etc.
HandleSpecialAttribute();
}
xmlEncoder.EndAttribute();
textWriter.Write(this.curQuoteChar);
}
void Indent(bool beforeEndElement)
{
// pretty printing.
if (top == 0)
{
textWriter.WriteLine();
}
else if (!stack[top].mixed)
{
textWriter.WriteLine();
int i = beforeEndElement ? top - 1 : top;
for (i *= this.indentation; i > 0; i--)
{
textWriter.Write(this.indentChar);
}
}
}
// pushes new namespace scope, and returns generated prefix, if one
// was needed to resolve conflicts.
void PushNamespace(string prefix, string ns, bool declared)
{
if (XmlConst.ReservedNsXmlNs == ns)
{
throw new ArgumentException(SR.Xml_CanNotBindToReservedNamespace);
}
if (prefix == null)
{
switch (stack[top].defaultNsState)
{
case NamespaceState.DeclaredButNotWrittenOut:
Debug.Assert(declared == true, "Unexpected situation!!");
// the first namespace that the user gave us is what we
// like to keep.
break;
case NamespaceState.Uninitialized:
case NamespaceState.NotDeclaredButInScope:
// we now got a brand new namespace that we need to remember
stack[top].defaultNs = ns;
break;
default:
Debug.Fail("Should have never come here");
return;
}
stack[top].defaultNsState = (declared ? NamespaceState.DeclaredAndWrittenOut : NamespaceState.DeclaredButNotWrittenOut);
}
else
{
if (prefix.Length != 0 && ns.Length == 0)
{
throw new ArgumentException(SR.Xml_PrefixForEmptyNs);
}
int existingNsIndex = LookupNamespace(prefix);
if (existingNsIndex != -1 && nsStack[existingNsIndex].ns == ns)
{
// it is already in scope.
if (declared)
{
nsStack[existingNsIndex].declared = true;
}
}
else
{
// see if prefix conflicts for the current element
if (declared)
{
if (existingNsIndex != -1 && existingNsIndex > stack[top].prevNsTop)
{
nsStack[existingNsIndex].declared = true; // old one is silenced now
}
}
AddNamespace(prefix, ns, declared);
}
}
}
void AddNamespace(string prefix, string ns, bool declared)
{
int nsIndex = ++nsTop;
if (nsIndex == nsStack.Length)
{
Namespace[] newStack = new Namespace[nsIndex * 2];
Array.Copy(nsStack, 0, newStack, 0, nsIndex);
nsStack = newStack;
}
nsStack[nsIndex].Set(prefix, ns, declared);
if (useNsHashtable)
{
AddToNamespaceHashtable(nsIndex);
}
else if (nsIndex == MaxNamespacesWalkCount)
{
// add all
nsHashtable = new Dictionary<string, int>(new SecureStringHasher());
for (int i = 0; i <= nsIndex; i++)
{
AddToNamespaceHashtable(i);
}
useNsHashtable = true;
}
}
void AddToNamespaceHashtable(int namespaceIndex)
{
string prefix = nsStack[namespaceIndex].prefix;
int existingNsIndex;
if (nsHashtable.TryGetValue(prefix, out existingNsIndex))
{
nsStack[namespaceIndex].prevNsIndex = existingNsIndex;
}
nsHashtable[prefix] = namespaceIndex;
}
private void PopNamespaces(int indexFrom, int indexTo)
{
Debug.Assert(useNsHashtable);
for (int i = indexTo; i >= indexFrom; i--)
{
Debug.Assert(nsHashtable.ContainsKey(nsStack[i].prefix));
if (nsStack[i].prevNsIndex == -1)
{
nsHashtable.Remove(nsStack[i].prefix);
}
else
{
nsHashtable[nsStack[i].prefix] = nsStack[i].prevNsIndex;
}
}
}
string GeneratePrefix()
{
int temp = stack[top].prefixCount++ + 1;
return "d" + top.ToString("d", CultureInfo.InvariantCulture)
+ "p" + temp.ToString("d", CultureInfo.InvariantCulture);
}
void InternalWriteProcessingInstruction(string name, string text)
{
textWriter.Write("<?");
ValidateName(name, false);
textWriter.Write(name);
textWriter.Write(' ');
if (null != text)
{
xmlEncoder.WriteRawWithSurrogateChecking(text);
}
textWriter.Write("?>");
}
int LookupNamespace(string prefix)
{
if (useNsHashtable)
{
int nsIndex;
if (nsHashtable.TryGetValue(prefix, out nsIndex))
{
return nsIndex;
}
}
else
{
for (int i = nsTop; i >= 0; i--)
{
if (nsStack[i].prefix == prefix)
{
return i;
}
}
}
return -1;
}
int LookupNamespaceInCurrentScope(string prefix)
{
if (useNsHashtable)
{
int nsIndex;
if (nsHashtable.TryGetValue(prefix, out nsIndex))
{
if (nsIndex > stack[top].prevNsTop)
{
return nsIndex;
}
}
}
else
{
for (int i = nsTop; i > stack[top].prevNsTop; i--)
{
if (nsStack[i].prefix == prefix)
{
return i;
}
}
}
return -1;
}
string FindPrefix(string ns)
{
for (int i = nsTop; i >= 0; i--)
{
if (nsStack[i].ns == ns)
{
if (LookupNamespace(nsStack[i].prefix) == i)
{
return nsStack[i].prefix;
}
}
}
return null;
}
// There are three kind of strings we write out - Name, LocalName and Prefix.
// Both LocalName and Prefix can be represented with NCName == false and Name
// can be represented as NCName == true
void InternalWriteName(string name, bool isNCName)
{
ValidateName(name, isNCName);
textWriter.Write(name);
}
// This method is used for validation of the DOCTYPE, processing instruction and entity names plus names
// written out by the user via WriteName and WriteQualifiedName.
// Unfortunately the names of elements and attributes are not validated by the XmlTextWriter.
// Also this method does not check whether the character after ':' is a valid start name character. It accepts
// all valid name characters at that position. This can't be changed because of backwards compatibility.
private unsafe void ValidateName(string name, bool isNCName)
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(SR.Xml_EmptyName);
}
int nameLength = name.Length;
// Namespaces supported
if (namespaces)
{
// We can't use ValidateNames.ParseQName here because of backwards compatibility bug we need to preserve.
// The bug is that the character after ':' is validated only as a NCName characters instead of NCStartName.
int colonPosition = -1;
// Parse NCName (may be prefix, may be local name)
int position = ValidateNames.ParseNCName(name);
Continue:
if (position == nameLength)
{
return;
}
// we have prefix:localName
if (name[position] == ':')
{
if (!isNCName)
{
// first colon in qname
if (colonPosition == -1)
{
// make sure it is not the first or last characters
if (position > 0 && position + 1 < nameLength)
{
colonPosition = position;
// Because of the back-compat bug (described above) parse the rest as Nmtoken
position++;
position += ValidateNames.ParseNmtoken(name, position);
goto Continue;
}
}
}
}
}
// Namespaces not supported
else
{
if (ValidateNames.IsNameNoNamespaces(name))
{
return;
}
}
throw new ArgumentException(SR.Format(SR.Xml_InvalidNameChars, name));
}
void HandleSpecialAttribute()
{
string value = xmlEncoder.AttributeValue;
switch (this.specialAttr)
{
case SpecialAttr.XmlLang:
stack[top].xmlLang = value;
break;
case SpecialAttr.XmlSpace:
// validate XmlSpace attribute
value = XmlConvertEx.TrimString(value);
if (value == "default")
{
stack[top].xmlSpace = XmlSpace.Default;
}
else if (value == "preserve")
{
stack[top].xmlSpace = XmlSpace.Preserve;
}
else
{
throw new ArgumentException(SR.Format(SR.Xml_InvalidXmlSpace, value));
}
break;
case SpecialAttr.XmlNs:
VerifyPrefixXml(this.prefixForXmlNs, value);
PushNamespace(this.prefixForXmlNs, value, true);
break;
}
}
void VerifyPrefixXml(string prefix, string ns)
{
if (prefix != null && prefix.Length == 3)
{
if (
(prefix[0] == 'x' || prefix[0] == 'X') &&
(prefix[1] == 'm' || prefix[1] == 'M') &&
(prefix[2] == 'l' || prefix[2] == 'L')
)
{
if (XmlConst.ReservedNsXml != ns)
{
throw new ArgumentException(SR.Xml_InvalidPrefix);
}
}
}
}
void PushStack()
{
if (top == stack.Length - 1)
{
TagInfo[] na = new TagInfo[stack.Length + 10];
if (top > 0) Array.Copy(stack, 0, na, 0, top + 1);
stack = na;
}
top++; // Move up stack
stack[top].Init(nsTop);
}
void FlushEncoders()
{
if (null != this.base64Encoder)
{
// The Flush will call WriteRaw to write out the rest of the encoded characters
this.base64Encoder.Flush();
}
this.flush = false;
}
}
}
| |
using System;
using System.Collections.Generic;
using EasyPost.Utilities;
namespace EasyPost.Tests.Net
{
public static class Fixture
{
// We keep the page_size of retrieving `all` records small so cassettes stay small
public const int PageSize = 5;
// This is the carrier account ID for the default USPS account that comes by default. All tests should use this carrier account
public const string UspsCarrierAccountId = "ca_7642d249fdcf47bcb5da9ea34c96dfcf";
public const string ChildUserId = "user_608a91d0487e419bb465e5acbc999056";
public const string Usps = "USPS";
public const string UspsService = "First";
public const string NextDayService = "NextDay";
// If ever these need to change due to re-recording cassettes, simply increment this date by 1
public const string ReportStartDate = "2022-02-01";
// If ever these need to change due to re-recording cassettes, simply increment this date by 1
public const string ReportEndDate = "2022-02-03";
public static string RandomUrl => $"https://{Guid.NewGuid().ToString().Substring(0, 8)}.com";
public static Dictionary<string, object> BasicAddress
{
get
{
return new Dictionary<string, object>
{
{
"name", "Jack Sparrow"
},
{
"company", "EasyPost"
},
{
"street1", "388 Townsend St"
},
{
"street2", "Apt 20"
},
{
"city", "San Francisco"
},
{
"state", "CA"
},
{
"zip", "94107"
},
{
"country", "US"
},
{
"phone", "5555555555"
},
};
}
}
public static Dictionary<string, object> IncorrectAddressToVerify
{
get
{
return new Dictionary<string, object>
{
{
"verify", new List<bool>
{
true
}
},
{
"street1", "417 montgomery streat"
},
{
"street2", "FL 5"
},
{
"city", "San Francisco"
},
{
"state", "CA"
},
{
"zip", "94104"
},
{
"country", "US"
},
{
"company", "EasyPost"
},
{
"phone", "415-123-4567"
}
};
}
}
public static Dictionary<string, object> PickupAddress
{
get
{
return new Dictionary<string, object>
{
{
"name", "Dr. Steve Brule"
},
{
"street1", "179 N Harbor Dr"
},
{
"city", "Redondo Beach"
},
{
"state", "CA"
},
{
"zip", "90277"
},
{
"country", "US"
},
{
"phone", "3331114444"
}
};
}
}
public static Dictionary<string, object> BasicParcel
{
get
{
return new Dictionary<string, object>
{
{
"length", "10"
},
{
"width", "8"
},
{
"height", "4"
},
{
"weight", "15.4"
}
};
}
}
public static Dictionary<string, object> BasicCustomsItem
{
get
{
return new Dictionary<string, object>
{
{
"description", "Sweet shirts"
},
{
"quantity", 2
},
{
"weight", 11
},
{
"value", 23.00
},
{
"hs_tariff_number", 654321
},
{
"origin_country", "US"
}
};
}
}
public static Dictionary<string, object> BasicCustomsInfo
{
get
{
return new Dictionary<string, object>
{
{
"eel_pfc", "NOEEI 30.37(a)"
},
{
"customs_certify", true
},
{
"customs_signer", "Dr. Steve Brule"
},
{
"contents_type", "merchandise"
},
{
"contents_explanation", ""
},
{
"restriction_type", "none"
},
{
"non_delivery_option", "return"
},
{
"customs_items", new List<object>
{
BasicCustomsItem
}
}
};
}
}
public static Dictionary<string, object> BasicCarrierAccount
{
get
{
return new Dictionary<string, object>
{
{
"type", "UpsAccount"
},
{
"credentials", new Dictionary<string, object>
{
{
"account_number", "A1A1A1"
},
{
"user_id", "USERID"
},
{
"password", "PASSWORD"
},
{
"access_license_number", "ALN"
}
}
}
};
}
}
public static Dictionary<string, object> TaxIdentifier
{
get
{
return new Dictionary<string, object>
{
{
"entity", "SENDER"
},
{
"tax_id_type", "IOSS"
},
{
"tax_id", "12345"
},
{
"issuing_country", "GB"
}
};
}
}
public static Dictionary<string, object> BasicShipment
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"parcel", BasicParcel
}
};
}
}
public static Dictionary<string, object> FullShipment
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"parcel", BasicParcel
},
{
"customs_info", BasicCustomsInfo
},
{
"options", new Dictionary<string, object>
{
{
"label_format", "PNG" // Must be PNG so we can convert to ZPL later
},
{
"invoice_number", "123"
}
}
},
{
"reference", "123"
}
};
}
}
public static Dictionary<string, object> OneCallBuyShipment
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"parcel", BasicParcel
},
{
"service", UspsService
},
{
"carrier_accounts", new List<string>
{
UspsCarrierAccountId
}
},
{
"carrier", Usps
}
};
}
}
public static Dictionary<string, object> BasicInsurance
{
get
{
Shipment shipment = Shipment.Create(OneCallBuyShipment);
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"tracking_code", shipment.tracking_code
},
{
"carrier", Usps
},
{
"amount", 100
}
};
}
}
// This fixture will require you to add a `shipment` key with a Shipment object from a test.
// If you need to re-record cassettes, simply iterate the dates below and ensure they're one day in the future,
// USPS only does "next-day" pickups including Saturday but not Sunday or Holidays.
public static Dictionary<string, object> BasicPickup
{
get
{
return new Dictionary<string, object>
{
{
"address", BasicAddress
},
{
"min_datetime", (DateTime.Today.Date + TimeSpan.FromDays(1)).ToString("yyyy-MM-dd")
},
{
"max_datetime", (DateTime.Today.Date + TimeSpan.FromDays(2)).ToString("yyyy-MM-dd")
},
{
"instructions", "Pickup at front door"
}
};
}
}
public static Dictionary<string, object> BasicOrder
{
get
{
return new Dictionary<string, object>
{
{
"to_address", BasicAddress
},
{
"from_address", BasicAddress
},
{
"shipments", new List<Dictionary<string, object>>
{
BasicShipment
}
}
};
}
}
public static string Event
{
get
{
Dictionary<string, object> data = new Dictionary<string, object>
{
{
"mode", "production"
},
{
"description", "batch.created"
},
{
"previous_attributes", new Dictionary<string, object>
{
{
"state", "purchasing"
}
}
},
{
"pending_urls", new List<string>
{
"example.com/easypost-webhook"
}
},
{
"completed_urls", new List<string>()
},
{
"created_at", "2015-12-03T19:09:19Z"
},
{
"updated_at", "2015-12-03T19:09:19Z"
},
{
"result", new Dictionary<string, object>
{
{
"id", "batch_..."
},
{
"object", "Batch"
},
{
"mode", "production"
},
{
"state", "purchased"
},
{
"num_shipments", 1
},
{
"reference", null
},
{
"created_at", "2015-12-03T19:09:19Z"
},
{
"updated_at", "2015-12-03T19:09:19Z"
},
{
"scan_form", null
},
{
"shipments", new Dictionary<string, object>
{
{
"batch_status", "postage_purchased"
},
{
"batch_message", null
},
{
"id", "shp_123..."
}
}
},
{
"status", new Dictionary<string, object>
{
{
"created", 0
},
{
"queued_for_purchase", 0
},
{
"creation_failed", 0
},
{
"postage_purchased", 1
},
{
"postage_purchase_failed", 0
}
}
},
{
"pickup", null
},
{
"label_url", null
}
}
},
{
"id", "evt_..."
},
{
"object", "Event"
}
};
return JsonSerialization.ConvertObjectToJson(data);
}
}
}
}
| |
using System.Globalization;
using Microsoft.Build.Framework;
namespace GitVersion.MsBuild.Tests.Helpers;
/// <summary>
/// Offers a default string format for Error and Warning events
/// </summary>
internal static class EventArgsFormatting
{
/// <summary>
/// Format the error event message and all the other event data into
/// a single string.
/// </summary>
/// <param name="e">Error to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildErrorEventArgs e) =>
// "error" should not be localized
FormatEventMessage("error", e.Subcategory, e.Message,
e.Code, e.File, null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
/// <summary>
/// Format the error event message and all the other event data into
/// a single string.
/// </summary>
/// <param name="e">Error to format</param>
/// <param name="showProjectFile"><code>true</code> to show the project file which issued the event, otherwise <code>false</code>.</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildErrorEventArgs e, bool showProjectFile) =>
// "error" should not be localized
FormatEventMessage("error", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
/// <summary>
/// Format the warning message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Warning to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildWarningEventArgs e) =>
// "warning" should not be localized
FormatEventMessage("warning", e.Subcategory, e.Message,
e.Code, e.File, null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
/// <summary>
/// Format the warning message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Warning to format</param>
/// <param name="showProjectFile"><code>true</code> to show the project file which issued the event, otherwise <code>false</code>.</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildWarningEventArgs e, bool showProjectFile) =>
// "warning" should not be localized
FormatEventMessage("warning", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber,
e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
/// <summary>
/// Format the message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Message to format</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage(BuildMessageEventArgs e) => FormatEventMessage(e, false);
/// <summary>
/// Format the message and all the other event data into a
/// single string.
/// </summary>
/// <param name="e">Message to format</param>
/// <param name="showProjectFile">Show project file or not</param>
/// <returns>The formatted message string.</returns>
private static string FormatEventMessage(BuildMessageEventArgs e, bool showProjectFile) =>
// "message" should not be localized
FormatEventMessage("message", e.Subcategory, e.Message,
e.Code, e.File, showProjectFile ? e.ProjectFile : null, e.LineNumber, e.EndLineNumber, e.ColumnNumber, e.EndColumnNumber, e.ThreadId);
/// <summary>
/// Format the event message and all the other event data into a
/// single string.
/// </summary>
/// <param name="category">category ("error" or "warning")</param>
/// <param name="subcategory">subcategory</param>
/// <param name="message">event message</param>
/// <param name="code">error or warning code number</param>
/// <param name="file">file name</param>
/// <param name="lineNumber">line number (0 if n/a)</param>
/// <param name="endLineNumber">end line number (0 if n/a)</param>
/// <param name="columnNumber">column number (0 if n/a)</param>
/// <param name="endColumnNumber">end column number (0 if n/a)</param>
/// <param name="threadId">thread id</param>
/// <returns>The formatted message string.</returns>
internal static string FormatEventMessage
(
string category,
string subcategory,
string message,
string code,
string file,
int lineNumber,
int endLineNumber,
int columnNumber,
int endColumnNumber,
int threadId
) => FormatEventMessage(category, subcategory, message, code, file, null, lineNumber, endLineNumber, columnNumber, endColumnNumber, threadId);
/// <summary>
/// Format the event message and all the other event data into a
/// single string.
/// </summary>
/// <param name="category">category ("error" or "warning")</param>
/// <param name="subcategory">subcategory</param>
/// <param name="message">event message</param>
/// <param name="code">error or warning code number</param>
/// <param name="file">file name</param>
/// <param name="projectFile">the project file name</param>
/// <param name="lineNumber">line number (0 if n/a)</param>
/// <param name="endLineNumber">end line number (0 if n/a)</param>
/// <param name="columnNumber">column number (0 if n/a)</param>
/// <param name="endColumnNumber">end column number (0 if n/a)</param>
/// <param name="threadId">thread id</param>
/// <returns>The formatted message string.</returns>
private static string FormatEventMessage
(
string category,
string subcategory,
string? message,
string? code,
string? file,
string? projectFile,
int lineNumber,
int endLineNumber,
int columnNumber,
int endColumnNumber,
int threadId
)
{
var format = new StringBuilder();
// Uncomment these lines to show show the processor, if present.
/*
if (threadId != 0)
{
format.Append("{0}>");
}
*/
if ((file == null) || (file.Length == 0))
{
format.Append("MSBUILD : "); // Should not be localized.
}
else
{
format.Append("{1}");
if (lineNumber == 0)
{
format.Append(" : ");
}
else
{
if (columnNumber == 0)
{
format.Append(endLineNumber == 0 ? "({2}): " : "({2}-{7}): ");
}
else
{
if (endLineNumber == 0)
{
format.Append(endColumnNumber == 0 ? "({2},{3}): " : "({2},{3}-{8}): ");
}
else
{
format.Append(endColumnNumber == 0 ? "({2}-{7},{3}): " : "({2},{3},{7},{8}): ");
}
}
}
}
if (!string.IsNullOrWhiteSpace(subcategory))
{
format.Append("{9} ");
}
// The category as a string (should not be localized)
format.Append("{4} ");
// Put a code in, if available and necessary.
format.Append(code == null ? ": " : "{5}: ");
// Put the message in, if available.
if (message != null)
{
format.Append("{6}");
}
// If the project file was specified, tack that onto the very end.
if (projectFile != null && !string.Equals(projectFile, file))
{
format.Append(" [{10}]");
}
// A null message is allowed and is to be treated as a blank line.
message ??= string.Empty;
var finalFormat = format.ToString();
// If there are multiple lines, show each line as a separate message.
var lines = SplitStringOnNewLines(message);
var formattedMessage = new StringBuilder();
for (var i = 0; i < lines.Length; i++)
{
formattedMessage.Append(string.Format(
CultureInfo.CurrentCulture, finalFormat,
threadId, file,
lineNumber, columnNumber, category, code,
lines[i], endLineNumber, endColumnNumber,
subcategory, projectFile));
if (i < (lines.Length - 1))
{
formattedMessage.AppendLine();
}
}
return formattedMessage.ToString();
}
/// <summary>
/// Splits strings on 'newLines' with tolerance for Everett and Dogfood builds.
/// </summary>
/// <param name="s">String to split.</param>
private static string[] SplitStringOnNewLines(string s)
{
var subStrings = s.Split(s_newLines, StringSplitOptions.None);
return subStrings;
}
/// <summary>
/// The kinds of newline breaks we expect.
/// </summary>
/// <remarks>Currently we're not supporting "\r".</remarks>
private static readonly string[] s_newLines = { "\r\n", "\n" };
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using DeOps.Implementation;
using DeOps.Implementation.Dht;
using DeOps.Implementation.Protocol;
using DeOps.Implementation.Protocol.Net;
using DeOps.Implementation.Protocol.Special;
namespace DeOps
{
// at high security, low threats and above must be checked
public enum ThreatLevel { Low = 3, Medium = 5, High = 7 }
public enum SecurityLevel { Low = 7, Medium = 5, High = 3 }
public enum TextFormat { Plain = 0, RTF = 1, HTML = 2 }
public static partial class Utilities
{
public static bool MemCompare(byte[] a, byte[] b)
{
if (a == null && b == null)
return true;
if (a == null || b == null)
return false;
if (a.Length != b.Length)
return false;
return MemCompare(a, 0, b, 0, a.Length);
}
public static bool MemCompare(byte[] aBuff, int aOffset, byte[] bBuff, int bOffset, int count)
{
for(int i = 0, aPos = aOffset, bPos = bOffset; i < count; i++, aPos++, bPos++)
if(aBuff[aPos] != bBuff[bPos])
return false;
return true;
}
public static bool GetBit(int bits, int pos)
{
return (((1 << pos) & bits) > 0);
}
public static bool GetBit(UInt64 bits, int pos)
{
pos = 63 - pos;
return (((1UL << pos) & bits) > 0);
}
public static void SetBit(ref UInt64 bits, int pos, bool val)
{
pos = 63 - pos;
if(val)
bits |= 1UL << pos;
else
bits &= ~1UL << pos;
}
public static ulong FlipBit(ulong value, int pos)
{
pos = 63 - pos;
return value ^= 1UL << pos;
}
public static string IDtoBin(UInt64 id)
{
string bin = "";
for(int i = 0; i < 12; i++)
if((id & ((UInt64)1 << 63 - i)) > 0)
bin += "1";
else
bin += "0";
return bin;
}
public static ulong RandUInt64(Random rnd)
{
byte[] bytes = new byte[8];
rnd.NextBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
public static ulong StrongRandUInt64(RNGCryptoServiceProvider rnd)
{
byte[] bytes = new byte[8];
rnd.GetBytes(bytes);
return BitConverter.ToUInt64(bytes, 0);
}
public static byte[] ExtractBytes(byte[] buffer, int offset, int length)
{
byte[] extracted = new byte[length];
Buffer.BlockCopy(buffer, offset, extracted, 0, length);
return extracted;
}
public static string BytestoHex(byte[] data)
{
return Utilities.BytestoHex(data, 0, data.Length, false);
}
public static string BytestoHex(byte[] data, int offset, int size, bool space)
{
StringBuilder hex = new StringBuilder();
for(int i = offset; i < offset + size; i++)
{
hex.Append( String.Format("{0:x2}", data[i]) );
if(space)
hex.Append(" ");
}
return hex.ToString();
}
public static byte[] HextoBytes(string hex)
{
if(hex.Length % 2 != 0)
return null;
byte[] bin = new byte[hex.Length / 2];
hex = hex.ToUpper();
for(int i = 0; i < hex.Length; i++)
{
int val = hex[i];
val -= 48; // 0 - 9
if(val > 9) // A - F
val -= 7;
if(val > 15) // invalid char read
return null;
if(i % 2 == 0)
bin[i/2] = (byte) (val << 4);
else
bin[(i-1)/2] |= (byte) val;
}
return bin;
}
public static string BytestoAscii(byte[] data, int offset, int size)
{
StringBuilder ascii = new StringBuilder();
for(int i = offset; i < offset + size; i++)
if(data[i] >= 33 && data[i] <= 126)
ascii.Append(" " + (char) data[i] + " ");
else
ascii.Append(" . ");
return ascii.ToString();
}
public static UInt64 KeytoID(RSAParameters pubParams)
{
return Utilities.KeytoID(pubParams.Modulus);
}
public static UInt64 KeytoID(byte[] key)
{
SHA1CryptoServiceProvider sha = new SHA1CryptoServiceProvider();
byte[] pubHash = sha.ComputeHash(key);
return BitConverter.ToUInt64(pubHash, 0); // first 8 bytes of sha1 of public key
}
public static string ToBase64String(byte[] hash)
{
string base64 = Convert.ToBase64String(hash);
return base64.Replace('/', '~');
}
public static byte[] FromBase64String(string base64)
{
base64 = base64.Replace('~', '/');
return Convert.FromBase64String(base64);
}
const long BytesInKilo = 1024;
const long BytesInMega = 1024 * 1024;
const long BytesInGiga = 1024 * 1024 * 1024;
public static string ByteSizetoString(long bytes)
{
if (bytes > BytesInGiga)
return string.Format("{0} GB", bytes / BytesInGiga);
if (bytes > BytesInMega)
return string.Format("{0} MB", bytes / BytesInMega);
if (bytes > BytesInKilo)
return string.Format("{0} KB", bytes / BytesInKilo);
return string.Format("{0} B", bytes);
}
public static string ByteSizetoDecString(long bytes)
{
if (bytes > BytesInGiga)
return string.Format("{0:#.00} GB", (double)bytes / (double)BytesInGiga);
if (bytes > BytesInMega)
return string.Format("{0:#.00} MB", (double)bytes / (double)BytesInMega);
if (bytes > BytesInKilo)
return string.Format("{0:#.00} KB", (double)bytes / (double)BytesInKilo);
return string.Format("{0} B", bytes);
}
public static string FormatTime(DateTime time)
{
// convert from utc
time = time.ToLocalTime();
// Thu 4/5/2006 at 4:59pm
string formatted = time.ToString("ddd M/d/yy");
formatted += " at ";
formatted += time.ToString("h:mm");
formatted += time.ToString("tt").ToLower();
return formatted;
}
public static void MoveReplace(string source, string dest)
{
File.Copy(source, dest, true);
File.Delete(source);
}
public static void PruneMap(Dictionary<ulong, uint> map, ulong local, int max)
{
if (map.Count < max)
return;
List<ulong> removeIDs = new List<ulong>();
while (map.Count > 0 && map.Count > max)
{
ulong furthest = local;
foreach (ulong id in map.Keys)
if ((id ^ local) > (furthest ^ local))
furthest = id;
map.Remove(furthest);
}
}
public static string StripOneLevel(string path)
{
int pos = path.LastIndexOf('\\');
if (pos == -1)
return "";
return path.Substring(0, pos);
}
public static void OpenFolder(string path)
{
string windir = Environment.GetEnvironmentVariable("WINDIR");
System.Diagnostics.Process prc = new System.Diagnostics.Process();
prc.StartInfo.FileName = windir + @"\explorer.exe";
prc.StartInfo.Arguments = path;
prc.Start();
}
public static string CommaIze(object value)
{
string final = "";
string num = value.ToString();
while (num.Length > 3)
{
final = "," + num.Substring(num.Length - 3, 3) + final;
num = num.Substring(0, num.Length - 3);
}
final = num + final;
return final;
}
public static void CopyDirectory(string sourcePath, string destPath)
{
if (destPath[destPath.Length - 1] != Path.DirectorySeparatorChar)
destPath += Path.DirectorySeparatorChar;
if (!Directory.Exists(destPath))
Directory.CreateDirectory(destPath);
String[] files = Directory.GetFileSystemEntries(sourcePath);
foreach (string path in files)
{
// if path is sub dir
if (Directory.Exists(path))
CopyDirectory(path, destPath + Path.GetDirectoryName(path));
else
File.Copy(path, destPath + Path.GetFileName(path), true);
}
}
public static byte[] CombineArrays(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
a.CopyTo(c, 0);
b.CopyTo(c, a.Length);
return c;
}
public static bool IsLocalIP(IPAddress address)
{
if (address.IsIPv6LinkLocal)
return true;
if (address.AddressFamily == AddressFamily.InterNetworkV6 )
return false;
byte[] ip = address.GetAddressBytes();
//1.*.*.*
//2.*.*.*
//5.*.*.*
//6.*.*.*
//10.*.*.*
if (ip[0] == 1 || ip[0] == 2 || ip[0] == 5 || ip[0] == 6 || ip[0] == 10)
return true;
//127.0.0.1
if (ip[0] == 127 && ip[1] == 0 && ip[2] == 0 && ip[3] == 1)
return true;
//169.254.*.*
if (ip[0] == 169 && ip[1] == 254)
return true;
//172.16.*.* - 172.31.*.*
if (ip[0] == 172 && (16 <= ip[1] && ip[1] <= 31))
return true;
//192.168.*.*
if (ip[0] == 192 && ip[1] == 168)
return true;
return false;
}
public static string ToRtf(string text)
{
return "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Tahoma;}}\r\n{\\colortbl ;\\red0\\green0\\blue0;}\r\n\\viewkind4\\uc1\\pard\\cf1\\f0\\fs20 " + text + "\\cf0}\r\n";
}
public static bool AreAllSet(this BitArray array, bool value)
{
foreach (bool bit in array)
if (bit != value)
return false;
return true;
}
public static byte[] ToBytes(this BitArray array)
{
// size info not transmitted, must be send seperately
int size = array.Length / 8;
if (array.Length % 8 > 0)
size += 1;
byte[] bytes = new byte[size];
for(int i = 0; i < size; i++)
for (int x = 0; x < 8; x++)
{
int index = i * 8 + x ;
if (index < array.Length && array[index])
bytes[i] = (byte)(bytes[i] | (1 << x));
}
return bytes;
}
public static bool Compare(this BitArray array, BitArray check)
{
if (array.Length != check.Length)
return false;
for (int i = 0; i < array.Length; i++)
if (array[i] != check[i])
return false;
return true;
}
public static BitArray ToBitArray(byte[] bytes, int length)
{
BitArray array = new BitArray(length);
for(int i = 0; i < bytes.Length; i++)
for (int x = 0; x < 8; x++)
{
int index = i * 8 + x;
if (index >= length)
break;
if ((bytes[i] & (1 << x)) > 0)
array.Set(index, true);
}
return array;
}
public static string WebDownloadString(string url)
{
// WebClient DownloadString does the same thing but has a bug that causes it to hang indefinitely
// in some situations when host is not responding, this we know times out, doesnt cause app close to hang
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Timeout = 7000;
WebResponse response = request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string responseText = streamReader.ReadToEnd();
response.Close();
return responseText;
}
public static void ExtractAttachedFile(string source, byte[] key, long fileStart, long[] attachments, int index, string destination)
{
using (TaggedStream tagged = new TaggedStream(source, new G2Protocol()))
using (IVCryptoStream crypto = IVCryptoStream.Load(tagged, key))
{
// get past packet section of file
const int buffSize = 4096;
byte[] buffer = new byte[4096];
long bytesLeft = fileStart;
while (bytesLeft > 0)
{
int readSize = (bytesLeft > buffSize) ? buffSize : (int)bytesLeft;
int read = crypto.Read(buffer, 0, readSize);
bytesLeft -= read;
}
// setup write file
using (FileStream outstream = new FileStream(destination, FileMode.Create, FileAccess.Write))
{
// read files, write the right one :P
for (int i = 0; i < attachments.Length; i++)
{
bytesLeft = attachments[i];
while (bytesLeft > 0)
{
int readSize = (bytesLeft > buffSize) ? buffSize : (int)bytesLeft;
int read = crypto.Read(buffer, 0, readSize);
bytesLeft -= read;
if (i == index)
outstream.Write(buffer, 0, read);
}
}
}
}
}
}
}
namespace DeOps.Implementation
{
public class BufferData
{
public byte[] Source;
public int Start;
public int Size;
public BufferData(byte[] source)
{
Source = source;
Size = source.Length;
Debug.Assert(Source.Length >= Size - Start);
}
public BufferData(byte[] source, int start, int size)
{
Source = source;
Start = start;
Size = size;
Debug.Assert(Source.Length >= Size - Start);
}
public void Reset()
{
Start = 0;
Size = Source.Length;
}
}
public class MovingAvg
{
int Entries;
int[] Elements;
int Pos;
int Total;
int SecondSum;
public MovingAvg(int size)
{
Elements = new int[size];
}
public void Input(int val)
{
SecondSum += val;
}
public void Next()
{
if(Entries < Elements.Length)
Entries++;
if(Pos == Elements.Length)
Pos = 0;
Total -= Elements[Pos];
Elements[Pos] = SecondSum;
Total += SecondSum;
SecondSum = 0;
Pos++;
}
public int GetAverage()
{
if(Entries > 0)
return Total / Entries;
return 0;
}
}
public class AttachedFile
{
public string FilePath;
public string Name;
public long Size;
public AttachedFile(string path)
{
FilePath = path;
Name = Path.GetFileName(FilePath);
FileInfo info = new FileInfo(path);
Size = info.Length;
}
public override string ToString()
{
return Name + " (" + Utilities.ByteSizetoString(Size) + ")";
}
}
public class ServiceEvent<TDelegate>
{
public Dictionary<uint, Dictionary<uint, TDelegate>> HandlerMap = new Dictionary<uint, Dictionary<uint, TDelegate>>();
public TDelegate this[uint service, uint type]
{
get
{
if (Contains(service, type))
return HandlerMap[service][type];
return default(TDelegate);
}
set
{
// adding handler
if (value != null)
{
if (!HandlerMap.ContainsKey(service))
HandlerMap[service] = new Dictionary<uint, TDelegate>();
HandlerMap[service][type] = value;
}
// removing handler
else
{
if (HandlerMap.ContainsKey(service))
{
if (HandlerMap[service].ContainsKey(type))
HandlerMap[service].Remove(type);
if (HandlerMap[service].Count == 0)
HandlerMap.Remove(service);
}
}
}
}
public bool Contains(uint service, uint type)
{
return HandlerMap.ContainsKey(service) && HandlerMap[service].ContainsKey(type);
}
}
public class BandwidthLog
{
public CircularBuffer<int> In;
public CircularBuffer<int> Out;
public int InPerSec;
public int OutPerSec;
public BandwidthLog(int size)
{
In = new CircularBuffer<int>(size);
Out = new CircularBuffer<int>(size);
}
public void NextSecond()
{
In.Add(InPerSec);
InPerSec = 0;
Out.Add(OutPerSec);
OutPerSec = 0;
}
public void Resize(int seconds)
{
In.Capacity = seconds;
Out.Capacity = seconds;
}
public float InOutAvg(int period)
{
return Average(In, period) + Average(Out, period);
}
public float InAvg()
{
return Average(In, In.Length);
}
public float OutAvg()
{
return Average(Out, Out.Length);
}
public float Average(CircularBuffer<int> buff, int period)
{
float avg = 0;
int i = 0;
for (; i < period && i < buff.Length; i++)
avg += buff[i];
return (i > 0) ? avg / i : 0;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections;
using System.Collections.Generic;
namespace System.Management.Automation
{
/// <summary>
/// Class HelpProviderWithCache provides a pseudo implementation of HelpProvider
/// at which results are cached in a hashtable so that later retrieval can be
/// faster.
/// </summary>
internal abstract class HelpProviderWithCache : HelpProvider
{
/// <summary>
/// Constructor for HelpProviderWithCache.
/// </summary>
internal HelpProviderWithCache(HelpSystem helpSystem) : base(helpSystem)
{
}
#region Help Provider Interface
/// <summary>
/// _helpCache is a hashtable to stores helpInfo.
/// </summary>
/// <remarks>
/// This hashtable is made case-insensitive so that helpInfo can be retrieved case insensitively.
/// </remarks>
private Hashtable _helpCache = new Hashtable(StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Exact match help for a target.
/// </summary>
/// <param name="helpRequest">Help request object.</param>
/// <returns>The HelpInfo found. Null if nothing is found.</returns>
internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest)
{
string target = helpRequest.Target;
if (!this.HasCustomMatch)
{
if (_helpCache.Contains(target))
{
yield return (HelpInfo)_helpCache[target];
}
}
else
{
foreach (string key in _helpCache.Keys)
{
if (CustomMatch(target, key))
{
yield return (HelpInfo)_helpCache[key];
}
}
}
if (!this.CacheFullyLoaded)
{
DoExactMatchHelp(helpRequest);
if (_helpCache.Contains(target))
{
yield return (HelpInfo)_helpCache[target];
}
}
}
/// <summary>
/// This is for child class to indicate that it has implemented
/// a custom way of match.
/// </summary>
/// <value></value>
protected bool HasCustomMatch { get; set; } = false;
/// <summary>
/// This is for implementing custom match algorithm.
/// </summary>
/// <param name="target">Target to search.</param>
/// <param name="key">Key used in cache table.</param>
/// <returns></returns>
protected virtual bool CustomMatch(string target, string key)
{
return target == key;
}
/// <summary>
/// Do exact match help for a target.
/// </summary>
/// <remarks>
/// Derived class can choose to either override ExactMatchHelp method to DoExactMatchHelp method.
/// If ExactMatchHelp is overridden, initial cache checking will be disabled by default.
/// If DoExactMatchHelp is overridden, cache check will be done first in ExactMatchHelp before the
/// logic in DoExactMatchHelp is in place.
/// </remarks>
/// <param name="helpRequest">Help request object.</param>
internal virtual void DoExactMatchHelp(HelpRequest helpRequest)
{
}
/// <summary>
/// Search help for a target.
/// </summary>
/// <param name="helpRequest">Help request object.</param>
/// <param name="searchOnlyContent">
/// If true, searches for pattern in the help content. Individual
/// provider can decide which content to search in.
///
/// If false, searches for pattern in the command names.
/// </param>
/// <returns>A collection of help info objects.</returns>
internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent)
{
string target = helpRequest.Target;
string wildcardpattern = GetWildCardPattern(target);
HelpRequest searchHelpRequest = helpRequest.Clone();
searchHelpRequest.Target = wildcardpattern;
if (!this.CacheFullyLoaded)
{
IEnumerable<HelpInfo> result = DoSearchHelp(searchHelpRequest);
if (result != null)
{
foreach (HelpInfo helpInfoToReturn in result)
{
yield return helpInfoToReturn;
}
}
}
else
{
int countOfHelpInfoObjectsFound = 0;
WildcardPattern helpMatcher = WildcardPattern.Get(wildcardpattern, WildcardOptions.IgnoreCase);
foreach (string key in _helpCache.Keys)
{
if ((!searchOnlyContent && helpMatcher.IsMatch(key)) ||
(searchOnlyContent && ((HelpInfo)_helpCache[key]).MatchPatternInContent(helpMatcher)))
{
countOfHelpInfoObjectsFound++;
yield return (HelpInfo)_helpCache[key];
if (helpRequest.MaxResults > 0 && countOfHelpInfoObjectsFound >= helpRequest.MaxResults)
{
yield break;
}
}
}
}
}
/// <summary>
/// Create a wildcard pattern based on a target.
///
/// Here we provide the default implementation of this, covering following
/// two cases
/// a. if target has wildcard pattern, return as it is.
/// b. if target doesn't have wildcard pattern, postfix it with *
///
/// Child class of this one may choose to override this function.
/// </summary>
/// <param name="target">Target string.</param>
/// <returns>Wild card pattern created.</returns>
internal virtual string GetWildCardPattern(string target)
{
if (WildcardPattern.ContainsWildcardCharacters(target))
return target;
return "*" + target + "*";
}
/// <summary>
/// Do search help. This is for child class to override.
/// </summary>
/// <remarks>
/// Child class can choose to override SearchHelp of DoSearchHelp depending on
/// whether it want to reuse the logic in SearchHelp for this class.
/// </remarks>
/// <param name="helpRequest">Help request object.</param>
/// <returns>A collection of help info objects.</returns>
internal virtual IEnumerable<HelpInfo> DoSearchHelp(HelpRequest helpRequest)
{
yield break;
}
/// <summary>
/// Add an help entry to cache.
/// </summary>
/// <param name="target">The key of the help entry.</param>
/// <param name="helpInfo">HelpInfo object as the value of the help entry.</param>
internal void AddCache(string target, HelpInfo helpInfo)
{
_helpCache[target] = helpInfo;
}
/// <summary>
/// Get help entry from cache.
/// </summary>
/// <param name="target">The key for the help entry to retrieve.</param>
/// <returns>The HelpInfo in cache corresponding the key specified.</returns>
internal HelpInfo GetCache(string target)
{
return (HelpInfo)_helpCache[target];
}
/// <summary>
/// Is cached fully loaded?
///
/// If cache is fully loaded, search/exactmatch Help can short cut the logic
/// in various help providers to get help directly from cache.
///
/// This indicator is usually set by help providers derived from this class.
/// </summary>
/// <value></value>
protected internal bool CacheFullyLoaded { get; set; } = false;
/// <summary>
/// This will reset the help cache. Normally this corresponds to a
/// help culture change.
/// </summary>
internal override void Reset()
{
base.Reset();
_helpCache.Clear();
CacheFullyLoaded = false;
}
#endregion
}
}
| |
namespace Lex
{
/*
* Class: MakeNfa
*/
using System;
using System.Collections;
using BitSet;
public class MakeNfa
{
/*
* Member Variables
*/
private static Spec spec;
private static Gen gen;
private static Input input;
/*
* Expands character class to include special BOL and
* EOF characters. Puts numeric index of these characters in
* input Spec.
*/
public static void Allocate_BOL_EOF(Spec s)
{
#if DEBUG
Utility.assert(Spec.NUM_PSEUDO==2);
#endif
s.BOL = s.dtrans_ncols++;
s.EOF = s.dtrans_ncols++;
}
/*
* Function: CreateMachine
* Description: High level access function to module.
* Deposits result in input Spec.
*/
public static void CreateMachine(Gen cmg, Spec cms, Input cmi)
{
int i;
Nfa elem;
int size;
spec = cms;
gen = cmg;
input = cmi;
size = spec.states.Count;
spec.state_rules = new ArrayList[size];
for (i = 0; i < size; ++i)
{
spec.state_rules[i] = new ArrayList();
}
/*
* Initialize current token variable and create nfa.
*/
spec.nfa_start = machine();
/* Set labels in created nfa machine. */
size = spec.nfa_states.Count;
for (i = 0; i < size; ++i)
{
elem = (Nfa) spec.nfa_states[i];
elem.SetLabel(i);
}
/* Debugging output. */
#if DO_DEBUG
gen.print_nfa();
#endif
if (spec.verbose)
{
Console.WriteLine("NFA comprised of "
+ (spec.nfa_states.Count + 1)
+ " states.");
}
}
/*
* Function: discardCNfa
*/
private static void discardNfa(Nfa nfa)
{
spec.nfa_states.Remove(nfa);
}
/*
* Function: ProcessStates
*/
private static void ProcessStates(BitSet bset, Nfa current)
{
foreach (int rule in bset)
{
ArrayList p = spec.state_rules[rule];
#if DEBUG
Utility.assert(p != null);
#endif
p.Add(current);
}
}
/*
* Function: machine
* Description: Recursive descent regular expression parser.
*/
private static Nfa machine()
{
Nfa start;
Nfa p;
BitSet states;
#if DESCENT_DEBUG
Utility.enter("machine",spec.lexeme,spec.current_token);
#endif
start = Alloc.NewNfa(spec);
p = start;
states = gen.GetStates();
/* Begin: Added for states. */
spec.current_token = Gen.EOS;
gen.Advance();
/* End: Added for states. */
if (Gen.END_OF_INPUT != spec.current_token)
{
p.SetNext(rule());
ProcessStates(states,p.GetNext());
}
while (Gen.END_OF_INPUT != spec.current_token)
{
/* Make state changes HERE. */
states = gen.GetStates();
/* Begin: Added for states. */
gen.Advance();
if (Gen.END_OF_INPUT == spec.current_token)
break;
/* End: Added for states. */
p.SetSib(Alloc.NewNfa(spec));
p = p.GetSib();
p.SetNext(rule());
ProcessStates(states,p.GetNext());
}
/*
* add pseudo-rules for BOL and EOF
*/
p.SetSib(Alloc.NewNfa(spec));
p = p.GetSib();
p.SetNext(Alloc.NewNfa(spec));
Nfa pnext = p.GetNext();
pnext.SetEdge(Nfa.CCL);
pnext.SetNext(Alloc.NewNfa(spec));
pnext.SetCharSet(new CharSet());
pnext.GetCharSet().add(spec.BOL);
pnext.GetCharSet().add(spec.EOF);
// do-nothing accept rule
pnext.GetNext().SetAccept(new Accept(null, input.line_number+1));
/* add the pseudo rules */
for (int i=0; i < spec.states.Count; i++)
{
ArrayList srule = spec.state_rules[i];
srule.Add(pnext);
}
#if DESCENT_DEBUG
Utility.leave("machine",spec.lexeme,spec.current_token);
#endif
return start;
}
/*
* Function: rule
* Description: Recursive descent regular expression parser.
*/
private static Nfa rule()
{
NfaPair pair;
Nfa start = null;
Nfa end = null;
int anchor = Spec.NONE;
#if DESCENT_DEBUG
Utility.enter("rule", spec.lexeme, spec.current_token);
#endif
pair = Alloc.NewNfaPair();
if (Gen.AT_BOL == spec.current_token)
{
anchor = anchor | Spec.START;
gen.Advance();
expr(pair);
start = Alloc.NewNfa(spec);
start.SetEdge(spec.BOL);
start.SetNext(pair.start);
end = pair.end;
}
else
{
expr(pair);
start = pair.start;
end = pair.end;
}
if (Gen.AT_EOL == spec.current_token)
{
gen.Advance();
NfaPair nlpair = Alloc.NewNLPair(spec);
end.SetNext(Alloc.NewNfa(spec));
Nfa enext = end.GetNext();
enext.SetNext(nlpair.start);
enext.SetSib(Alloc.NewNfa(spec));
enext.GetSib().SetEdge(spec.EOF);
enext.GetSib().SetNext(nlpair.end);
end = nlpair.end;
anchor = anchor | Spec.END;
}
/* check for null rules */
if (end == null)
Error.parse_error(Error.E_ZERO, input.line_number);
/* Handle end of regular expression */
end.SetAccept(gen.packAccept());
end.SetAnchor(anchor);
#if DESCENT_DEBUG
Utility.leave("rule",spec.lexeme,spec.current_token);
#endif
return start;
}
/*
* Function: expr
* Description: Recursive descent regular expression parser.
*/
private static void expr(NfaPair pair)
{
NfaPair e2_pair;
Nfa p;
#if DESCENT_DEBUG
Utility.enter("expr",spec.lexeme,spec.current_token);
#endif
#if DEBUG
Utility.assert(null != pair);
#endif
e2_pair = Alloc.NewNfaPair();
cat_expr(pair);
while (Gen.OR == spec.current_token)
{
gen.Advance();
cat_expr(e2_pair);
p = Alloc.NewNfa(spec);
p.SetSib(e2_pair.start);
p.SetNext(pair.start);
pair.start = p;
p = Alloc.NewNfa(spec);
pair.end.SetNext(p);
e2_pair.end.SetNext(p);
pair.end = p;
}
#if DESCENT_DEBUG
Utility.leave("expr",spec.lexeme,spec.current_token);
#endif
}
/*
* Function: cat_expr
* Description: Recursive descent regular expression parser.
*/
private static void cat_expr(NfaPair pair)
{
NfaPair e2_pair;
#if DESCENT_DEBUG
Utility.enter("cat_expr",spec.lexeme,spec.current_token);
#endif
#if DEBUG
Utility.assert(null != pair);
#endif
e2_pair = Alloc.NewNfaPair();
if (first_in_cat(spec.current_token))
{
factor(pair);
}
while (first_in_cat(spec.current_token))
{
factor(e2_pair);
/* Destroy */
pair.end.mimic(e2_pair.start);
discardNfa(e2_pair.start);
pair.end = e2_pair.end;
}
#if DESCENT_DEBUG
Utility.leave("cat_expr",spec.lexeme,spec.current_token);
#endif
}
/*
* Function: first_in_cat
* Description: Recursive descent regular expression parser.
*/
private static bool first_in_cat(int token)
{
if (token == Gen.CLOSE_PAREN || token == Gen.AT_EOL
|| token == Gen.OR || token == Gen.EOS)
return false;
if (token == Gen.CLOSURE || token == Gen.PLUS_CLOSE
|| token == Gen.OPTIONAL)
{
Error.parse_error(Error.E_CLOSE,input.line_number);
return false;
}
if (token == Gen.CCL_END)
{
Error.parse_error(Error.E_BRACKET,input.line_number);
return false;
}
if (token == Gen.AT_BOL)
{
Error.parse_error(Error.E_BOL,input.line_number);
return false;
}
return true;
}
/*
* Function: factor
* Description: Recursive descent regular expression parser.
*/
private static void factor(NfaPair pair)
{
Nfa start = null;
Nfa end = null;
#if DESCENT_DEBUG
Utility.enter("factor",spec.lexeme,spec.current_token);
#endif
term(pair);
if (Gen.CLOSURE == spec.current_token
|| Gen.PLUS_CLOSE == spec.current_token
|| Gen.OPTIONAL == spec.current_token)
{
start = Alloc.NewNfa(spec);
end = Alloc.NewNfa(spec);
start.SetNext(pair.start);
pair.end.SetNext(end);
if (Gen.CLOSURE == spec.current_token
|| Gen.OPTIONAL == spec.current_token)
{
start.SetSib(end);
}
if (Gen.CLOSURE == spec.current_token
|| Gen.PLUS_CLOSE == spec.current_token)
{
pair.end.SetSib(pair.start);
}
pair.start = start;
pair.end = end;
gen.Advance();
}
#if DESCENT_DEBUG
Utility.leave("factor",spec.lexeme,spec.current_token);
#endif
}
/*
* Function: term
* Description: Recursive descent regular expression parser.
*/
private static void term(NfaPair pair)
{
Nfa start;
bool isAlphaL;
#if DESCENT_DEBUG
Utility.enter("term",spec.lexeme,spec.current_token);
#endif
if (Gen.OPEN_PAREN == spec.current_token)
{
gen.Advance();
expr(pair);
if (Gen.CLOSE_PAREN == spec.current_token)
{
gen.Advance();
}
else
{
Error.parse_error(Error.E_SYNTAX,input.line_number);
}
}
else
{
start = Alloc.NewNfa(spec);
pair.start = start;
start.SetNext(Alloc.NewNfa(spec));
pair.end = start.GetNext();
if (Gen.L == spec.current_token && Char.IsLetter(spec.lexeme))
{
isAlphaL = true;
}
else
{
isAlphaL = false;
}
if (false == (Gen.ANY == spec.current_token
|| Gen.CCL_START == spec.current_token
|| (spec.ignorecase && isAlphaL)))
{
start.SetEdge(spec.lexeme);
gen.Advance();
}
else
{
start.SetEdge(Nfa.CCL);
start.SetCharSet(new CharSet());
CharSet cset = start.GetCharSet();
/* Match case-insensitive letters using character class. */
if (spec.ignorecase && isAlphaL)
{
cset.addncase(spec.lexeme);
}
/* Match dot (.) using character class. */
else if (Gen.ANY == spec.current_token)
{
cset.add('\n');
cset.add('\r');
/* exclude BOL and EOF from character classes */
cset.add(spec.BOL);
cset.add(spec.EOF);
cset.complement();
}
else
{
gen.Advance();
if (Gen.AT_BOL == spec.current_token)
{
gen.Advance();
/* exclude BOL and EOF from character classes */
cset.add(spec.BOL);
cset.add(spec.EOF);
cset.complement();
}
if (!(Gen.CCL_END == spec.current_token))
{
dodash(cset);
}
}
gen.Advance();
}
}
#if DESCENT_DEBUG
Utility.leave("term",spec.lexeme,spec.current_token);
#endif
}
/*
* Function: dodash
* Description: Recursive descent regular expression parser.
*/
private static void dodash(CharSet set)
{
int first = -1;
#if DESCENT_DEBUG
Utility.enter("dodash",spec.lexeme,spec.current_token);
#endif
while (Gen.EOS != spec.current_token
&& Gen.CCL_END != spec.current_token)
{
// DASH loses its special meaning if it is first in class.
if (Gen.DASH == spec.current_token && -1 != first)
{
gen.Advance();
// DASH loses its special meaning if it is last in class.
if (spec.current_token == Gen.CCL_END)
{
// 'first' already in set.
set.add('-');
break;
}
for ( ; first <= spec.lexeme; ++first)
{
if (spec.ignorecase)
set.addncase((char)first);
else
set.add(first);
}
}
else
{
first = spec.lexeme;
if (spec.ignorecase)
set.addncase(spec.lexeme);
else
set.add(spec.lexeme);
}
gen.Advance();
}
#if DESCENT_DEBUG
Utility.leave("dodash",spec.lexeme,spec.current_token);
#endif
}
}
}
| |
namespace Petstore
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Microsoft.Rest;
using Models;
/// <summary>
/// This is a sample server Petstore server. You can find out more about
/// Swagger at <a
/// href="http://swagger.io">http://swagger.io</a> or on
/// irc.freenode.net, #swagger. For this sample, you can use the api key
/// "special-key" to test the authorization filters
/// </summary>
public partial interface ISwaggerPetstore : IDisposable
{
/// <summary>
/// The base URI of the service.
/// </summary>
Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
JsonSerializerSettings SerializationSettings { get; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
JsonSerializerSettings DeserializationSettings { get; }
/// <summary>
/// Fake endpoint to test byte array in body parameter for adding a
/// new pet to the store
/// </summary>
/// <param name='body'>
/// Pet object in the form of byte array
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> AddPetUsingByteArrayWithHttpMessagesAsync(string body = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Add a new pet to the store
/// </summary>
/// <remarks>
/// Adds a new pet to the store. You may receive an HTTP invalid input
/// if your pet is invalid.
/// </remarks>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> AddPetWithHttpMessagesAsync(Pet body = default(Pet), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Update an existing pet
/// </summary>
/// <param name='body'>
/// Pet object that needs to be added to the store
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithHttpMessagesAsync(Pet body = default(Pet), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by status
/// </summary>
/// <remarks>
/// Multiple status values can be provided with comma seperated strings
/// </remarks>
/// <param name='status'>
/// Status values that need to be considered for filter
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByStatusWithHttpMessagesAsync(IList<string> status = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Finds Pets by tags
/// </summary>
/// <remarks>
/// Muliple tags can be provided with comma seperated strings. Use
/// tag1, tag2, tag3 for testing.
/// </remarks>
/// <param name='tags'>
/// Tags to filter by
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IList<Pet>>> FindPetsByTagsWithHttpMessagesAsync(IList<string> tags = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Fake endpoint to test byte array return by 'Find pet by ID'
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will
/// simulate API error conditions
/// </remarks>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<string>> FindPetsWithByteArrayWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find pet by ID
/// </summary>
/// <remarks>
/// Returns a pet when ID < 10. ID > 10 or nonintegers will
/// simulate API error conditions
/// </remarks>
/// <param name='petId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Pet>> GetPetByIdWithHttpMessagesAsync(long petId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates a pet in the store with form data
/// </summary>
/// <param name='petId'>
/// ID of pet that needs to be updated
/// </param>
/// <param name='name'>
/// Updated name of the pet
/// </param>
/// <param name='status'>
/// Updated status of the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdatePetWithFormWithHttpMessagesAsync(string petId, string name = default(string), string status = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a pet
/// </summary>
/// <param name='petId'>
/// Pet id to delete
/// </param>
/// <param name='apiKey'>
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeletePetWithHttpMessagesAsync(long petId, string apiKey = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// uploads an image
/// </summary>
/// <param name='petId'>
/// ID of pet to update
/// </param>
/// <param name='additionalMetadata'>
/// Additional data to pass to server
/// </param>
/// <param name='file'>
/// file to upload
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UploadFileWithHttpMessagesAsync(long petId, string additionalMetadata = default(string), System.IO.Stream file = default(System.IO.Stream), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Returns pet inventories by status
/// </summary>
/// <remarks>
/// Returns a map of status codes to quantities
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<IDictionary<string, int?>>> GetInventoryWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Place an order for a pet
/// </summary>
/// <param name='body'>
/// order placed for purchasing the pet
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> PlaceOrderWithHttpMessagesAsync(Order body = default(Order), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Find purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value <= 5 or > 10.
/// Other values will generated exceptions
/// </remarks>
/// <param name='orderId'>
/// ID of pet that needs to be fetched
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<Order>> GetOrderByIdWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete purchase order by ID
/// </summary>
/// <remarks>
/// For valid response try integer IDs with value < 1000. Anything
/// above 1000 or nonintegers will generate API errors
/// </remarks>
/// <param name='orderId'>
/// ID of the order that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteOrderWithHttpMessagesAsync(string orderId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='body'>
/// Created user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUserWithHttpMessagesAsync(User body = default(User), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithArrayInputWithHttpMessagesAsync(IList<User> body = default(IList<User>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates list of users with given input array
/// </summary>
/// <param name='body'>
/// List of user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> CreateUsersWithListInputWithHttpMessagesAsync(IList<User> body = default(IList<User>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs user into the system
/// </summary>
/// <param name='username'>
/// The user name for login
/// </param>
/// <param name='password'>
/// The password for login in clear text
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<string>> LoginUserWithHttpMessagesAsync(string username = default(string), string password = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Logs out current logged in user session
/// </summary>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> LogoutUserWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get user by user name
/// </summary>
/// <param name='username'>
/// The name that needs to be fetched. Use user1 for testing.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse<User>> GetUserByNameWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updated user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// name that need to be deleted
/// </param>
/// <param name='body'>
/// Updated user object
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> UpdateUserWithHttpMessagesAsync(string username, User body = default(User), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete user
/// </summary>
/// <remarks>
/// This can only be done by the logged in user.
/// </remarks>
/// <param name='username'>
/// The name that needs to be deleted
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
Task<HttpOperationResponse> DeleteUserWithHttpMessagesAsync(string username, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if ES_BUILD_STANDALONE
using System;
using System.Diagnostics;
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
#endif
using System.Runtime.InteropServices;
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: This is the implementation of the DataCollector
/// functionality. To enable safe access to the DataCollector from
/// untrusted code, there is one thread-local instance of this structure
/// per thread. The instance must be Enabled before any data is written to
/// it. The instance must be Finished before the data is passed to
/// EventWrite. The instance must be Disabled before the arrays referenced
/// by the pointers are freed or unpinned.
/// </summary>
internal unsafe struct DataCollector
{
[ThreadStatic]
internal static DataCollector ThreadInstance;
private byte* scratchEnd;
private EventSource.EventData* datasEnd;
private GCHandle* pinsEnd;
private EventSource.EventData* datasStart;
private byte* scratch;
private EventSource.EventData* datas;
private GCHandle* pins;
private byte[]? buffer;
private int bufferPos;
private int bufferNesting; // We may merge many fields int a single blob. If we are doing this we increment this.
private bool writingScalars;
internal void Enable(
byte* scratch,
int scratchSize,
EventSource.EventData* datas,
int dataCount,
GCHandle* pins,
int pinCount)
{
this.datasStart = datas;
this.scratchEnd = scratch + scratchSize;
this.datasEnd = datas + dataCount;
this.pinsEnd = pins + pinCount;
this.scratch = scratch;
this.datas = datas;
this.pins = pins;
this.writingScalars = false;
}
internal void Disable()
{
this = new DataCollector();
}
/// <summary>
/// Completes the list of scalars. Finish must be called before the data
/// descriptor array is passed to EventWrite.
/// </summary>
/// <returns>
/// A pointer to the next unused data descriptor, or datasEnd if they were
/// all used. (Descriptors may be unused if a string or array was null.)
/// </returns>
internal EventSource.EventData* Finish()
{
this.ScalarsEnd();
return this.datas;
}
internal void AddScalar(void* value, int size)
{
var pb = (byte*)value;
if (this.bufferNesting == 0)
{
byte* scratchOld = this.scratch;
byte* scratchNew = scratchOld + size;
if (this.scratchEnd < scratchNew)
{
throw new IndexOutOfRangeException(SR.EventSource_AddScalarOutOfRange);
}
this.ScalarsBegin();
this.scratch = scratchNew;
for (int i = 0; i != size; i++)
{
scratchOld[i] = pb[i];
}
}
else
{
int oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
Debug.Assert(buffer != null);
for (int i = 0; i != size; i++, oldPos++)
{
this.buffer[oldPos] = pb[i];
}
}
}
internal void AddBinary(string? value, int size)
{
if (size > ushort.MaxValue)
{
size = ushort.MaxValue - 1;
}
if (this.bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
this.AddScalar(&size, 2);
if (size != 0)
{
if (this.bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
int oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
Debug.Assert(buffer != null);
fixed (void* p = value)
{
Marshal.Copy((IntPtr)p, buffer, oldPos, size);
}
}
}
}
internal void AddNullTerminatedString(string? value)
{
// Treat null strings as empty strings.
if (value == null)
{
value = string.Empty;
}
// Calculate the size of the string including the trailing NULL char.
// Don't use value.Length here because string allows for embedded NULL characters.
int nullCharIndex = value.IndexOf((char)0);
if (nullCharIndex < 0)
{
nullCharIndex = value.Length;
}
int size = (nullCharIndex + 1) * 2;
if (this.bufferNesting != 0)
{
this.EnsureBuffer(size);
}
if (this.bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
int oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
Debug.Assert(buffer != null);
fixed (void* p = value)
{
Marshal.Copy((IntPtr)p, buffer, oldPos, size);
}
}
}
internal void AddBinary(Array value, int size)
{
this.AddArray(value, size, 1);
}
internal void AddArray(Array? value, int length, int itemSize)
{
if (length > ushort.MaxValue)
{
length = ushort.MaxValue;
}
int size = length * itemSize;
if (this.bufferNesting != 0)
{
this.EnsureBuffer(size + 2);
}
this.AddScalar(&length, 2);
if (length != 0)
{
if (this.bufferNesting == 0)
{
this.ScalarsEnd();
this.PinArray(value, size);
}
else
{
int oldPos = this.bufferPos;
this.bufferPos = checked(this.bufferPos + size);
this.EnsureBuffer();
Debug.Assert(value != null && buffer != null);
Buffer.BlockCopy(value, 0, this.buffer, oldPos, size);
}
}
}
/// <summary>
/// Marks the start of a non-blittable array or enumerable.
/// </summary>
/// <returns>Bookmark to be passed to EndBufferedArray.</returns>
internal int BeginBufferedArray()
{
this.BeginBuffered();
this.bufferPos += 2; // Reserve space for the array length (filled in by EndEnumerable)
return this.bufferPos;
}
/// <summary>
/// Marks the end of a non-blittable array or enumerable.
/// </summary>
/// <param name="bookmark">The value returned by BeginBufferedArray.</param>
/// <param name="count">The number of items in the array.</param>
internal void EndBufferedArray(int bookmark, int count)
{
this.EnsureBuffer();
Debug.Assert(buffer != null);
this.buffer[bookmark - 2] = unchecked((byte)count);
this.buffer[bookmark - 1] = unchecked((byte)(count >> 8));
this.EndBuffered();
}
/// <summary>
/// Marks the start of dynamically-buffered data.
/// </summary>
internal void BeginBuffered()
{
this.ScalarsEnd();
this.bufferNesting++;
}
/// <summary>
/// Marks the end of dynamically-buffered data.
/// </summary>
internal void EndBuffered()
{
this.bufferNesting--;
if (this.bufferNesting == 0)
{
/*
TODO (perf): consider coalescing adjacent buffered regions into a
single buffer, similar to what we're already doing for adjacent
scalars. In addition, if a type contains a buffered region adjacent
to a blittable array, and the blittable array is small, it would be
more efficient to buffer the array instead of pinning it.
*/
this.EnsureBuffer();
Debug.Assert(buffer != null);
this.PinArray(this.buffer, this.bufferPos);
this.buffer = null;
this.bufferPos = 0;
}
}
private void EnsureBuffer()
{
int required = this.bufferPos;
if (this.buffer == null || this.buffer.Length < required)
{
this.GrowBuffer(required);
}
}
private void EnsureBuffer(int additionalSize)
{
int required = this.bufferPos + additionalSize;
if (this.buffer == null || this.buffer.Length < required)
{
this.GrowBuffer(required);
}
}
private void GrowBuffer(int required)
{
int newSize = this.buffer == null ? 64 : this.buffer.Length;
do
{
newSize *= 2;
}
while (newSize < required);
Array.Resize(ref this.buffer, newSize);
}
private void PinArray(object? value, int size)
{
GCHandle* pinsTemp = this.pins;
if (this.pinsEnd <= pinsTemp)
{
throw new IndexOutOfRangeException(SR.EventSource_PinArrayOutOfRange);
}
EventSource.EventData* datasTemp = this.datas;
if (this.datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(SR.EventSource_DataDescriptorsOutOfRange);
}
this.pins = pinsTemp + 1;
this.datas = datasTemp + 1;
*pinsTemp = GCHandle.Alloc(value, GCHandleType.Pinned);
datasTemp->DataPointer = pinsTemp->AddrOfPinnedObject();
datasTemp->m_Size = size;
}
private void ScalarsBegin()
{
if (!this.writingScalars)
{
EventSource.EventData* datasTemp = this.datas;
if (this.datasEnd <= datasTemp)
{
throw new IndexOutOfRangeException(SR.EventSource_DataDescriptorsOutOfRange);
}
datasTemp->DataPointer = (IntPtr)this.scratch;
this.writingScalars = true;
}
}
private void ScalarsEnd()
{
if (this.writingScalars)
{
EventSource.EventData* datasTemp = this.datas;
datasTemp->m_Size = checked((int)(this.scratch - (byte*)datasTemp->m_Ptr));
this.datas = datasTemp + 1;
this.writingScalars = false;
}
}
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1) Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using Newtonsoft.Json;
namespace XenAPI
{
/// <summary>
/// A set of properties that describe one result element of SR.probe. Result elements and properties can change dynamically based on changes to the the SR.probe input-parameters or the target.
/// </summary>
public partial class Probe_result : XenObject<Probe_result>
{
#region Constructors
public Probe_result()
{
}
public Probe_result(Dictionary<string, string> configuration,
bool complete,
Sr_stat sr,
Dictionary<string, string> extra_info)
{
this.configuration = configuration;
this.complete = complete;
this.sr = sr;
this.extra_info = extra_info;
}
/// <summary>
/// Creates a new Probe_result 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 Probe_result(Hashtable table)
: this()
{
UpdateFrom(table);
}
/// <summary>
/// Creates a new Probe_result from a Proxy_Probe_result.
/// </summary>
/// <param name="proxy"></param>
public Probe_result(Proxy_Probe_result proxy)
{
UpdateFrom(proxy);
}
#endregion
/// <summary>
/// Updates each field of this instance with the value of
/// the corresponding field of a given Probe_result.
/// </summary>
public override void UpdateFrom(Probe_result record)
{
configuration = record.configuration;
complete = record.complete;
sr = record.sr;
extra_info = record.extra_info;
}
internal void UpdateFrom(Proxy_Probe_result proxy)
{
configuration = proxy.configuration == null ? null : Maps.convert_from_proxy_string_string(proxy.configuration);
complete = (bool)proxy.complete;
sr = proxy.sr == null ? null : new Sr_stat(proxy.sr);
extra_info = proxy.extra_info == null ? null : Maps.convert_from_proxy_string_string(proxy.extra_info);
}
/// <summary>
/// Given a Hashtable with field-value pairs, it updates the fields of this Probe_result
/// 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("configuration"))
configuration = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "configuration"));
if (table.ContainsKey("complete"))
complete = Marshalling.ParseBool(table, "complete");
if (table.ContainsKey("sr"))
sr = (Sr_stat)Marshalling.convertStruct(typeof(Sr_stat), Marshalling.ParseHashTable(table, "sr"));;
if (table.ContainsKey("extra_info"))
extra_info = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "extra_info"));
}
public Proxy_Probe_result ToProxy()
{
Proxy_Probe_result result_ = new Proxy_Probe_result();
result_.configuration = Maps.convert_to_proxy_string_string(configuration);
result_.complete = complete;
result_.sr = sr == null ? null : sr.ToProxy();
result_.extra_info = Maps.convert_to_proxy_string_string(extra_info);
return result_;
}
public bool DeepEquals(Probe_result other)
{
if (ReferenceEquals(null, other))
return false;
if (ReferenceEquals(this, other))
return true;
return Helper.AreEqual2(this._configuration, other._configuration) &&
Helper.AreEqual2(this._complete, other._complete) &&
Helper.AreEqual2(this._sr, other._sr) &&
Helper.AreEqual2(this._extra_info, other._extra_info);
}
public override string SaveChanges(Session session, string opaqueRef, Probe_result server)
{
if (opaqueRef == null)
{
System.Diagnostics.Debug.Assert(false, "Cannot create instances of this type on the server");
return "";
}
else
{
throw new InvalidOperationException("This type has no read/write properties");
}
}
/// <summary>
/// Plugin-specific configuration which describes where and how to locate the storage repository. This may include the physical block device name, a remote NFS server and path or an RBD storage pool.
/// Experimental. First published in XenServer 7.5.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> configuration
{
get { return _configuration; }
set
{
if (!Helper.AreEqual(value, _configuration))
{
_configuration = value;
NotifyPropertyChanged("configuration");
}
}
}
private Dictionary<string, string> _configuration = new Dictionary<string, string>() {};
/// <summary>
/// True if this configuration is complete and can be used to call SR.create. False if it requires further iterative calls to SR.probe, to potentially narrow down on a configuration that can be used.
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual bool complete
{
get { return _complete; }
set
{
if (!Helper.AreEqual(value, _complete))
{
_complete = value;
NotifyPropertyChanged("complete");
}
}
}
private bool _complete;
/// <summary>
/// Existing SR found for this configuration
/// Experimental. First published in XenServer 7.5.
/// </summary>
public virtual Sr_stat sr
{
get { return _sr; }
set
{
if (!Helper.AreEqual(value, _sr))
{
_sr = value;
NotifyPropertyChanged("sr");
}
}
}
private Sr_stat _sr;
/// <summary>
/// Additional plugin-specific information about this configuration, that might be of use for an API user. This can for example include the LUN or the WWPN.
/// Experimental. First published in XenServer 7.5.
/// </summary>
[JsonConverter(typeof(StringStringMapConverter))]
public virtual Dictionary<string, string> extra_info
{
get { return _extra_info; }
set
{
if (!Helper.AreEqual(value, _extra_info))
{
_extra_info = value;
NotifyPropertyChanged("extra_info");
}
}
}
private Dictionary<string, string> _extra_info = new Dictionary<string, string>() {};
}
}
| |
/* ====================================================================
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
{
using System;
using System.Text;
using NPOI.HSSF.Record.CF;
using NPOI.HSSF.Record.Common;
using NPOI.HSSF.UserModel;
using NPOI.SS.Formula;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.Util;
using ExtendedColorR = NPOI.HSSF.Record.Common.ExtendedColor;
/**
* Conditional Formatting v12 Rule Record (0x087A).
*
* <p>This is for newer-style Excel conditional formattings,
* from Excel 2007 onwards.
*
* <p>{@link CFRuleRecord} is used where the condition type is
* {@link #CONDITION_TYPE_CELL_VALUE_IS} or {@link #CONDITION_TYPE_FORMULA},
* this is only used for the other types
*/
public class CFRule12Record : CFRuleBase, IFutureRecord, ICloneable
{
public static short sid = 0x087A;
private FtrHeader futureHeader;
private int ext_formatting_length;
private byte[] ext_formatting_data;
private Formula formula_scale;
private byte ext_opts;
private int priority;
private int template_type;
private byte template_param_length;
private byte[] template_params;
private DataBarFormatting data_bar;
private IconMultiStateFormatting multistate;
private ColorGradientFormatting color_gradient;
// TODO Parse this, see #58150
private byte[] filter_data;
/** Creates new CFRuleRecord */
private CFRule12Record(byte conditionType, byte comparisonOperation)
: base(conditionType, comparisonOperation)
{
SetDefaults();
}
private CFRule12Record(byte conditionType, byte comparisonOperation, Ptg[] formula1, Ptg[] formula2, Ptg[] formulaScale)
: base(conditionType, comparisonOperation, formula1, formula2)
{
SetDefaults();
this.formula_scale = Formula.Create(formulaScale);
}
private void SetDefaults() {
futureHeader = new FtrHeader();
futureHeader.RecordType = (/*setter*/sid);
ext_formatting_length = 0;
ext_formatting_data = new byte[4];
formula_scale = Formula.Create(Ptg.EMPTY_PTG_ARRAY);
ext_opts = 0;
priority = 0;
template_type = ConditionType;
template_param_length = 16;
template_params = new byte[template_param_length];
}
/**
* Creates a new comparison operation rule
*/
public static CFRule12Record Create(HSSFSheet sheet, String formulaText) {
Ptg[] formula1 = ParseFormula(formulaText, sheet);
return new CFRule12Record(CONDITION_TYPE_FORMULA, ComparisonOperator.NO_COMPARISON,
formula1, null, null);
}
/**
* Creates a new comparison operation rule
*/
public static CFRule12Record Create(HSSFSheet sheet, byte comparisonOperation,
String formulaText1, String formulaText2) {
Ptg[] formula1 = ParseFormula(formulaText1, sheet);
Ptg[] formula2 = ParseFormula(formulaText2, sheet);
return new CFRule12Record(CONDITION_TYPE_CELL_VALUE_IS, comparisonOperation,
formula1, formula2, null);
}
/**
* Creates a new comparison operation rule
*/
public static CFRule12Record Create(HSSFSheet sheet, byte comparisonOperation,
String formulaText1, String formulaText2, String formulaTextScale) {
Ptg[] formula1 = ParseFormula(formulaText1, sheet);
Ptg[] formula2 = ParseFormula(formulaText2, sheet);
Ptg[] formula3 = ParseFormula(formulaTextScale, sheet);
return new CFRule12Record(CONDITION_TYPE_CELL_VALUE_IS, comparisonOperation,
formula1, formula2, formula3);
}
/**
* Creates a new Data Bar formatting
*/
public static CFRule12Record Create(HSSFSheet sheet, ExtendedColorR color) {
CFRule12Record r = new CFRule12Record(CONDITION_TYPE_DATA_BAR,
ComparisonOperator.NO_COMPARISON);
DataBarFormatting dbf = r.CreateDataBarFormatting();
dbf.Color = (/*setter*/color);
dbf.PercentMin = (/*setter*/(byte)0);
dbf.PercentMax = (/*setter*/(byte)100);
DataBarThreshold min = new DataBarThreshold();
min.SetType(RangeType.MIN.id);
dbf.ThresholdMin = (/*setter*/min);
DataBarThreshold max = new DataBarThreshold();
max.SetType(RangeType.MAX.id);
dbf.ThresholdMax = (/*setter*/max);
return r;
}
/**
* Creates a new Icon Set / Multi-State formatting
*/
public static CFRule12Record Create(HSSFSheet sheet, IconSet iconSet) {
Threshold[] ts = new Threshold[iconSet.num];
for (int i = 0; i < ts.Length; i++) {
ts[i] = new IconMultiStateThreshold();
}
CFRule12Record r = new CFRule12Record(CONDITION_TYPE_ICON_SET,
ComparisonOperator.NO_COMPARISON);
IconMultiStateFormatting imf = r.CreateMultiStateFormatting();
imf.IconSet = (/*setter*/iconSet);
imf.Thresholds = (/*setter*/ts);
return r;
}
/**
* Creates a new Color Scale / Color Gradient formatting
*/
public static CFRule12Record CreateColorScale(HSSFSheet sheet) {
int numPoints = 3;
ExtendedColorR[] colors = new ExtendedColorR[numPoints];
ColorGradientThreshold[] ts = new ColorGradientThreshold[numPoints];
for (int i = 0; i < ts.Length; i++) {
ts[i] = new ColorGradientThreshold();
colors[i] = new ExtendedColorR();
}
CFRule12Record r = new CFRule12Record(CONDITION_TYPE_COLOR_SCALE,
ComparisonOperator.NO_COMPARISON);
ColorGradientFormatting cgf = r.CreateColorGradientFormatting();
cgf.NumControlPoints = (/*setter*/numPoints);
cgf.Thresholds = (/*setter*/ts);
cgf.Colors = (/*setter*/colors);
return r;
}
public CFRule12Record(RecordInputStream in1) {
futureHeader = new FtrHeader(in1);
ConditionType = ((byte)in1.ReadByte());
ComparisonOperation = ((byte)in1.ReadByte());
int field_3_formula1_len = in1.ReadUShort();
int field_4_formula2_len = in1.ReadUShort();
ext_formatting_length = in1.ReadInt();
ext_formatting_data = new byte[0];
if (ext_formatting_length == 0) {
// 2 bytes reserved
in1.ReadUShort();
} else {
int len = ReadFormatOptions(in1);
if (len < ext_formatting_length) {
ext_formatting_data = new byte[ext_formatting_length - len];
in1.ReadFully(ext_formatting_data);
}
}
Formula1 = (Formula.Read(field_3_formula1_len, in1));
Formula2 = (Formula.Read(field_4_formula2_len, in1));
int formula_scale_len = in1.ReadUShort();
formula_scale = Formula.Read(formula_scale_len, in1);
ext_opts = (byte)in1.ReadByte();
priority = in1.ReadUShort();
template_type = in1.ReadUShort();
template_param_length = (byte)in1.ReadByte();
if (template_param_length == 0 || template_param_length == 16) {
template_params = new byte[template_param_length];
in1.ReadFully(template_params);
} else {
//logger.Log(POILogger.WARN, "CF Rule v12 template params length should be 0 or 16, found " + template_param_length);
in1.ReadRemainder();
}
byte type = ConditionType;
if (type == CONDITION_TYPE_COLOR_SCALE) {
color_gradient = new ColorGradientFormatting(in1);
} else if (type == CONDITION_TYPE_DATA_BAR) {
data_bar = new DataBarFormatting(in1);
} else if (type == CONDITION_TYPE_FILTER) {
filter_data = in1.ReadRemainder();
} else if (type == CONDITION_TYPE_ICON_SET) {
multistate = new IconMultiStateFormatting(in1);
}
}
public bool ContainsDataBarBlock() {
return (data_bar != null);
}
public DataBarFormatting DataBarFormatting
{
get { return data_bar; }
}
public DataBarFormatting CreateDataBarFormatting() {
if (data_bar != null) return data_bar;
// Convert, Setup and return
ConditionType = (CONDITION_TYPE_DATA_BAR);
data_bar = new DataBarFormatting();
return data_bar;
}
public bool ContainsMultiStateBlock() {
return (multistate != null);
}
public IconMultiStateFormatting MultiStateFormatting
{
get { return multistate; }
}
public IconMultiStateFormatting CreateMultiStateFormatting() {
if (multistate != null) return multistate;
// Convert, Setup and return
ConditionType = (CONDITION_TYPE_ICON_SET);
multistate = new IconMultiStateFormatting();
return multistate;
}
public bool ContainsColorGradientBlock() {
return (color_gradient != null);
}
public ColorGradientFormatting ColorGradientFormatting
{
get { return color_gradient; }
}
public ColorGradientFormatting CreateColorGradientFormatting() {
if (color_gradient != null) return color_gradient;
// Convert, Setup and return
ConditionType = (CONDITION_TYPE_COLOR_SCALE);
color_gradient = new ColorGradientFormatting();
return color_gradient;
}
/**
* Get the stack of the scale expression as a list
*
* @return list of tokens (casts stack to a list and returns it!)
* this method can return null is we are unable to create Ptgs from
* existing excel file
* callers should check for null!
*/
public Ptg[] ParsedExpressionScale
{
get
{
return formula_scale.Tokens;
}
set
{
formula_scale = Formula.Create(value);
}
}
public override short Sid
{
get
{
return sid;
}
}
/**
* called by the class that is responsible for writing this sucker.
* Subclasses should implement this so that their data is passed back in a
* byte array.
*
* @param out the stream to write to
*/
public override void Serialize(ILittleEndianOutput out1) {
futureHeader.Serialize(out1);
int formula1Len = GetFormulaSize(Formula1);
int formula2Len = GetFormulaSize(Formula2);
out1.WriteByte(ConditionType);
out1.WriteByte(ComparisonOperation);
out1.WriteShort(formula1Len);
out1.WriteShort(formula2Len);
// TODO Update ext_formatting_length
if (ext_formatting_length == 0) {
out1.WriteInt(0);
out1.WriteShort(0);
} else {
out1.WriteInt(ext_formatting_length);
SerializeFormattingBlock(out1);
out1.Write(ext_formatting_data);
}
Formula1.SerializeTokens(out1);
Formula2.SerializeTokens(out1);
out1.WriteShort(GetFormulaSize(formula_scale));
formula_scale.SerializeTokens(out1);
out1.WriteByte(ext_opts);
out1.WriteShort(priority);
out1.WriteShort(template_type);
out1.WriteByte(template_param_length);
out1.Write(template_params);
byte type = ConditionType;
if (type == CONDITION_TYPE_COLOR_SCALE) {
color_gradient.Serialize(out1);
} else if (type == CONDITION_TYPE_DATA_BAR) {
data_bar.Serialize(out1);
} else if (type == CONDITION_TYPE_FILTER) {
out1.Write(filter_data);
} else if (type == CONDITION_TYPE_ICON_SET) {
multistate.Serialize(out1);
}
}
protected override int DataSize
{
get
{
int len = FtrHeader.GetDataSize() + 6;
if (ext_formatting_length == 0)
{
len += 6;
}
else
{
len += 4 + FormattingBlockSize + ext_formatting_data.Length;
}
len += GetFormulaSize(Formula1);
len += GetFormulaSize(Formula2);
len += 2 + GetFormulaSize(formula_scale);
len += 6 + template_params.Length;
byte type = ConditionType;
if (type == CONDITION_TYPE_COLOR_SCALE)
{
len += color_gradient.DataLength;
}
else if (type == CONDITION_TYPE_DATA_BAR)
{
len += data_bar.DataLength;
}
else if (type == CONDITION_TYPE_FILTER)
{
len += filter_data.Length;
}
else if (type == CONDITION_TYPE_ICON_SET)
{
len += multistate.DataLength;
}
return len;
}
}
public override String ToString() {
StringBuilder buffer = new StringBuilder();
buffer.Append("[CFRULE12]\n");
buffer.Append(" .condition_type=").Append(ConditionType).Append("\n");
buffer.Append(" .dxfn12_length =0x").Append(HexDump.ToHex(ext_formatting_length)).Append("\n");
buffer.Append(" .option_flags =0x").Append(HexDump.ToHex(Options)).Append("\n");
if (ContainsFontFormattingBlock) {
buffer.Append(_fontFormatting.ToString()).Append("\n");
}
if (ContainsBorderFormattingBlock) {
buffer.Append(_borderFormatting.ToString()).Append("\n");
}
if (ContainsPatternFormattingBlock) {
buffer.Append(_patternFormatting.ToString()).Append("\n");
}
buffer.Append(" .dxfn12_ext=").Append(HexDump.ToHex(ext_formatting_data)).Append("\n");
buffer.Append(" .Formula_1 =").Append(Arrays.ToString(Formula1.Tokens)).Append("\n");
buffer.Append(" .Formula_2 =").Append(Arrays.ToString(Formula2.Tokens)).Append("\n");
buffer.Append(" .Formula_S =").Append(Arrays.ToString(formula_scale.Tokens)).Append("\n");
buffer.Append(" .ext_opts =").Append(ext_opts).Append("\n");
buffer.Append(" .priority =").Append(priority).Append("\n");
buffer.Append(" .template_type =").Append(template_type).Append("\n");
buffer.Append(" .template_params=").Append(HexDump.ToHex(template_params)).Append("\n");
buffer.Append(" .filter_data =").Append(HexDump.ToHex(filter_data)).Append("\n");
if (color_gradient != null) {
buffer.Append(color_gradient);
}
if (multistate != null) {
buffer.Append(multistate);
}
if (data_bar != null) {
buffer.Append(data_bar);
}
buffer.Append("[/CFRULE12]\n");
return buffer.ToString();
}
public override Object Clone() {
CFRule12Record rec = new CFRule12Record(ConditionType, ComparisonOperation);
rec.futureHeader.AssociatedRange = (/*setter*/futureHeader.AssociatedRange.Copy());
base.CopyTo(rec);
rec.ext_formatting_length = ext_formatting_length;
rec.ext_formatting_data = new byte[ext_formatting_length];
Array.Copy(ext_formatting_data, 0, rec.ext_formatting_data, 0, ext_formatting_length);
rec.formula_scale = formula_scale.Copy();
rec.ext_opts = ext_opts;
rec.priority = priority;
rec.template_type = template_type;
rec.template_param_length = template_param_length;
rec.template_params = new byte[template_param_length];
Array.Copy(template_params, 0, rec.template_params, 0, template_param_length);
if (color_gradient != null) {
rec.color_gradient = (ColorGradientFormatting)color_gradient.Clone();
}
if (multistate != null) {
rec.multistate = (IconMultiStateFormatting)multistate.Clone();
}
if (data_bar != null) {
rec.data_bar = (DataBarFormatting)data_bar.Clone();
}
if (filter_data != null) {
rec.filter_data = new byte[filter_data.Length];
Array.Copy(filter_data, 0, rec.filter_data, 0, filter_data.Length);
}
return rec;
}
public short GetFutureRecordType() {
return futureHeader.RecordType;
}
public FtrHeader GetFutureHeader() {
return futureHeader;
}
public CellRangeAddress GetAssociatedRange() {
return futureHeader.AssociatedRange;
}
}
}
| |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// A collection of utility functions for dealing with Type information.
/// </summary>
internal static class TypeUtils
{
/// <summary>
/// The assembly name of the core Orleans assembly.
/// </summary>
private static readonly AssemblyName OrleansCoreAssembly = typeof(IGrain).GetTypeInfo().Assembly.GetName();
private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>();
private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>();
private static string GetSimpleNameHandleArray(Type t, Language language)
{
if (t.IsArray && language == Language.VisualBasic)
return t.Name.Replace('[', '(').Replace(']', ')');
return t.Name;
}
private static string GetSimpleNameHandleArray(TypeInfo typeInfo, Language language)
{
return GetSimpleNameHandleArray(typeInfo.AsType(), language);
}
public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null, Language language = Language.CSharp)
{
return GetSimpleTypeName(t.GetTypeInfo(), fullName, language);
}
public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null, Language language = Language.CSharp)
{
if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate)
{
if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType)
{
return GetTemplatedName(
GetUntemplatedTypeName(typeInfo.DeclaringType.Name),
typeInfo.DeclaringType,
typeInfo.GetGenericArguments(),
_ => true,
language) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
return GetTemplatedName(typeInfo.DeclaringType, language: language) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
var type = typeInfo.AsType();
if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type, language) : GetSimpleNameHandleArray(typeInfo, language));
return fullName != null && fullName(type) ? GetFullName(type, language) : GetSimpleNameHandleArray(typeInfo, language);
}
public static string GetUntemplatedTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static string GetSimpleTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('[');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static bool IsConcreteTemplateType(Type t)
{
if (t.GetTypeInfo().IsGenericType) return true;
return t.IsArray && IsConcreteTemplateType(t.GetElementType());
}
public static string GetTemplatedName(Type t, Predicate<Type> fullName = null, Language language = Language.CSharp)
{
if (fullName == null)
fullName = _ => true; // default to full type names
var typeInfo = t.GetTypeInfo();
if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName, language), t, typeInfo.GetGenericArguments(), fullName, language);
if (t.IsArray)
{
bool isVB = language == Language.VisualBasic;
return GetTemplatedName(t.GetElementType(), fullName)
+ (isVB ? "(" : "[")
+ new string(',', t.GetArrayRank() - 1)
+ (isVB ? ")" : "]");
}
return GetSimpleTypeName(typeInfo, fullName, language);
}
public static bool IsConstructedGenericType(this TypeInfo typeInfo)
{
// is there an API that returns this info without converting back to type already?
return typeInfo.AsType().IsConstructedGenericType;
}
internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types)
{
return types.Select(t => t.GetTypeInfo());
}
public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName, Language language = Language.CSharp)
{
var typeInfo = t.GetTypeInfo();
if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName;
bool isVB = language == Language.VisualBasic;
string s = baseName;
s += isVB ? "(Of " : "<";
s += GetGenericTypeArgs(genericArguments, fullName, language);
s += isVB ? ")" : ">";
return s;
}
public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName, Language language = Language.CSharp)
{
string s = string.Empty;
bool first = true;
foreach (var genericParameter in args)
{
if (!first)
{
s += ",";
}
if (!genericParameter.GetTypeInfo().IsGenericType)
{
s += GetSimpleTypeName(genericParameter, fullName, language);
}
else
{
s += GetTemplatedName(genericParameter, fullName, language);
}
first = false;
}
return s;
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null, Language language = Language.CSharp)
{
if (fullName == null)
fullName = tt => true;
return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively, language);
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false, Language language = Language.CSharp)
{
if (typeInfo.IsGenericType)
{
return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName, language);
}
var t = typeInfo.AsType();
if (fullName != null && fullName(t) == true)
{
return t.FullName;
}
return t.Name;
}
public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null, Language language = Language.CSharp)
{
if (fullName == null)
fullName = tt => false;
if (!typeInfo.IsGenericType) return baseName;
bool isVB = language == Language.VisualBasic;
string s = baseName;
s += isVB ? "(Of " : "<";
bool first = true;
foreach (var genericParameter in typeInfo.GetGenericArguments())
{
if (!first)
{
s += ",";
}
var genericParameterTypeInfo = genericParameter.GetTypeInfo();
if (applyRecursively && genericParameterTypeInfo.IsGenericType)
{
s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively, language: language);
}
else
{
s += genericParameter.FullName == null || !fullName(genericParameter)
? genericParameter.Name
: genericParameter.FullName;
}
first = false;
}
s += isVB ? ")" : ">";
return s;
}
public static string GetRawClassName(string baseName, Type t)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName;
}
public static string GetRawClassName(string typeName)
{
int i = typeName.IndexOf('[');
return i <= 0 ? typeName : typeName.Substring(0, i);
}
public static Type[] GenericTypeArgsFromClassName(string className)
{
return GenericTypeArgsFromArgsString(GenericTypeArgsString(className));
}
public static Type[] GenericTypeArgsFromArgsString(string genericArgs)
{
if (string.IsNullOrEmpty(genericArgs)) return new Type[] { };
var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments
return InnerGenericTypeArgs(genericTypeDef);
}
private static Type[] InnerGenericTypeArgs(string className)
{
var typeArgs = new List<Type>();
var innerTypes = GetInnerTypes(className);
foreach (var innerType in innerTypes)
{
if (innerType.StartsWith("[[")) // Resolve and load generic types recursively
{
InnerGenericTypeArgs(GenericTypeArgsString(innerType));
string genericTypeArg = className.Trim('[', ']');
typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]")));
}
else
{
string nonGenericTypeArg = innerType.Trim('[', ']');
typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]")));
}
}
return typeArgs.ToArray();
}
private static string[] GetInnerTypes(string input)
{
// Iterate over strings of length 2 positionwise.
var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i });
var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos });
var results = new List<string>();
int startPos = -1;
int endPos = -1;
int endTokensNeeded = 0;
string curStartToken = "";
string curEndToken = "";
var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones
foreach (var candidate in candidatesWithPositions)
{
if (startPos == -1)
{
foreach (var token in tokenPairs)
{
if (candidate.Str.StartsWith(token.Start))
{
curStartToken = token.Start;
curEndToken = token.End;
startPos = candidate.Pos;
break;
}
}
}
if (curStartToken != "" && candidate.Str.StartsWith(curStartToken))
endTokensNeeded++;
if (curEndToken != "" && candidate.Str.EndsWith(curEndToken))
{
endPos = candidate.Pos;
endTokensNeeded--;
}
if (endTokensNeeded == 0 && startPos != -1)
{
results.Add(input.Substring(startPos, endPos - startPos + 2));
startPos = -1;
curStartToken = "";
}
}
return results.ToArray();
}
public static string GenericTypeArgsString(string className)
{
int startIndex = className.IndexOf('[');
int endIndex = className.LastIndexOf(']');
return className.Substring(startIndex + 1, endIndex - startIndex - 1);
}
public static bool IsGenericClass(string name)
{
return name.Contains("`") || name.Contains("[");
}
public static string GetFullName(TypeInfo typeInfo, Language language = Language.CSharp)
{
if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo));
return GetFullName(typeInfo.AsType());
}
public static string GetFullName(Type t, Language language = Language.CSharp)
{
if (t == null) throw new ArgumentNullException("t");
if (t.IsNested && !t.IsGenericParameter)
{
return t.Namespace + "." + t.DeclaringType.Name + "." + GetSimpleNameHandleArray(t, language);
}
if (t.IsArray)
{
bool isVB = language == Language.VisualBasic;
return GetFullName(t.GetElementType(), language)
+ (isVB ? "(" : "[")
+ new string(',', t.GetArrayRank() - 1)
+ (isVB ? ")" : "]");
}
return t.FullName ?? (t.IsGenericParameter ? GetSimpleNameHandleArray(t, language) : t.Namespace + "." + GetSimpleNameHandleArray(t, language));
}
/// <summary>
/// Returns all fields of the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>All fields of the specified type.</returns>
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
const BindingFlags AllFields =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
var current = type;
while ((current != typeof(object)) && (current != null))
{
var fields = current.GetFields(AllFields);
foreach (var field in fields)
{
yield return field;
}
current = current.GetTypeInfo().BaseType;
}
}
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
public static bool IsGrainClass(Type type)
{
var grainType = typeof(Grain);
var grainChevronType = typeof(Grain<>);
if (type.Assembly.ReflectionOnly)
{
grainType = ToReflectionOnlyType(grainType);
grainChevronType = ToReflectionOnlyType(grainChevronType);
}
if (grainType == type || grainChevronType == type) return false;
if (!grainType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsSystemTargetClass(Type type)
{
Type systemTargetType;
if (!TryResolveType("Orleans.Runtime.SystemTarget", out systemTargetType)) return false;
var systemTargetInterfaceType = typeof(ISystemTarget);
var systemTargetBaseInterfaceType = typeof(ISystemTargetBase);
if (type.Assembly.ReflectionOnly)
{
systemTargetType = ToReflectionOnlyType(systemTargetType);
systemTargetInterfaceType = ToReflectionOnlyType(systemTargetInterfaceType);
systemTargetBaseInterfaceType = ToReflectionOnlyType(systemTargetBaseInterfaceType);
}
if (!systemTargetInterfaceType.IsAssignableFrom(type) ||
!systemTargetBaseInterfaceType.IsAssignableFrom(type) ||
!systemTargetType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain)
{
complaints = null;
if (!IsGrainClass(type)) return false;
if (!type.GetTypeInfo().IsAbstract) return true;
complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null;
return false;
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints)
{
return IsConcreteGrainClass(type, out complaints, complain: true);
}
public static bool IsConcreteGrainClass(Type type)
{
IEnumerable<string> complaints;
return IsConcreteGrainClass(type, out complaints, complain: false);
}
public static bool IsGeneratedType(Type type)
{
return TypeHasAttribute(type, typeof(GeneratedAttribute));
}
/// <summary>
/// Returns true if the provided <paramref name="type"/> is in any of the provided
/// <paramref name="namespaces"/>, false otherwise.
/// </summary>
/// <param name="type">The type to check.</param>
/// <param name="namespaces"></param>
/// <returns>
/// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false
/// otherwise.
/// </returns>
public static bool IsInNamespace(Type type, List<string> namespaces)
{
if (type.Namespace == null)
{
return false;
}
foreach (var ns in namespaces)
{
if (ns.Length > type.Namespace.Length)
{
continue;
}
// If the candidate namespace is a prefix of the type's namespace, return true.
if (type.Namespace.StartsWith(ns, StringComparison.Ordinal)
&& (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.'))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </returns>
public static bool HasAllSerializationMethods(Type type)
{
// Check if the type has any of the serialization methods.
var hasCopier = false;
var hasSerializer = false;
var hasDeserializer = false;
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public))
{
hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null;
hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null;
hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null;
}
var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer;
return hasAllSerializationMethods;
}
public static bool IsGrainMethodInvokerType(Type type)
{
var generalType = typeof(IGrainMethodInvoker);
if (type.Assembly.ReflectionOnly)
{
generalType = ToReflectionOnlyType(generalType);
}
return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute));
}
public static Type ResolveType(string fullName)
{
return CachedTypeResolver.Instance.ResolveType(fullName);
}
public static bool TryResolveType(string fullName, out Type type)
{
return CachedTypeResolver.Instance.TryResolveType(fullName, out type);
}
public static Type ResolveReflectionOnlyType(string assemblyQualifiedName)
{
return CachedReflectionOnlyTypeResolver.Instance.ResolveType(assemblyQualifiedName);
}
public static Type ToReflectionOnlyType(Type type)
{
return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName);
}
public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, Logger logger)
{
return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type));
}
public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, Logger logger)
{
try
{
return assembly.DefinedTypes;
}
catch (Exception exception)
{
if (logger.IsWarning)
{
var message =
string.Format(
"AssemblyLoader encountered an exception loading types from assembly '{0}': {1}",
assembly.FullName,
exception);
logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception);
}
return Enumerable.Empty<TypeInfo>();
}
}
public static IEnumerable<Type> GetTypes(Predicate<Type> whereFunc, Logger logger)
{
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in assemblies)
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc, logger);
result.AddRange(types);
}
return result;
}
public static IEnumerable<Type> GetTypes(List<string> assemblies, Predicate<Type> whereFunc, Logger logger)
{
var currentAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var result = new List<Type>();
foreach (var assembly in currentAssemblies.Where(loaded => !loaded.IsDynamic && assemblies.Contains(loaded.Location)))
{
// there's no point in evaluating nested private types-- one of them fails to coerce to a reflection-only type anyhow.
var types = GetTypes(assembly, whereFunc, logger);
result.AddRange(types);
}
return result;
}
/// <summary>
/// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.
/// </summary>
/// <param name="methodInfo">The method.</param>
/// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns>
public static bool IsGrainMethod(MethodInfo methodInfo)
{
if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info");
if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null)
{
return false;
}
return methodInfo.DeclaringType.GetTypeInfo().IsInterface
&& typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType);
}
public static bool TypeHasAttribute(Type type, Type attribType)
{
if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly)
{
type = ToReflectionOnlyType(type);
attribType = ToReflectionOnlyType(attribType);
// we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type.
return CustomAttributeData.GetCustomAttributes(type).Any(
attrib => attribType.IsAssignableFrom(attrib.AttributeType));
}
return TypeHasAttribute(type.GetTypeInfo(), attribType);
}
public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType)
{
return typeInfo.GetCustomAttributes(attribType, true).Any();
}
/// <summary>
/// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </summary>
/// <param name="type">
/// The grain type.
/// </param>
/// <returns>
/// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </returns>
public static string GetSuitableClassName(Type type)
{
return GetClassNameFromInterfaceName(type.GetUnadornedTypeName());
}
/// <summary>
/// Returns a class-like version of <paramref name="interfaceName"/>.
/// </summary>
/// <param name="interfaceName">
/// The interface name.
/// </param>
/// <returns>
/// A class-like version of <paramref name="interfaceName"/>.
/// </returns>
public static string GetClassNameFromInterfaceName(string interfaceName)
{
string cleanName;
if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase))
{
cleanName = interfaceName.Substring(1);
}
else
{
cleanName = interfaceName;
}
return cleanName;
}
/// <summary>
/// Returns the non-generic type name without any special characters.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The non-generic type name without any special characters.
/// </returns>
public static string GetUnadornedTypeName(this Type type)
{
var index = type.Name.IndexOf('`');
// An ampersand can appear as a suffix to a by-ref type.
return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&');
}
/// <summary>
/// Returns the non-generic method name without any special characters.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The non-generic method name without any special characters.
/// </returns>
public static string GetUnadornedMethodName(this MethodInfo method)
{
var index = method.Name.IndexOf('`');
return index > 0 ? method.Name.Substring(0, index) : method.Name;
}
/// <summary>
/// Returns a string representation of <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="includeNamespace">
/// A value indicating whether or not to include the namespace name.
/// </param>
/// <returns>
/// A string representation of the <paramref name="type"/>.
/// </returns>
public static string GetParseableName(this Type type, TypeFormattingOptions options = null)
{
options = options ?? new TypeFormattingOptions();
return ParseableNameCache.GetOrAdd(
Tuple.Create(type, options),
_ =>
{
var builder = new StringBuilder();
var typeInfo = type.GetTypeInfo();
GetParseableName(
type,
builder,
new Queue<Type>(
typeInfo.IsGenericTypeDefinition
? typeInfo.GetGenericArguments()
: typeInfo.GenericTypeArguments),
options);
return builder.ToString();
});
}
/// <summary>
/// Returns a string representation of <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="builder">
/// The <see cref="StringBuilder"/> to append results to.
/// </param>
/// <param name="typeArguments">
/// The type arguments of <paramref name="type"/>.
/// </param>
/// <param name="options">
/// The type formatting options.
/// </param>
private static void GetParseableName(
Type type,
StringBuilder builder,
Queue<Type> typeArguments,
TypeFormattingOptions options)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsArray)
{
builder.AppendFormat(
"{0}[{1}]",
typeInfo.GetElementType().GetParseableName(options),
string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ',')));
return;
}
if (typeInfo.IsGenericParameter)
{
if (options.IncludeGenericTypeParameters)
{
builder.Append(type.GetUnadornedTypeName());
}
return;
}
if (typeInfo.DeclaringType != null)
{
// This is not the root type.
GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options);
builder.Append(options.NestedTypeSeparator);
}
else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace)
{
// This is the root type, so include the namespace.
var namespaceName = type.Namespace;
if (options.NestedTypeSeparator != '.')
{
namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator);
}
if (options.IncludeGlobal)
{
builder.AppendFormat("global::");
}
builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator);
}
if (type.IsConstructedGenericType)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix;
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(generic => GetParseableName(generic, options)));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else if (typeInfo.IsGenericTypeDefinition)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = type.GetUnadornedTypeName() + options.NameSuffix;
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else
{
builder.Append(EscapeIdentifier(type.GetUnadornedTypeName() + options.NameSuffix));
}
}
/// <summary>
/// Returns the namespaces of the specified types.
/// </summary>
/// <param name="types">
/// The types to include.
/// </param>
/// <returns>
/// The namespaces of the specified types.
/// </returns>
public static IEnumerable<string> GetNamespaces(params Type[] types)
{
return types.Select(type => "global::" + type.Namespace).Distinct();
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method<T>(Expression<Func<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method<T>(Expression<Action<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.
/// </returns>
public static string GetNamespaceOrEmpty(this Type type)
{
if (type == null || string.IsNullOrEmpty(type.Namespace))
{
return string.Empty;
}
return type.Namespace;
}
/// <summary>
/// Returns the types referenced by the provided <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="includeMethods">
/// Whether or not to include the types referenced in the methods of this type.
/// </param>
/// <returns>
/// The types referenced by the provided <paramref name="type"/>.
/// </returns>
public static IList<Type> GetTypes(this Type type, bool includeMethods = false)
{
List<Type> results;
var key = Tuple.Create(type, includeMethods);
if (!ReferencedTypes.TryGetValue(key, out results))
{
results = GetTypes(type, includeMethods, null).ToList();
ReferencedTypes.TryAdd(key, results);
}
return results;
}
/// <summary>
/// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns>
internal static bool IsOrleansOrReferencesOrleans(Assembly assembly)
{
// We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans,
// but we want a strong assembly match for the Orleans binary itself
// (so we don't load 2 different versions of Orleans by mistake)
return DoReferencesContain(assembly.GetReferencedAssemblies(), OrleansCoreAssembly)
|| string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal);
}
/// <summary>
/// Returns a value indicating whether or not the specified references contain the provided assembly name.
/// </summary>
/// <param name="references">The references.</param>
/// <param name="assemblyName">The assembly name.</param>
/// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns>
private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName)
{
if (references.Count == 0)
{
return false;
}
return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal));
}
/// <summary>
/// Returns the types referenced by the provided <paramref name="type"/>.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <param name="includeMethods">
/// Whether or not to include the types referenced in the methods of this type.
/// </param>
/// <returns>
/// The types referenced by the provided <paramref name="type"/>.
/// </returns>
private static IEnumerable<Type> GetTypes(
this Type type,
bool includeMethods,
HashSet<Type> exclude)
{
exclude = exclude ?? new HashSet<Type>();
if (!exclude.Add(type))
{
yield break;
}
yield return type;
if (type.IsArray)
{
foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude))
{
yield return elementType;
}
}
if (type.IsConstructedGenericType)
{
foreach (var genericTypeArgument in
type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude)))
{
yield return genericTypeArgument;
}
}
if (!includeMethods)
{
yield break;
}
foreach (var method in type.GetMethods())
{
foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude))
{
yield return referencedType;
}
foreach (var parameter in method.GetParameters())
{
foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude))
{
yield return referencedType;
}
}
}
}
private static string EscapeIdentifier(string identifier)
{
switch (identifier)
{
case "abstract":
case "add":
case "base":
case "bool":
case "break":
case "byte":
case "case":
case "catch":
case "char":
case "checked":
case "class":
case "const":
case "continue":
case "decimal":
case "default":
case "delegate":
case "do":
case "double":
case "else":
case "enum":
case "event":
case "explicit":
case "extern":
case "false":
case "finally":
case "fixed":
case "float":
case "for":
case "foreach":
case "get":
case "goto":
case "if":
case "implicit":
case "in":
case "int":
case "interface":
case "internal":
case "lock":
case "long":
case "namespace":
case "new":
case "null":
case "object":
case "operator":
case "out":
case "override":
case "params":
case "partial":
case "private":
case "protected":
case "public":
case "readonly":
case "ref":
case "remove":
case "return":
case "sbyte":
case "sealed":
case "set":
case "short":
case "sizeof":
case "static":
case "string":
case "struct":
case "switch":
case "this":
case "throw":
case "true":
case "try":
case "typeof":
case "uint":
case "ulong":
case "unsafe":
case "ushort":
case "using":
case "virtual":
case "where":
case "while":
return "@" + identifier;
default:
return identifier;
}
}
}
}
| |
using System.Collections.Generic;
using System.Diagnostics;
namespace Lucene.Net.Codecs.asserting
{
using AssertingAtomicReader = Lucene.Net.Index.AssertingAtomicReader;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using FieldInfo = Lucene.Net.Index.FieldInfo;
using FieldInfos = Lucene.Net.Index.FieldInfos;
using Fields = Lucene.Net.Index.Fields;
using IOContext = Lucene.Net.Store.IOContext;
/*
* 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 Lucene40TermVectorsFormat = Lucene.Net.Codecs.Lucene40.Lucene40TermVectorsFormat;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
/// <summary>
/// Just like <seealso cref="Lucene40TermVectorsFormat"/> but with additional asserts.
/// </summary>
public class AssertingTermVectorsFormat : TermVectorsFormat
{
private readonly TermVectorsFormat @in = new Lucene40TermVectorsFormat();
public override TermVectorsReader VectorsReader(Directory directory, SegmentInfo segmentInfo, FieldInfos fieldInfos, IOContext context)
{
return new AssertingTermVectorsReader(@in.VectorsReader(directory, segmentInfo, fieldInfos, context));
}
public override TermVectorsWriter VectorsWriter(Directory directory, SegmentInfo segmentInfo, IOContext context)
{
return new AssertingTermVectorsWriter(@in.VectorsWriter(directory, segmentInfo, context));
}
internal class AssertingTermVectorsReader : TermVectorsReader
{
internal readonly TermVectorsReader @in;
internal AssertingTermVectorsReader(TermVectorsReader @in)
{
this.@in = @in;
}
protected override void Dispose(bool disposing)
{
if (disposing)
@in.Dispose();
}
public override Fields Get(int doc)
{
Fields fields = @in.Get(doc);
return fields == null ? null : new AssertingAtomicReader.AssertingFields(fields);
}
public override object Clone()
{
return new AssertingTermVectorsReader((TermVectorsReader)@in.Clone());
}
public override long RamBytesUsed()
{
return @in.RamBytesUsed();
}
public override void CheckIntegrity()
{
@in.CheckIntegrity();
}
}
internal enum Status
{
UNDEFINED,
STARTED,
FINISHED
}
internal class AssertingTermVectorsWriter : TermVectorsWriter
{
internal readonly TermVectorsWriter @in;
internal Status DocStatus, FieldStatus, TermStatus;
internal int DocCount, FieldCount, TermCount, PositionCount;
internal bool HasPositions;
internal AssertingTermVectorsWriter(TermVectorsWriter @in)
{
this.@in = @in;
DocStatus = Status.UNDEFINED;
FieldStatus = Status.UNDEFINED;
TermStatus = Status.UNDEFINED;
FieldCount = TermCount = PositionCount = 0;
}
public override void StartDocument(int numVectorFields)
{
Debug.Assert(FieldCount == 0);
Debug.Assert(DocStatus != Status.STARTED);
@in.StartDocument(numVectorFields);
DocStatus = Status.STARTED;
FieldCount = numVectorFields;
DocCount++;
}
public override void FinishDocument()
{
Debug.Assert(FieldCount == 0);
Debug.Assert(DocStatus == Status.STARTED);
@in.FinishDocument();
DocStatus = Status.FINISHED;
}
public override void StartField(FieldInfo info, int numTerms, bool positions, bool offsets, bool payloads)
{
Debug.Assert(TermCount == 0);
Debug.Assert(DocStatus == Status.STARTED);
Debug.Assert(FieldStatus != Status.STARTED);
@in.StartField(info, numTerms, positions, offsets, payloads);
FieldStatus = Status.STARTED;
TermCount = numTerms;
HasPositions = positions || offsets || payloads;
}
public override void FinishField()
{
Debug.Assert(TermCount == 0);
Debug.Assert(FieldStatus == Status.STARTED);
@in.FinishField();
FieldStatus = Status.FINISHED;
--FieldCount;
}
public override void StartTerm(BytesRef term, int freq)
{
Debug.Assert(DocStatus == Status.STARTED);
Debug.Assert(FieldStatus == Status.STARTED);
Debug.Assert(TermStatus != Status.STARTED);
@in.StartTerm(term, freq);
TermStatus = Status.STARTED;
PositionCount = HasPositions ? freq : 0;
}
public override void FinishTerm()
{
Debug.Assert(PositionCount == 0);
Debug.Assert(DocStatus == Status.STARTED);
Debug.Assert(FieldStatus == Status.STARTED);
Debug.Assert(TermStatus == Status.STARTED);
@in.FinishTerm();
TermStatus = Status.FINISHED;
--TermCount;
}
public override void AddPosition(int position, int startOffset, int endOffset, BytesRef payload)
{
Debug.Assert(DocStatus == Status.STARTED);
Debug.Assert(FieldStatus == Status.STARTED);
Debug.Assert(TermStatus == Status.STARTED);
@in.AddPosition(position, startOffset, endOffset, payload);
--PositionCount;
}
public override void Abort()
{
@in.Abort();
}
public override void Finish(FieldInfos fis, int numDocs)
{
Debug.Assert(DocCount == numDocs);
Debug.Assert(DocStatus == (numDocs > 0 ? Status.FINISHED : Status.UNDEFINED));
Debug.Assert(FieldStatus != Status.STARTED);
Debug.Assert(TermStatus != Status.STARTED);
@in.Finish(fis, numDocs);
}
public override IComparer<BytesRef> Comparator
{
get
{
return @in.Comparator;
}
}
protected override void Dispose(bool disposing)
{
if (disposing)
@in.Dispose();
}
}
}
}
| |
// 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.
/*============================================================
**
**
**
** Purpose: Base class for all value classes.
**
**
===========================================================*/
using System.Runtime;
using Internal.Runtime.CompilerServices;
using Internal.Runtime.Augments;
using Debug = System.Diagnostics.Debug;
namespace System
{
// CONTRACT with Runtime
// Place holder type for type hierarchy, Compiler/Runtime requires this class
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public abstract class ValueType
{
public override String ToString()
{
return this.GetType().ToString();
}
#if PROJECTN
public override bool Equals(object obj)
{
return RuntimeAugments.Callbacks.ValueTypeEqualsUsingReflection(this, obj);
}
public override int GetHashCode()
{
return RuntimeAugments.Callbacks.ValueTypeGetHashCodeUsingReflection(this);
}
#else
private const int UseFastHelper = -1;
private const int GetNumFields = -1;
// An override of this method will be injected by the compiler into all valuetypes that cannot be compared
// using a simple memory comparison.
// This API is a bit awkward because we want to avoid burning more than one vtable slot on this.
// When index == GetNumFields, this method is expected to return the number of fields of this
// valuetype. Otherwise, it returns the offset and type handle of the index-th field on this type.
internal virtual int __GetFieldHelper(int index, out EETypePtr eeType)
{
// Value types that don't override this method will use the fast path that looks at bytes, not fields.
Debug.Assert(index == GetNumFields);
eeType = default;
return UseFastHelper;
}
public override bool Equals(object obj)
{
if (obj == null || obj.EETypePtr != this.EETypePtr)
return false;
int numFields = __GetFieldHelper(GetNumFields, out _);
ref byte thisRawData = ref this.GetRawData();
ref byte thatRawData = ref obj.GetRawData();
if (numFields == UseFastHelper)
{
// Sanity check - if there are GC references, we should not be comparing bytes
Debug.Assert(!this.EETypePtr.HasPointers);
// Compare the memory
int valueTypeSize = (int)this.EETypePtr.ValueTypeSize;
for (int i = 0; i < valueTypeSize; i++)
{
if (Unsafe.Add(ref thisRawData, i) != Unsafe.Add(ref thatRawData, i))
return false;
}
}
else
{
// Foreach field, box and call the Equals method.
for (int i = 0; i < numFields; i++)
{
int fieldOffset = __GetFieldHelper(i, out EETypePtr fieldType);
// Fetch the value of the field on both types
object thisField = RuntimeImports.RhBoxAny(ref Unsafe.Add(ref thisRawData, fieldOffset), fieldType);
object thatField = RuntimeImports.RhBoxAny(ref Unsafe.Add(ref thatRawData, fieldOffset), fieldType);
// Compare the fields
if (thisField == null)
{
if (thatField != null)
return false;
}
else if (!thisField.Equals(thatField))
{
return false;
}
}
}
return true;
}
public override int GetHashCode()
{
int hashCode = this.EETypePtr.GetHashCode();
hashCode ^= GetHashCodeImpl();
return hashCode;
}
private int GetHashCodeImpl()
{
int numFields = __GetFieldHelper(GetNumFields, out _);
if (numFields == UseFastHelper)
return FastGetValueTypeHashCodeHelper(this.EETypePtr, ref this.GetRawData());
return RegularGetValueTypeHashCode(this.EETypePtr, ref this.GetRawData(), numFields);
}
private static int FastGetValueTypeHashCodeHelper(EETypePtr type, ref byte data)
{
// Sanity check - if there are GC references, we should not be hashing bytes
Debug.Assert(!type.HasPointers);
int size = (int)type.ValueTypeSize;
int hashCode = 0;
for (int i = 0; i < size / 4; i++)
{
hashCode ^= Unsafe.As<byte, int>(ref Unsafe.Add(ref data, i * 4));
}
return hashCode;
}
private int RegularGetValueTypeHashCode(EETypePtr type, ref byte data, int numFields)
{
int hashCode = 0;
// We only take the hashcode for the first non-null field. That's what the CLR does.
for (int i = 0; i < numFields; i++)
{
int fieldOffset = __GetFieldHelper(i, out EETypePtr fieldType);
ref byte fieldData = ref Unsafe.Add(ref data, fieldOffset);
Debug.Assert(!fieldType.IsPointer);
if (fieldType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_R4)
{
hashCode = Unsafe.Read<float>(ref fieldData).GetHashCode();
}
else if (fieldType.CorElementType == RuntimeImports.RhCorElementType.ELEMENT_TYPE_R8)
{
hashCode = Unsafe.Read<double>(ref fieldData).GetHashCode();
}
else if (fieldType.IsPrimitive)
{
hashCode = FastGetValueTypeHashCodeHelper(fieldType, ref fieldData);
}
else if (fieldType.IsValueType)
{
// We have no option but to box since this value type could have
// GC pointers (we could find out if we want though), or fields of type Double/Single (we can't
// really find out). Double/Single have weird requirements around -0.0 and +0.0.
// If this boxing becomes a problem, we could build a piece of infrastructure that determines the slot
// of __GetFieldHelper, decodes the unboxing stub pointed to by the slot to the real target
// (we already have that part), and calls the entrypoint that expects a byref `this`, and use the
// data to decide between calling fast or regular hashcode helper.
var fieldValue = (ValueType)RuntimeImports.RhBox(fieldType, ref fieldData);
hashCode = fieldValue.GetHashCodeImpl();
}
else
{
object fieldValue = Unsafe.Read<object>(ref fieldData);
if (fieldValue != null)
{
hashCode = fieldValue.GetHashCode();
}
else
{
// null object reference, try next
continue;
}
}
break;
}
return hashCode;
}
#endif
}
}
| |
/* Copyright (c) 2011-2014 Stanford University
* Copyright (c) 2015 Diego Ongaro
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//#include "../Core/ConditionVariable.h"
//#include "../Core/Mutex.h"
//#include "../Event/Timer.h"
using System;
using System.Collections.Generic;
using System.Threading;
namespace RaftLib.Event
{
/**
* This class contains an event loop based on Linux's epoll interface.
* It keeps track of interesting events such as timers and socket activity, and
* arranges for callbacks to be invoked when the events happen.
*/
class Loop : SynchronizationContext
{
/**
* This is a flag to runForever() to exit, set by exit().
* Protected by Event::Loop::Lock (or #mutex directly inside runForever()).
*/
volatile bool shouldExit;
/**
* This mutex protects all of the members of this class defined below this
* point, except breakTimerMonitor.
*/
private object syncRoot = new object();
/**
* The thread ID of the thread running the event loop, or
* Core::ThreadId::NONE if no thread is currently running the event loop.
* This serves two purposes:
* First, it allows Lock to tell whether it's running under the event loop.
* Second, it allows Lock to tell if the event loop is running.
*/
volatile int runningThread;
/**
* The number of Lock instances, including those that are blocked and those
* that are active.
* runForever() waits for this to drop to 0 before running again.
*/
volatile int numLocks;
/**
* The number of Locks that are active. This is used to support reentrant
* Lock objects, specifically to know when to set #lockOwner back to
* Core::ThreadId::NONE.
*/
volatile int numActiveLocks;
/**
* The thread ID of the thread with active Locks, or Core::ThreadId::NONE
* if no thread currently has a Lock. This allows for mutually exclusive
* yet reentrant Lock objects.
*/
volatile int lockOwner;
/**
* Signaled when there are no longer any Locks active.
*/
AutoResetEvent unlocked = new AutoResetEvent(false);
/**
* Lock objects are used to synchronize between the Event::Loop thread and
* other threads. As long as a Lock object exists the following guarantees
* are in effect: either
* (a) the thread is the event loop thread or
* (b) no other thread has a Lock object and the event loop thread has
* paused in a safe place (with no event handlers active) waiting for
* the Lock to be destroyed.
* Locks may be used recursively.
*/
public void Lock()
{
Monitor.Enter(syncRoot);
try
{
Interlocked.Increment(ref numLocks);
var threadId = Thread.CurrentThread.ManagedThreadId;
if (runningThread != threadId && lockOwner != threadId)
{
// This is an actual lock: we're not running inside the event loop, and
// we're not recursively locking.
if (runningThread != threadId)
breakTimer.schedule(0);
while (runningThread != threadId || lockOwner != threadId)
{
Monitor.Wait(syncRoot);
}
// Take ownership of the lock
lockOwner = threadId;
}
Interlocked.Increment(ref numActiveLocks);
}
finally
{
Monitor.Exit(syncRoot);
}
}
public void Unlock()
{
Monitor.Enter(syncRoot);
try
{
Interlocked.Decrement(ref numLocks);
Interlocked.Decrement(ref numActiveLocks);
if (numActiveLocks == 0)
{
lockOwner = 0;
if (numLocks == 0)
unlocked.Set();
else
Monitor.Pulse(syncRoot);
}
}
finally
{
Monitor.Exit(syncRoot);
}
}
/**
* Run the main event loop until exit() is called.
* It is safe to call this again after it returns.
* The caller must ensure that only one thread is executing runForever() at
* a time.
*/
void runForever()
{
while (true)
{
Monitor.Enter(syncRoot);
try
{
runningThread = 0;
// Wait for all Locks to finish up
while (numLocks > 0)
{
Monitor.Pulse(syncRoot);
Monitor.Exit(syncRoot);
unlocked.WaitOne();
Monitor.Enter(syncRoot);
}
if (shouldExit)
{
shouldExit = false;
return;
}
runningThread = Thread.CurrentThread.ManagedThreadId;
}
finally
{
Monitor.Exit(syncRoot);
}
// Block in the kernel for events, then process them.
// TODO(ongaro): It'd be more efficient to handle more than 1 event at
// a time, but that complicates the interface: if a handler removes
// itself from the poll set and deletes itself, we don't want further
// events to call that same handler. For example, if a socket is
// dup()ed so that the receive side handles events separately from the
// send side, both are active events, and the first deletes the object,
// this could cause trouble.
int x;
//enum { NUM_EVENTS = 1 };
// struct epoll_event events[NUM_EVENTS];
// int r = epoll_wait(epollfd, events, NUM_EVENTS, -1);
// if (r <= 0) {
// if (errno == EINTR) // caused by GDB
// continue;
// PANIC("epoll_wait failed: %s", strerror(errno));
// }
// for (int i = 0; i<r; ++i) {
// Event::File& file = * static_cast<Event::File*>(events[i].data.ptr);
// file.handleFileEvent(events[i].events);
// }
}
}
/**
* Exit the main event loop, if one is running. It may return before
* runForever() has returned but guarantees runForever() will return soon.
*
* If the event loop is not running, then the next time it runs, it will
* exit right away (these semantics can be useful to avoid races).
*
* This may be called from an event handler or from any thread.
*/
void Exit()
{
Lock();
shouldExit = true;
Unlock();
}
private readonly Queue<Action> messagesToProcess = new Queue<Action>();
private readonly object syncHandle = new object();
private bool isRunning = true;
public override void Send(SendOrPostCallback codeToRun, object state)
{
throw new NotImplementedException();
}
public override void Post(SendOrPostCallback codeToRun, object state)
{
lock (syncHandle)
{
messagesToProcess.Enqueue(() => codeToRun(state));
SignalContinue();
}
}
public void RunMessagePump()
{
while (CanContinue())
{
Action nextToRun = GrabItem();
nextToRun();
}
}
private Action GrabItem()
{
lock (syncHandle)
{
while (CanContinue() && messagesToProcess.Count == 0)
{
Monitor.Wait(syncHandle);
}
return messagesToProcess.Dequeue();
}
}
private bool CanContinue()
{
lock (syncHandle)
{
return isRunning;
}
}
public void Cancel()
{
lock (syncHandle)
{
isRunning = false;
SignalContinue();
}
}
private void SignalContinue()
{
Monitor.Pulse(syncHandle);
}
}
}
| |
/*
Copyright (c) Microsoft Corporation
All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License
at http://www.apache.org/licenses/LICENSE-2.0
THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER
EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF
TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace Microsoft.Research.DryadLinq
{
internal enum DryadLinqErrorCodeCategory : int
{
QueryAPI = 0x01000000,
CodeGen = 0x02000000,
JobSubmission = 0x03000000,
Serialization = 0x04000000,
StoreClient= 0x05000000,
VertexRuntime = 0x06000000,
LocalDebug = 0x07000000,
Unknown = 0x0f000000
}
/// <summary>
/// Lists all error code in DryadLinq
/// </summary>
/// <remarks>
/// NOTE: New error codes must be appended to a category
/// NOTE: Error codes cannot be deleted
/// </remarks>
internal static class DryadLinqErrorCode
{
internal const int codesPerCategory = 0x01000000;
#region CodeGen
public const int TypeRequiredToBePublic = (int) DryadLinqErrorCodeCategory.CodeGen + 0;
public const int CustomSerializerMustSupportDefaultCtor = (int) DryadLinqErrorCodeCategory.CodeGen + 1;
public const int CustomSerializerMustBeClassOrStruct = (int) DryadLinqErrorCodeCategory.CodeGen + 2;
public const int TypeNotSerializable = (int) DryadLinqErrorCodeCategory.CodeGen + 3;
public const int CannotHandleSubtypes = (int)DryadLinqErrorCodeCategory.CodeGen + 4;
public const int UDTMustBeConcreteType = (int)DryadLinqErrorCodeCategory.CodeGen + 5;
public const int UDTHasFieldOfNonPublicType = (int)DryadLinqErrorCodeCategory.CodeGen + 6;
public const int UDTIsDelegateType = (int)DryadLinqErrorCodeCategory.CodeGen + 7;
public const int FailedToBuild = (int) DryadLinqErrorCodeCategory.CodeGen + 8;
public const int OutputTypeCannotBeAnonymous = (int) DryadLinqErrorCodeCategory.CodeGen + 9;
public const int InputTypeCannotBeAnonymous = (int) DryadLinqErrorCodeCategory.CodeGen + 10;
public const int BranchOfForkNotUsed = (int) DryadLinqErrorCodeCategory.CodeGen + 11;
public const int ComparerMustBeSpecifiedOrKeyTypeMustBeIComparable= (int) DryadLinqErrorCodeCategory.CodeGen + 12;
public const int ComparerMustBeSpecifiedOrKeyTypeMustBeIEquatable = (int)DryadLinqErrorCodeCategory.CodeGen + 13;
public const int ComparerExpressionMustBeSpecifiedOrElementTypeMustBeIEquatable = (int)DryadLinqErrorCodeCategory.CodeGen + 14;
public const int TooManyHomomorphicAttributes = (int) DryadLinqErrorCodeCategory.CodeGen + 15;
public const int HomomorphicApplyNeedsSamePartitionCount = (int)DryadLinqErrorCodeCategory.CodeGen + 16;
public const int UnrecognizedDataSource = (int) DryadLinqErrorCodeCategory.CodeGen + 17;
public const int CannotConcatDatasetsWithDifferentCompression = (int) DryadLinqErrorCodeCategory.CodeGen + 21;
public const int AggregateOperatorNotSupported = (int) DryadLinqErrorCodeCategory.CodeGen + 23;
public const int FinalizerReturnTypeMismatch = (int)DryadLinqErrorCodeCategory.CodeGen + 24;
public const int CannotHandleCircularTypes = (int)DryadLinqErrorCodeCategory.CodeGen + 26;
public const int OperatorNotSupported = (int)DryadLinqErrorCodeCategory.CodeGen + 27;
public const int AggregationOperatorRequiresIComparable = (int)DryadLinqErrorCodeCategory.CodeGen + 28;
public const int DecomposerTypeDoesNotImplementInterface = (int)DryadLinqErrorCodeCategory.CodeGen + 29;
public const int DecomposerTypeImplementsTooManyInterfaces = (int)DryadLinqErrorCodeCategory.CodeGen + 30;
public const int DecomposerTypesDoNotMatch = (int)DryadLinqErrorCodeCategory.CodeGen + 31;
public const int DecomposerTypeMustBePublic = (int)DryadLinqErrorCodeCategory.CodeGen + 32;
public const int DecomposerTypeDoesNotHavePublicDefaultCtor = (int)DryadLinqErrorCodeCategory.CodeGen + 33;
public const int AssociativeMethodHasWrongForm = (int)DryadLinqErrorCodeCategory.QueryAPI + 34;
public const int AssociativeTypeDoesNotImplementInterface = (int)DryadLinqErrorCodeCategory.CodeGen + 35;
public const int AssociativeTypeImplementsTooManyInterfaces = (int)DryadLinqErrorCodeCategory.CodeGen + 36;
public const int AssociativeTypesDoNotMatch = (int)DryadLinqErrorCodeCategory.CodeGen + 37;
public const int AssociativeTypeMustBePublic = (int)DryadLinqErrorCodeCategory.CodeGen + 38;
public const int AssociativeTypeDoesNotHavePublicDefaultCtor = (int)DryadLinqErrorCodeCategory.CodeGen + 39;
public const int CannotCreatePartitionNodeRandom = (int)DryadLinqErrorCodeCategory.CodeGen + 43;
public const int PartitionKeysNotProvided = (int)DryadLinqErrorCodeCategory.CodeGen + 44;
public const int PartitionKeysAreNotConsistentlyOrdered = (int)DryadLinqErrorCodeCategory.CodeGen + 45;
public const int IsDescendingIsInconsistent = (int)DryadLinqErrorCodeCategory.CodeGen + 46;
public const int BadSeparatorCount = (int)DryadLinqErrorCodeCategory.CodeGen + 65;
public const int TypeMustHaveDataMembers = (int)DryadLinqErrorCodeCategory.CodeGen + 66;
public const int CannotHandleObjectFields = (int)DryadLinqErrorCodeCategory.CodeGen + 67;
public const int CannotHandleDerivedtypes = (int)DryadLinqErrorCodeCategory.CodeGen + 68;
public const int MultipleOutputsWithSameDscUri = (int)DryadLinqErrorCodeCategory.CodeGen + 69;
public const int OutputUriAlsoQueryInput = (int)DryadLinqErrorCodeCategory.CodeGen + 70;
//The "internal" code is used for internal errors that should not be hit by users.
//The messages may be informative, but the error code doesn't need to be and it avoids users
//seeing all the error codes in intellisense and/or wondering if they should catch & deal with them etc.
public const int Internal = (int)DryadLinqErrorCodeCategory.CodeGen + 71;
#endregion
#region StoreClient
public const int DSCStreamError = (int) DryadLinqErrorCodeCategory.StoreClient + 0;
public const int StreamDoesNotExist = (int) DryadLinqErrorCodeCategory.StoreClient + 1;
public const int StreamAlreadyExists = (int) DryadLinqErrorCodeCategory.StoreClient + 2;
public const int AttemptToReadFromAWriteStream = (int) DryadLinqErrorCodeCategory.StoreClient + 3;
public const int FailedToCreateStream = (int) DryadLinqErrorCodeCategory.StoreClient + 4;
public const int JobToCreateTableWasCanceled = (int) DryadLinqErrorCodeCategory.StoreClient + 5;
public const int FailedToGetReadPathsForStream = (int) DryadLinqErrorCodeCategory.StoreClient + 6;
public const int CannotAccesFilePath = (int)DryadLinqErrorCodeCategory.StoreClient + 7;
public const int PositionNotSupported = (int)DryadLinqErrorCodeCategory.StoreClient + 8;
public const int GetFileSizeError = (int)DryadLinqErrorCodeCategory.StoreClient + 9;
public const int ReadFileError = (int)DryadLinqErrorCodeCategory.StoreClient + 10;
public const int UnknownCompressionScheme = (int)DryadLinqErrorCodeCategory.StoreClient + 11;
public const int WriteFileError = (int)DryadLinqErrorCodeCategory.StoreClient + 12;
public const int MultiBlockEmptyPartitionList = (int)DryadLinqErrorCodeCategory.StoreClient + 13;
public const int GetURINotSupported = (int)DryadLinqErrorCodeCategory.StoreClient + 14;
public const int SetCalcFPNotSupported = (int)DryadLinqErrorCodeCategory.StoreClient + 15;
public const int GetFPNotSupported = (int)DryadLinqErrorCodeCategory.StoreClient + 16;
public const int FailedToAllocateNewNativeBuffer = (int)DryadLinqErrorCodeCategory.StoreClient + 17;
public const int FailedToReadFromInputChannel = (int)DryadLinqErrorCodeCategory.StoreClient + 18;
public const int FailedToWriteToOutputChannel = (int)DryadLinqErrorCodeCategory.StoreClient + 19;
public const int MultiBlockCannotAccesFilePath = (int)DryadLinqErrorCodeCategory.StoreClient + 25;
#endregion
#region JobSubmission
public const int DryadHomeMustBeSpecified = (int) DryadLinqErrorCodeCategory.JobSubmission + 0;
public const int ClusterNameMustBeSpecified = (int) DryadLinqErrorCodeCategory.JobSubmission + 1;
public const int UnexpectedJobStatus = (int) DryadLinqErrorCodeCategory.JobSubmission + 2;
public const int JobStatusQueryError = (int) DryadLinqErrorCodeCategory.JobSubmission + 3;
public const int JobOptionNotImplemented = (int) DryadLinqErrorCodeCategory.JobSubmission + 4;
public const int DryadLinqJobMinMustBe2OrMore = (int) DryadLinqErrorCodeCategory.JobSubmission + 5;
public const int SubmissionFailure = (int)DryadLinqErrorCodeCategory.JobSubmission + 6;
public const int UnsupportedSchedulerType = (int)DryadLinqErrorCodeCategory.JobSubmission + 7;
public const int UnsupportedExecutionKind = (int)DryadLinqErrorCodeCategory.JobSubmission + 8;
public const int DidNotCompleteSuccessfully = (int)DryadLinqErrorCodeCategory.JobSubmission + 9;
public const int Binaries32BitNotSupported = (int)DryadLinqErrorCodeCategory.JobSubmission + 10;
#endregion
#region QueryAPI
public const int DistinctAttributeComparerNotDefined = (int) DryadLinqErrorCodeCategory.QueryAPI + 0;
public const int SerializerTypeMustBeNonNull = (int) DryadLinqErrorCodeCategory.QueryAPI + 1;
public const int SerializerTypeMustSupportIDryadLinqSerializer = (int) DryadLinqErrorCodeCategory.QueryAPI + 2;
public const int UnrecognizedOperatorName = (int) DryadLinqErrorCodeCategory.QueryAPI + 3;
public const int UnsupportedExpressionsType = (int) DryadLinqErrorCodeCategory.QueryAPI + 7;
public const int UnsupportedExpressionType = (int) DryadLinqErrorCodeCategory.QueryAPI + 8;
public const int IndexTooSmall = (int)DryadLinqErrorCodeCategory.QueryAPI + 10;
public const int MultiQueryableKeyOutOfRange = (int) DryadLinqErrorCodeCategory.QueryAPI + 11;
public const int IndexOutOfRange = (int) DryadLinqErrorCodeCategory.QueryAPI + 12;
public const int ExpressionTypeNotHandled = (int) DryadLinqErrorCodeCategory.QueryAPI + 15;
public const int FailedToGetStreamProps = (int) DryadLinqErrorCodeCategory.QueryAPI + 16;
public const int MetadataRecordType = (int) DryadLinqErrorCodeCategory.QueryAPI + 17;
public const int JobToCreateTableFailed = (int) DryadLinqErrorCodeCategory.QueryAPI + 20;
public const int OnlyAvailableForPhysicalData = (int) DryadLinqErrorCodeCategory.QueryAPI + 22;
public const int FileSetMustBeSealed = (int)DryadLinqErrorCodeCategory.QueryAPI + 23;
public const int FileSetCouldNotBeOpened = (int)DryadLinqErrorCodeCategory.QueryAPI + 24;
public const int FileSetMustHaveAtLeastOneFile = (int)DryadLinqErrorCodeCategory.QueryAPI + 25;
public const int CouldNotGetClientVersion = (int)DryadLinqErrorCodeCategory.QueryAPI + 27;
public const int CouldNotGetServerVersion = (int)DryadLinqErrorCodeCategory.QueryAPI + 28;
public const int ContextDisposed = (int)DryadLinqErrorCodeCategory.QueryAPI + 29;
public const int UnhandledQuery = (int)DryadLinqErrorCodeCategory.QueryAPI + 30; //@@TODO: when possible, reword the sr.txt entry.
public const int ExpressionMustBeMethodCall= (int)DryadLinqErrorCodeCategory.QueryAPI + 31;
public const int UntypedProviderMethodsNotSupported = (int)DryadLinqErrorCodeCategory.QueryAPI + 32;
public const int ErrorReadingMetadata = (int)DryadLinqErrorCodeCategory.QueryAPI + 33;
public const int MustStartFromContext = (int)DryadLinqErrorCodeCategory.QueryAPI + 34;
#endregion
#region Serialization
public const int FailedToReadFrom = (int) DryadLinqErrorCodeCategory.Serialization + 0;
public const int EndOfStreamEncountered = (int) DryadLinqErrorCodeCategory.Serialization + 1;
public const int SettingPositionNotSupported = (int) DryadLinqErrorCodeCategory.Serialization + 2;
public const int FingerprintDisabled = (int) DryadLinqErrorCodeCategory.Serialization + 3;
public const int RecordSizeMax2GB = (int) DryadLinqErrorCodeCategory.Serialization + 4;
public const int ReadByteNotAllowed = (int) DryadLinqErrorCodeCategory.Serialization + 6;
public const int ReadNotAllowed = (int) DryadLinqErrorCodeCategory.Serialization + 7;
public const int SeekNotSupported = (int) DryadLinqErrorCodeCategory.Serialization + 8;
public const int SetLengthNotSupported = (int) DryadLinqErrorCodeCategory.Serialization + 9;
public const int FailedToDeserialize = (int) DryadLinqErrorCodeCategory.Serialization + 10;
public const int ChannelCannotBeReadMoreThanOnce = (int) DryadLinqErrorCodeCategory.Serialization + 11;
public const int WriteNotSupported = (int)DryadLinqErrorCodeCategory.Serialization + 13;
public const int WriteByteNotSupported = (int)DryadLinqErrorCodeCategory.Serialization + 14;
public const int CannotSerializeDryadLinqQuery = (int)DryadLinqErrorCodeCategory.Serialization + 15;
public const int CannotSerializeObject = (int)DryadLinqErrorCodeCategory.Serialization + 16;
public const int GeneralSerializeFailure = (int)DryadLinqErrorCodeCategory.Serialization + 17;
#endregion
#region VertexRuntime
public const int SourceOfMergesortMustBeMultiEnumerable = (int) DryadLinqErrorCodeCategory.VertexRuntime + 1;
public const int ThenByNotSupported = (int) DryadLinqErrorCodeCategory.VertexRuntime + 2;
public const int AggregateNoElements = (int) DryadLinqErrorCodeCategory.VertexRuntime + 3;
public const int FirstNoElementsFirst = (int) DryadLinqErrorCodeCategory.VertexRuntime + 4;
public const int SingleMoreThanOneElement = (int) DryadLinqErrorCodeCategory.VertexRuntime + 5;
public const int SingleNoElements = (int) DryadLinqErrorCodeCategory.VertexRuntime + 6;
public const int LastNoElements = (int) DryadLinqErrorCodeCategory.VertexRuntime + 7;
public const int MinNoElements = (int) DryadLinqErrorCodeCategory.VertexRuntime + 8;
public const int MaxNoElements = (int) DryadLinqErrorCodeCategory.VertexRuntime + 9;
public const int AverageNoElements = (int) DryadLinqErrorCodeCategory.VertexRuntime + 10;
public const int RangePartitionKeysMissing = (int) DryadLinqErrorCodeCategory.VertexRuntime + 11;
public const int PartitionFuncReturnValueExceedsNumPorts = (int) DryadLinqErrorCodeCategory.VertexRuntime + 12;
public const int FailureInExcept = (int) DryadLinqErrorCodeCategory.VertexRuntime + 13;
public const int FailureInIntersect = (int) DryadLinqErrorCodeCategory.VertexRuntime + 14;
public const int FailureInSort = (int) DryadLinqErrorCodeCategory.VertexRuntime + 15;
public const int RangePartitionInputOutputMismatch = (int) DryadLinqErrorCodeCategory.VertexRuntime + 16;
public const int KeyNotFound = (int)DryadLinqErrorCodeCategory.VertexRuntime + 18;
public const int TooManyItems = (int)DryadLinqErrorCodeCategory.VertexRuntime + 19;
public const int FailureInHashGroupBy = (int)DryadLinqErrorCodeCategory.VertexRuntime + 20;
public const int FailureInSortGroupBy = (int)DryadLinqErrorCodeCategory.VertexRuntime + 21;
public const int FailureInHashJoin = (int)DryadLinqErrorCodeCategory.VertexRuntime + 22;
public const int FailureInHashGroupJoin = (int)DryadLinqErrorCodeCategory.VertexRuntime + 23;
public const int FailureInDistinct = (int)DryadLinqErrorCodeCategory.VertexRuntime + 24;
public const int FailureInOperator = (int)DryadLinqErrorCodeCategory.VertexRuntime + 25;
public const int FailureInUserApplyFunction = (int)DryadLinqErrorCodeCategory.VertexRuntime + 26;
public const int FailureInOrderedGroupBy = (int)DryadLinqErrorCodeCategory.VertexRuntime + 27;
public const int TooManyElementsBeforeReduction = (int)DryadLinqErrorCodeCategory.VertexRuntime + 33;
#endregion
#region LocalDebug
public const int CreatingDscDataFromLocalDebugFailed = (int)DryadLinqErrorCodeCategory.LocalDebug + 0;
#endregion
#region Unknown
public const int UnknownError = (int) DryadLinqErrorCodeCategory.Unknown + 0;
#endregion
/// <summary>
/// Returns the category of the specified error code
/// </summary>
internal static DryadLinqErrorCodeCategory Category(int code)
{
if ((code >= (int)DryadLinqErrorCodeCategory.QueryAPI) &&
(code < (int)DryadLinqErrorCodeCategory.QueryAPI+ codesPerCategory))
{
return DryadLinqErrorCodeCategory.QueryAPI;
}
else if ((code >= (int)DryadLinqErrorCodeCategory.CodeGen) &&
(code < (int)DryadLinqErrorCodeCategory.CodeGen+ codesPerCategory))
{
return DryadLinqErrorCodeCategory.CodeGen;
}
else if ((code >= (int)DryadLinqErrorCodeCategory.JobSubmission) &&
(code < (int)DryadLinqErrorCodeCategory.JobSubmission+ codesPerCategory))
{
return DryadLinqErrorCodeCategory.JobSubmission;
}
else if ((code >= (int)DryadLinqErrorCodeCategory.Serialization) &&
(code < (int)DryadLinqErrorCodeCategory.Serialization+ codesPerCategory))
{
return DryadLinqErrorCodeCategory.Serialization;
}
else if ((code >= (int)DryadLinqErrorCodeCategory.StoreClient) &&
(code < (int)DryadLinqErrorCodeCategory.StoreClient+ codesPerCategory))
{
return DryadLinqErrorCodeCategory.StoreClient;
}
else if ((code >= (int)DryadLinqErrorCodeCategory.VertexRuntime) &&
(code < (int)DryadLinqErrorCodeCategory.VertexRuntime+ codesPerCategory))
{
return DryadLinqErrorCodeCategory.VertexRuntime;
}
else if ((code >= (int)DryadLinqErrorCodeCategory.LocalDebug) &&
(code < (int)DryadLinqErrorCodeCategory.LocalDebug+ codesPerCategory))
{
return DryadLinqErrorCodeCategory.LocalDebug;
}
else
{
return DryadLinqErrorCodeCategory.Unknown;
}
}
}
}
| |
using System.Collections.Generic;
using Orleans.Configuration;
using Orleans.Runtime;
namespace Orleans.TestingHost
{
/// <summary>
/// Configuration options for test clusters.
/// </summary>
public class TestClusterOptions
{
/// <summary>
/// Gets or sets the cluster identifier.
/// </summary>
/// <seealso cref="ClusterOptions.ClusterId"/>
/// <value>The cluster identifier.</value>
public string ClusterId { get; set; }
/// <summary>
/// Gets or sets the service identifier.
/// </summary>
/// <seealso cref="ClusterOptions.ServiceId"/>
/// <value>The service identifier.</value>
public string ServiceId { get; set; }
/// <summary>
/// Gets or sets the base silo port, which is the port for the first silo. Other silos will use subsequent ports.
/// </summary>
/// <value>The base silo port.</value>
public int BaseSiloPort{ get; set; }
/// <summary>
/// Gets or sets the base gateway port, which is the gateway port for the first silo. Other silos will use subsequent ports.
/// </summary>
/// <value>The base gateway port.</value>
public int BaseGatewayPort { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use test cluster membership.
/// </summary>
/// <value><see langword="true" /> if test cluster membership should be used; otherwise, <see langword="false" />.</value>
public bool UseTestClusterMembership { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to initialize the client immediately on deployment.
/// </summary>
/// <value><see langword="true" /> if the client should be initialized immediately on deployment; otherwise, <see langword="false" />.</value>
public bool InitializeClientOnDeploy { get; set; }
/// <summary>
/// Gets or sets the initial silos count.
/// </summary>
/// <value>The initial silos count.</value>
public short InitialSilosCount { get; set; }
/// <summary>
/// Gets or sets the application base directory.
/// </summary>
/// <value>The application base directory.</value>
public string ApplicationBaseDirectory { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to configure file logging.
/// </summary>
/// <value><see langword="true" /> if file logging should be configured; otherwise, <see langword="false" />.</value>
public bool ConfigureFileLogging { get; set; } = true;
/// <summary>
/// Gets or sets a value indicating whether to assume homogeneous silos for testing purposes.
/// </summary>
/// <value><see langword="true" /> if the cluster should assume homogeneous silos; otherwise, <see langword="false" />.</value>
public bool AssumeHomogenousSilosForTesting { get; set; }
/// <summary>
/// Gets or sets a value indicating whether each silo should host a gateway.
/// </summary>
/// <value><see langword="true" /> if each silo should host a gateway; otherwise, <see langword="false" />.</value>
public bool GatewayPerSilo { get; set; } = true;
/// <summary>
/// Gets the silo builder configurator types.
/// </summary>
/// <value>The silo builder configurator types.</value>
public List<string> SiloBuilderConfiguratorTypes { get; } = new List<string>();
/// <summary>
/// Gets the client builder configurator types.
/// </summary>
/// <value>The client builder configurator types.</value>
public List<string> ClientBuilderConfiguratorTypes { get; } = new List<string>();
/// <summary>
/// Converts these options into a dictionary.
/// </summary>
/// <returns>The options dictionary.</returns>
public Dictionary<string, string> ToDictionary()
{
var result = new Dictionary<string, string>
{
[nameof(ClusterId)] = this.ClusterId,
[nameof(ServiceId)] = this.ServiceId,
[nameof(BaseSiloPort)] = this.BaseSiloPort.ToString(),
[nameof(BaseGatewayPort)] = this.BaseGatewayPort.ToString(),
[nameof(UseTestClusterMembership)] = this.UseTestClusterMembership.ToString(),
[nameof(InitializeClientOnDeploy)] = this.InitializeClientOnDeploy.ToString(),
[nameof(InitialSilosCount)] = this.InitialSilosCount.ToString(),
[nameof(ApplicationBaseDirectory)] = this.ApplicationBaseDirectory,
[nameof(ConfigureFileLogging)] = this.ConfigureFileLogging.ToString(),
[nameof(AssumeHomogenousSilosForTesting)] = this.AssumeHomogenousSilosForTesting.ToString(),
[nameof(GatewayPerSilo)] = this.GatewayPerSilo.ToString(),
};
if (this.SiloBuilderConfiguratorTypes != null)
{
for (int i = 0; i < this.SiloBuilderConfiguratorTypes.Count; i++)
{
result[$"{nameof(SiloBuilderConfiguratorTypes)}:{i}"] = this.SiloBuilderConfiguratorTypes[i];
}
}
if (this.ClientBuilderConfiguratorTypes != null)
{
for (int i = 0; i < this.ClientBuilderConfiguratorTypes.Count; i++)
{
result[$"{nameof(ClientBuilderConfiguratorTypes)}:{i}"] = this.ClientBuilderConfiguratorTypes[i];
}
}
return result;
}
}
/// <summary>
/// Configuration overrides for individual silos.
/// </summary>
public class TestSiloSpecificOptions
{
/// <summary>
/// Gets or sets the silo port.
/// </summary>
/// <value>The silo port.</value>
public int SiloPort { get; set; }
/// <summary>
/// Gets or sets the gateway port.
/// </summary>
/// <value>The gateway port.</value>
public int GatewayPort { get; set; }
/// <summary>
/// Gets or sets the name of the silo.
/// </summary>
/// <value>The name of the silo.</value>
public string SiloName { get; set; }
/// <summary>
/// Gets or sets the primary silo port.
/// </summary>
/// <value>The primary silo port.</value>
public int PrimarySiloPort { get; set; }
/// <summary>
/// Creates an instance of the <see cref="TestSiloSpecificOptions"/> class.
/// </summary>
/// <param name="testCluster">The test cluster.</param>
/// <param name="testClusterOptions">The test cluster options.</param>
/// <param name="instanceNumber">The instance number.</param>
/// <param name="assignNewPort">if set to <see langword="true" />, assign a new port for the silo.</param>
/// <returns>The options.</returns>
public static TestSiloSpecificOptions Create(TestCluster testCluster, TestClusterOptions testClusterOptions, int instanceNumber, bool assignNewPort = false)
{
var siloName = testClusterOptions.UseTestClusterMembership && instanceNumber == 0
? Silo.PrimarySiloName
: $"Secondary_{instanceNumber}";
if (assignNewPort)
{
(int siloPort, int gatewayPort) = testCluster.PortAllocator.AllocateConsecutivePortPairs(1);
var result = new TestSiloSpecificOptions
{
SiloPort = siloPort,
GatewayPort = (instanceNumber == 0 || testClusterOptions.GatewayPerSilo) ? gatewayPort : 0,
SiloName = siloName,
PrimarySiloPort = testClusterOptions.UseTestClusterMembership ? testClusterOptions.BaseSiloPort : 0,
};
return result;
}
else
{
var result = new TestSiloSpecificOptions
{
SiloPort = testClusterOptions.BaseSiloPort + instanceNumber,
GatewayPort = (instanceNumber == 0 || testClusterOptions.GatewayPerSilo) ? testClusterOptions.BaseGatewayPort + instanceNumber : 0,
SiloName = siloName,
PrimarySiloPort = testClusterOptions.UseTestClusterMembership ? testClusterOptions.BaseSiloPort : 0,
};
return result;
}
}
/// <summary>
/// Converts these options into a dictionary.
/// </summary>
/// <returns>The options dictionary.</returns>
public Dictionary<string, string> ToDictionary() => new Dictionary<string, string>
{
[nameof(SiloPort)] = this.SiloPort.ToString(),
[nameof(GatewayPort)] = this.GatewayPort.ToString(),
[nameof(SiloName)] = this.SiloName,
[nameof(PrimarySiloPort)] = this.PrimarySiloPort.ToString()
};
}
}
| |
// /*
// * Copyright (c) 2016, Alachisoft. 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;
using Alachisoft.NosDB.Serialization.Surrogates;
using System.Collections.Generic;
using Alachisoft.NosDB.Common.Serialization;
namespace Alachisoft.NosDB.Serialization
{
/// <summary>
/// Provides methods to register <see cref="ICompactSerializable"/> implementations
/// utilizing available surrogates.
/// </summary>
public sealed class CompactFormatterServices
{
static object mutex = new object();
#region / ICompactSerializable specific /
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterCompactType(Type type, short typeHandle)
{
//registers type as version compatible compact type
RegisterCompactType(type, typeHandle, true);
}
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterNonVersionCompatibleCompactType(Type type, short typeHandle)
{
RegisterCompactType(type, typeHandle, false);
}
static private void RegisterCompactType(Type type, short typeHandle, bool versionCompatible)
{
if (type == null) throw new ArgumentNullException("type");
ISerializationSurrogate surrogate = null;
if ((surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null)) != null)
{
//No need to check subHandle since this funciton us not used by DataSharing
if (surrogate.TypeHandle == typeHandle)
return; //Type is already registered with same handle.
throw new ArgumentException("Type " + type.FullName + "is already registered with different handle");
}
//if (typeof(IDictionary).IsAssignableFrom(type))
//{
// if (type.IsGenericType)
// surrogate = new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>));
// else
// surrogate = new IDictionarySerializationSurrogate(type);
//}
if (typeof(Dictionary<,>).Equals(type))
{
if (type.IsGenericType)
surrogate = new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>));
else
surrogate = new IDictionarySerializationSurrogate(type);
}
else if (type.IsArray)
{
surrogate = new ArraySerializationSurrogate(type);
}
//else if (typeof(IList).IsAssignableFrom(type))
//{
// if (type.IsGenericType)
// surrogate = new GenericIListSerializationSurrogate(typeof(IList<>));
// else
// surrogate = new IListSerializationSurrogate(type);
//}
else if (typeof(List<>).Equals(type))
{
if (type.IsGenericType)
surrogate = new GenericIListSerializationSurrogate(typeof(IList<>));
else
surrogate = new IListSerializationSurrogate(type);
}
else if (typeof(ICompactSerializable).IsAssignableFrom(type))
{
if (versionCompatible)
surrogate = new VersionCompatibleCompactSerializationSurrogate(type);
else
surrogate = new ICompactSerializableSerializationSurrogate(type);
}
else if (typeof(Enum).IsAssignableFrom(type))
{
surrogate = new EnumSerializationSurrogate(type);
}
if (surrogate == null)
throw new ArgumentException("No appropriate surrogate found for type " + type.FullName);
System.Diagnostics.Debug.WriteLine("Registered suurogate for type " + type.FullName);
TypeSurrogateSelector.RegisterTypeSurrogate(surrogate, typeHandle);
}
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterCustomCompactType(Type type, short typeHandle,string cacheContext, short subTypeHandle, Hashtable attributeOrder,bool portable,Hashtable nonCompactFields)
{
if (type == null) throw new ArgumentNullException("type");
ISerializationSurrogate surrogate = null;
if(cacheContext == null) throw new ArgumentException("cacheContext can not be null");
if ((surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,cacheContext)) != null)
{
if (surrogate.TypeHandle == typeHandle && ( surrogate.SubTypeHandle == subTypeHandle || surrogate.SubTypeHandle != 0))
return; //Type is already registered with same handle.
throw new ArgumentException("Type " + type.FullName + "is already registered with different handle");
}
//if (typeof(IDictionary).IsAssignableFrom(type) && string.IsNullOrEmpty(((Type[])type.GetGenericArguments())[0].FullName))
//{
// if (type.IsGenericType)
// surrogate = new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>));
// else
// surrogate = new IDictionarySerializationSurrogate(type);
//}
if (typeof(Dictionary<,>).Equals(type) && string.IsNullOrEmpty(((Type[])type.GetGenericArguments())[0].FullName))
{
if (type.IsGenericType)
surrogate = new GenericIDictionarySerializationSurrogate(typeof(IDictionary<,>));
else
surrogate = new IDictionarySerializationSurrogate(type);
}
else if (type.IsArray)
//if (type.IsArray)
{
surrogate = new ArraySerializationSurrogate(type);
}
//else if (typeof(IList).IsAssignableFrom(type) && string.IsNullOrEmpty(((Type[])type.GetGenericArguments())[0].FullName))
//{
// if (type.IsGenericType)
// surrogate = new GenericIListSerializationSurrogate(typeof(IList<>));
// else
// surrogate = new IListSerializationSurrogate(type);
//}
else if (typeof(List<>).Equals(type) && string.IsNullOrEmpty(((Type[])type.GetGenericArguments())[0].FullName))
{
if (type.IsGenericType)
surrogate = new GenericIListSerializationSurrogate(typeof(IList<>));
else
surrogate = new IListSerializationSurrogate(type);
}
else if (typeof(ICompactSerializable).IsAssignableFrom(type))
{
surrogate = new ICompactSerializableSerializationSurrogate(type);
}
else if (typeof(Enum).IsAssignableFrom(type))
{
surrogate = new EnumSerializationSurrogate(type);
}
else
{
lock (mutex)
{
DynamicSurrogateBuilder.Portable = portable;
if (portable)
DynamicSurrogateBuilder.SubTypeHandle = subTypeHandle;
surrogate = DynamicSurrogateBuilder.CreateTypeSurrogate(type, attributeOrder,nonCompactFields);
}
}
if (surrogate == null)
throw new ArgumentException("No appropriate surrogate found for type " + type.FullName);
System.Diagnostics.Debug.WriteLine("Registered suurogate for type " + type.FullName);
TypeSurrogateSelector.RegisterTypeSurrogate(surrogate, typeHandle,cacheContext, subTypeHandle, portable);
}
/// <summary>
/// Registers a type that implements <see cref="ICompactSerializable"/> with the system. If the
/// type is an array of <see cref="ICompactSerializable"/>s appropriate surrogates for arrays
/// and the element type are also registered.
/// </summary>
/// <param name="type">type that implements <see cref="ICompactSerializable"/></param>
/// <exception cref="ArgumentNullException">If <param name="type"/> is null.
/// </exception>
/// <exception cref="ArgumentException">
/// If the <param name="type"/> is already registered or when no appropriate surrogate
/// is found for the specified <param name="type"/>.
/// </exception>
static public void RegisterCompactType(Type type)
{
if (type == null) throw new ArgumentNullException("type");
if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null) != null)
throw new ArgumentException("Type '" + type.FullName + "' is already registered");
ISerializationSurrogate surrogate = null;
//if (typeof(IDictionary).IsAssignableFrom(type))
//{
// surrogate = new IDictionarySerializationSurrogate(type);
//}
if (typeof(Dictionary<,>).Equals(type))
{
surrogate = new IDictionarySerializationSurrogate(type);
}
else if (type.IsArray)
{
surrogate = new ArraySerializationSurrogate(type);
}
//else if (typeof(IList).IsAssignableFrom(type))
//{
// surrogate = new IListSerializationSurrogate(type);
//}
else if (typeof(List<>).Equals(type))
{
surrogate = new IListSerializationSurrogate(type);
}
else if (typeof(ICompactSerializable).IsAssignableFrom(type))
{
surrogate = new ICompactSerializableSerializationSurrogate(type);
}
else if (typeof(Enum).IsAssignableFrom(type))
{
surrogate = new EnumSerializationSurrogate(type);
}
if (surrogate == null)
throw new ArgumentException("No appropriate surrogate found for type " + type.FullName);
System.Diagnostics.Debug.WriteLine("Registered suurogate for type " + type.FullName);
TypeSurrogateSelector.RegisterTypeSurrogate(surrogate);
}
/// <summary>
/// Unregisters the surrogate for the specified type that implements
/// <see cref="ICompactSerializable"/> from the system. Used only to unregister
/// internal types.
/// <b><u>NOTE: </u></b> <b>CODE COMMENTED, NOT IMPLEMENTED</b>
/// </summary>
/// <param name="type">the specified type</param>
static public void UnregisterCompactType(Type type)
{
throw new NotImplementedException();
if (type == null) throw new ArgumentNullException("type");
if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null) == null) return;
if (type.IsArray ||
//typeof(IDictionary).IsAssignableFrom(type) ||
//typeof(IList).IsAssignableFrom(type) ||
typeof(Dictionary<,>).Equals(type) ||
typeof(List<>).Equals(type) ||
typeof(ICompactSerializable).IsAssignableFrom(type) ||
typeof(Enum).IsAssignableFrom(type))
{
ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,null);
TypeSurrogateSelector.UnregisterTypeSurrogate(surrogate);
System.Diagnostics.Debug.WriteLine("Unregistered suurogate for type " + type.FullName);
}
}
/// <summary>
/// Unregisters the surrogate for the Custom specified type that implements
/// <see cref="ICompactSerializable"/> from the system.
/// </summary>
/// <param name="type">the specified type</param>
static public void UnregisterCustomCompactType(Type type,string cacheContext)
{
throw new NotImplementedException();
if (type == null) throw new ArgumentNullException("type");
if (cacheContext == null) throw new ArgumentException("cacheContext can not be null");
if (TypeSurrogateSelector.GetSurrogateForTypeStrict(type,cacheContext) == null) return;
if (type.IsArray ||
//typeof(IDictionary).IsAssignableFrom(type) ||
//typeof(IList).IsAssignableFrom(type) ||
typeof(Dictionary<,>).Equals(type) ||
typeof(List<>).Equals(type) ||
typeof(ICompactSerializable).IsAssignableFrom(type) ||
typeof(Enum).IsAssignableFrom(type))
{
ISerializationSurrogate surrogate = TypeSurrogateSelector.GetSurrogateForTypeStrict(type,cacheContext);
TypeSurrogateSelector.UnregisterTypeSurrogate(surrogate,cacheContext);
System.Diagnostics.Debug.WriteLine("Unregistered suurogate for type " + type.FullName);
}
}
/// <summary>
/// Unregisters all the compact types associated with the cache context.
/// </summary>
/// <param name="cacheContext">Cache context</param>
static public void UnregisterAllCustomCompactTypes(string cacheContext)
{
if (cacheContext == null) throw new ArgumentException("cacheContext can not be null");
TypeSurrogateSelector.UnregisterAllSurrogates(cacheContext);
System.Diagnostics.Debug.WriteLine("Unregister all types " + cacheContext);
}
#endregion
}
}
| |
using System;
using System.Linq;
using JetBrains.Annotations;
using JetBrains.Application.Threading;
using JetBrains.Diagnostics;
using JetBrains.ReSharper.Plugins.Unity.CSharp.Psi.Resolve;
using JetBrains.ReSharper.Plugins.Unity.Utils;
using JetBrains.ReSharper.Psi;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Parsing;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.CSharp.Util;
using JetBrains.ReSharper.Psi.ExtensionsAPI.Resolve.Managed;
using JetBrains.ReSharper.Psi.Naming.Extentions;
using JetBrains.ReSharper.Psi.Naming.Settings;
using JetBrains.ReSharper.Psi.Tree;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.QuickFixes.MoveQuickFixes
{
internal static class MonoBehaviourMoveUtil
{
[CanBeNull]
public static IMethodDeclaration GetMonoBehaviourMethod([NotNull] IClassDeclaration classDeclaration,
[NotNull] string name)
{
classDeclaration.GetPsiServices().Locks.AssertReadAccessAllowed();
return classDeclaration.MethodDeclarations.FirstOrDefault(t => name.Equals(t.NameIdentifier?.Name));
}
[NotNull]
public static IMethodDeclaration GetOrCreateMethod([NotNull] IClassDeclaration classDeclaration,
[NotNull] string methodName)
{
classDeclaration.GetPsiServices().Locks.AssertReadAccessAllowed();
var result = GetMonoBehaviourMethod(classDeclaration, methodName);
if (result == null)
{
var factory = CSharpElementFactory.GetInstance(classDeclaration);
var declaration = (IMethodDeclaration) factory.CreateTypeMemberDeclaration("void $0(){}", methodName);
result = classDeclaration.AddClassMemberDeclarationBefore(declaration, classDeclaration.MethodDeclarations.FirstOrDefault());
}
return result;
}
public static bool IsExpressionAccessibleInMethod([NotNull] ICSharpExpression expression,
[NotNull] string methodName)
{
expression.GetPsiServices().Locks.AssertReadAccessAllowed();
if (!expression.IsValid())
return false;
var methodDeclaration = expression.GetContainingNode<IMethodDeclaration>();
if (methodDeclaration == null)
return false;
var statement = expression.GetContainingStatementLike();
if (statement == null)
return false;
return IsAvailableToMoveFromMethodToMethod(expression, methodName);
}
/// <summary>
/// Is node available to move outside the loop
/// </summary>
public static bool IsAvailableToMoveFromLoop([NotNull] ITreeNode toMove, [NotNull] ILoopStatement loop)
{
toMove.GetPsiServices().Locks.AssertReadAccessAllowed();
var sourceFile = toMove.GetSourceFile();
if (sourceFile == null)
return false;
var loopStartOffset = loop.GetTreeStartOffset().Offset;
return IsAvailableToMoveInner(toMove, declaredElement =>
declaredElement.GetDeclarationsIn(sourceFile)
.FirstOrDefault(declaration => declaration.GetSourceFile() == sourceFile)?.GetTreeStartOffset()
.Offset < loopStartOffset
);
}
/// <summary>
/// Is node available to move from one method to another in MonoBehaviour class
/// </summary>
public static bool IsAvailableToMoveFromMethodToMethod([NotNull] ITreeNode toMove, [NotNull] string methodName)
{
toMove.GetPsiServices().Locks.AssertReadAccessAllowed();
var classDeclaration = toMove.GetContainingNode<IClassDeclaration>();
if (classDeclaration == null)
return false;
var modifiers = classDeclaration.ModifiersList;
if (modifiers == null ||
!modifiers.ModifiersEnumerable.Any(t => t.GetTokenType().Equals(CSharpTokenType.ABSTRACT_KEYWORD)))
return IsAvailableToMoveInner(toMove);
var method = GetMonoBehaviourMethod(classDeclaration, methodName);
if (method == null)
return IsAvailableToMoveInner(toMove);
;
var methodModifiers = method.ModifiersList;
if (methodModifiers == null ||
!methodModifiers.ModifiersEnumerable.Any(t => t.GetTokenType().Equals(CSharpTokenType.ABSTRACT_KEYWORD))
)
return IsAvailableToMoveInner(toMove);
return false;
}
private static bool IsAvailableToMoveInner([NotNull] ITreeNode toMove,
[CanBeNull] Func<IDeclaredElement, bool> isElementIgnored = null)
{
var sourceFile = toMove.GetSourceFile();
if (sourceFile == null)
return false;
var methodDeclaration = toMove.GetContainingNode<IMethodDeclaration>();
if (methodDeclaration == null)
return false;
var nodeEnumerator = toMove.ThisAndDescendants();
while (nodeEnumerator.MoveNext())
{
var current = nodeEnumerator.Current;
foreach (var reference in current.GetReferences())
{
var declaredElement = reference.Resolve().DeclaredElement;
if (declaredElement == null || isElementIgnored?.Invoke(declaredElement) == true)
continue;
var declaration = declaredElement.GetDeclarationsIn(sourceFile).FirstOrDefault();
if (declaration == null)
continue;
if (declaration.GetContainingNode<IMethodDeclaration>() == methodDeclaration &&
declaration.GetContainingNode<ICSharpClosure>() == null)
return false;
}
}
return true;
}
public static void MoveToMethodWithFieldIntroduction([NotNull] IClassDeclaration classDeclaration,
[NotNull] ICSharpExpression expression, [NotNull] string methodName, string fieldName = null)
{
classDeclaration.GetPsiServices().Locks.AssertReadAccessAllowed();
var methodDeclaration = GetOrCreateMethod(classDeclaration, methodName);
MoveToMethodWithFieldIntroduction(classDeclaration, methodDeclaration, expression, fieldName);
}
public static void MoveToMethodWithFieldIntroduction([NotNull] IClassDeclaration classDeclaration,
[NotNull] IMethodDeclaration methodDeclaration,
[NotNull] ICSharpExpression expression, string fieldName = null)
{
classDeclaration.GetPsiServices().Locks.AssertReadAccessAllowed();
var result = GetDeclaredElementFromParentDeclaration(expression);
var factory = CSharpElementFactory.GetInstance(classDeclaration);
var type = expression.Type(new ResolveContext(classDeclaration.GetPsiModule()));
if (type.IsUnknown)
type = TypeFactory.CreateTypeByCLRName("System.Object", classDeclaration.GetPsiModule());
var isVoid = type.IsVoid();
if (!isVoid)
{
var baseName = fieldName ?? CreateBaseName(expression, result);
var name = NamingUtil.GetUniqueName(expression, baseName, NamedElementKinds.PrivateInstanceFields,
baseName == null
? collection =>
{
collection.Add(expression.Type(), new EntryOptions());
}
: (Action<INamesCollection>) null,
de => !de.Equals(result));
var field = factory.CreateFieldDeclaration(type, name);
field.SetAccessRights(AccessRights.PRIVATE);
classDeclaration.AddClassMemberDeclaration(field);
var initialization = factory.CreateStatement("$0 = $1;", name, expression.CopyWithResolve());
var body = methodDeclaration.EnsureStatementMemberBody();
body.AddStatementAfter(initialization, null);
RenameOldUsages(expression, result, name, factory);
}
else
{
var initialization = factory.CreateStatement("$0;", expression.CopyWithResolve());
var body = methodDeclaration.EnsureStatementMemberBody();
body.AddStatementAfter(initialization, null);
ExpressionStatementNavigator.GetByExpression(expression).NotNull("statement != null").RemoveOrReplaceByEmptyStatement();
}
}
public static void RenameOldUsages([NotNull] ICSharpExpression originExpression,
[CanBeNull] IDeclaredElement localVariableDeclaredElement,
[NotNull] string newName, [NotNull] CSharpElementFactory factory)
{
originExpression.GetPsiServices().Locks.AssertReadAccessAllowed();
var statement = ExpressionStatementNavigator.GetByExpression(originExpression);
if (statement != null)
{
statement.RemoveOrReplaceByEmptyStatement();
}
else
{
if (localVariableDeclaredElement == null)
{
originExpression.ReplaceBy(factory.CreateReferenceExpression(newName));
}
else if (!newName.Equals(localVariableDeclaredElement.ShortName))
{
var provider = DefaultUsagesProvider.Instance;
var usages = provider.GetUsages(localVariableDeclaredElement,
originExpression.GetContainingNode<IMethodDeclaration>().NotNull("scope != null"));
originExpression.GetContainingStatement().NotNull("expression.GetContainingStatement() != null")
.RemoveOrReplaceByEmptyStatement();
foreach (var usage in usages)
{
if (usage.IsValid() && usage is IReferenceExpression node)
node.ReplaceBy(factory.CreateReferenceExpression(newName));
}
}
else
{
DeclarationStatementNavigator.GetByVariableDeclaration(
LocalVariableDeclarationNavigator.GetByInitial(
ExpressionInitializerNavigator.GetByValue(
originExpression.GetContainingParenthesizedExpression())))
?.RemoveOrReplaceByEmptyStatement();
}
}
}
/// <summary>
/// If current expression is used as initializer for local variable, declared element for this variable will be returned
/// </summary>
public static IDeclaredElement GetDeclaredElementFromParentDeclaration([NotNull] ICSharpExpression expression)
{
expression.GetPsiServices().Locks.AssertReadAccessAllowed();
var localVariableDeclaration =
LocalVariableDeclarationNavigator.GetByInitial(
ExpressionInitializerNavigator.GetByValue(expression.GetContainingParenthesizedExpression()));
return localVariableDeclaration?.DeclaredElement;
}
public static string CreateBaseName([NotNull] ICSharpExpression toMove,
[CanBeNull] IDeclaredElement variableDeclaration)
{
toMove.GetPsiServices().Locks.AssertReadAccessAllowed();
string baseName = null;
if (variableDeclaration != null)
{
baseName = variableDeclaration.ShortName;
}
else
{
if (toMove is IInvocationExpression invocationExpression)
{
var arguments = invocationExpression.Arguments;
if (arguments.Count > 0)
{
var argument = arguments[0].Value;
var reference = argument.GetReferences<UnityObjectTypeOrNamespaceReference>().FirstOrDefault();
if (reference != null && reference.Resolve().ResolveErrorType.IsAcceptable)
{
baseName = (argument.ConstantValue.Value as string).NotNull(
"argument.ConstantValue.Value as string != null");
}
}
}
}
return baseName;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using Microsoft.Extensions.Logging;
using Orleans.CodeGeneration;
namespace Orleans.Runtime
{
/// <summary>
/// A collection of utility functions for dealing with Type information.
/// </summary>
internal static class TypeUtils
{
/// <summary>
/// The assembly name of the core Orleans assembly.
/// </summary>
private static readonly AssemblyName OrleansCoreAssembly = typeof(RuntimeVersion).GetTypeInfo().Assembly.GetName();
/// <summary>
/// The assembly name of the core Orleans abstractions assembly.
/// </summary>
private static readonly AssemblyName OrleansAbstractionsAssembly = typeof(IGrain).GetTypeInfo().Assembly.GetName();
private static readonly ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string> ParseableNameCache = new ConcurrentDictionary<Tuple<Type, TypeFormattingOptions>, string>();
private static readonly ConcurrentDictionary<Tuple<Type, bool>, List<Type>> ReferencedTypes = new ConcurrentDictionary<Tuple<Type, bool>, List<Type>>();
private static readonly CachedReflectionOnlyTypeResolver ReflectionOnlyTypeResolver = new CachedReflectionOnlyTypeResolver();
public static string GetSimpleTypeName(Type t, Predicate<Type> fullName = null)
{
return GetSimpleTypeName(t.GetTypeInfo(), fullName);
}
public static string GetSimpleTypeName(TypeInfo typeInfo, Predicate<Type> fullName = null)
{
if (typeInfo.IsNestedPublic || typeInfo.IsNestedPrivate)
{
if (typeInfo.DeclaringType.GetTypeInfo().IsGenericType)
{
return GetTemplatedName(
GetUntemplatedTypeName(typeInfo.DeclaringType.Name),
typeInfo.DeclaringType,
typeInfo.GetGenericArguments(),
_ => true) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
return GetTemplatedName(typeInfo.DeclaringType) + "." + GetUntemplatedTypeName(typeInfo.Name);
}
var type = typeInfo.AsType();
if (typeInfo.IsGenericType) return GetSimpleTypeName(fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name);
return fullName != null && fullName(type) ? GetFullName(type) : typeInfo.Name;
}
public static string GetUntemplatedTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static string GetSimpleTypeName(string typeName)
{
int i = typeName.IndexOf('`');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('[');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
i = typeName.IndexOf('<');
if (i > 0)
{
typeName = typeName.Substring(0, i);
}
return typeName;
}
public static bool IsConcreteTemplateType(Type t)
{
if (t.GetTypeInfo().IsGenericType) return true;
return t.IsArray && IsConcreteTemplateType(t.GetElementType());
}
public static string GetTemplatedName(Type t, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = _ => true; // default to full type names
var typeInfo = t.GetTypeInfo();
if (typeInfo.IsGenericType) return GetTemplatedName(GetSimpleTypeName(typeInfo, fullName), t, typeInfo.GetGenericArguments(), fullName);
if (t.IsArray)
{
return GetTemplatedName(t.GetElementType(), fullName)
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return GetSimpleTypeName(typeInfo, fullName);
}
public static bool IsConstructedGenericType(this TypeInfo typeInfo)
{
// is there an API that returns this info without converting back to type already?
return typeInfo.AsType().IsConstructedGenericType;
}
internal static IEnumerable<TypeInfo> GetTypeInfos(this Type[] types)
{
return types.Select(t => t.GetTypeInfo());
}
public static string GetTemplatedName(string baseName, Type t, Type[] genericArguments, Predicate<Type> fullName)
{
var typeInfo = t.GetTypeInfo();
if (!typeInfo.IsGenericType || (t.DeclaringType != null && t.DeclaringType.GetTypeInfo().IsGenericType)) return baseName;
string s = baseName;
s += "<";
s += GetGenericTypeArgs(genericArguments, fullName);
s += ">";
return s;
}
public static string GetGenericTypeArgs(IEnumerable<Type> args, Predicate<Type> fullName)
{
string s = string.Empty;
bool first = true;
foreach (var genericParameter in args)
{
if (!first)
{
s += ",";
}
if (!genericParameter.GetTypeInfo().IsGenericType)
{
s += GetSimpleTypeName(genericParameter, fullName);
}
else
{
s += GetTemplatedName(genericParameter, fullName);
}
first = false;
}
return s;
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => true;
return GetParameterizedTemplateName(typeInfo, fullName, applyRecursively);
}
public static string GetParameterizedTemplateName(TypeInfo typeInfo, Predicate<Type> fullName, bool applyRecursively = false)
{
if (typeInfo.IsGenericType)
{
return GetParameterizedTemplateName(GetSimpleTypeName(typeInfo, fullName), typeInfo, applyRecursively, fullName);
}
var t = typeInfo.AsType();
if (fullName != null && fullName(t) == true)
{
return t.FullName;
}
return t.Name;
}
public static string GetParameterizedTemplateName(string baseName, TypeInfo typeInfo, bool applyRecursively = false, Predicate<Type> fullName = null)
{
if (fullName == null)
fullName = tt => false;
if (!typeInfo.IsGenericType) return baseName;
string s = baseName;
s += "<";
bool first = true;
foreach (var genericParameter in typeInfo.GetGenericArguments())
{
if (!first)
{
s += ",";
}
var genericParameterTypeInfo = genericParameter.GetTypeInfo();
if (applyRecursively && genericParameterTypeInfo.IsGenericType)
{
s += GetParameterizedTemplateName(genericParameterTypeInfo, applyRecursively);
}
else
{
s += genericParameter.FullName == null || !fullName(genericParameter)
? genericParameter.Name
: genericParameter.FullName;
}
first = false;
}
s += ">";
return s;
}
public static string GetRawClassName(string baseName, Type t)
{
var typeInfo = t.GetTypeInfo();
return typeInfo.IsGenericType ? baseName + '`' + typeInfo.GetGenericArguments().Length : baseName;
}
public static string GetRawClassName(string typeName)
{
int i = typeName.IndexOf('[');
return i <= 0 ? typeName : typeName.Substring(0, i);
}
public static Type[] GenericTypeArgsFromClassName(string className)
{
return GenericTypeArgsFromArgsString(GenericTypeArgsString(className));
}
public static Type[] GenericTypeArgsFromArgsString(string genericArgs)
{
if (string.IsNullOrEmpty(genericArgs)) return Type.EmptyTypes;
var genericTypeDef = genericArgs.Replace("[]", "##"); // protect array arguments
return InnerGenericTypeArgs(genericTypeDef);
}
private static Type[] InnerGenericTypeArgs(string className)
{
var typeArgs = new List<Type>();
var innerTypes = GetInnerTypes(className);
foreach (var innerType in innerTypes)
{
if (innerType.StartsWith("[[")) // Resolve and load generic types recursively
{
InnerGenericTypeArgs(GenericTypeArgsString(innerType));
string genericTypeArg = className.Trim('[', ']');
typeArgs.Add(Type.GetType(genericTypeArg.Replace("##", "[]")));
}
else
{
string nonGenericTypeArg = innerType.Trim('[', ']');
typeArgs.Add(Type.GetType(nonGenericTypeArg.Replace("##", "[]")));
}
}
return typeArgs.ToArray();
}
private static string[] GetInnerTypes(string input)
{
// Iterate over strings of length 2 positionwise.
var charsWithPositions = input.Zip(Enumerable.Range(0, input.Length), (c, i) => new { Ch = c, Pos = i });
var candidatesWithPositions = charsWithPositions.Zip(charsWithPositions.Skip(1), (c1, c2) => new { Str = c1.Ch.ToString() + c2.Ch, Pos = c1.Pos });
var results = new List<string>();
int startPos = -1;
int endPos = -1;
int endTokensNeeded = 0;
string curStartToken = "";
string curEndToken = "";
var tokenPairs = new[] { new { Start = "[[", End = "]]" }, new { Start = "[", End = "]" } }; // Longer tokens need to come before shorter ones
foreach (var candidate in candidatesWithPositions)
{
if (startPos == -1)
{
foreach (var token in tokenPairs)
{
if (candidate.Str.StartsWith(token.Start))
{
curStartToken = token.Start;
curEndToken = token.End;
startPos = candidate.Pos;
break;
}
}
}
if (curStartToken != "" && candidate.Str.StartsWith(curStartToken))
endTokensNeeded++;
if (curEndToken != "" && candidate.Str.EndsWith(curEndToken))
{
endPos = candidate.Pos;
endTokensNeeded--;
}
if (endTokensNeeded == 0 && startPos != -1)
{
results.Add(input.Substring(startPos, endPos - startPos + 2));
startPos = -1;
curStartToken = "";
}
}
return results.ToArray();
}
public static string GenericTypeArgsString(string className)
{
int startIndex = className.IndexOf('[');
int endIndex = className.LastIndexOf(']');
return className.Substring(startIndex + 1, endIndex - startIndex - 1);
}
public static bool IsGenericClass(string name)
{
return name.Contains("`") || name.Contains("[");
}
public static string GetFullName(TypeInfo typeInfo)
{
if (typeInfo == null) throw new ArgumentNullException(nameof(typeInfo));
return GetFullName(typeInfo.AsType());
}
public static string GetFullName(Type t)
{
if (t == null) throw new ArgumentNullException(nameof(t));
if (t.IsNested && !t.IsGenericParameter)
{
return t.Namespace + "." + t.DeclaringType.Name + "." + t.Name;
}
if (t.IsArray)
{
return GetFullName(t.GetElementType())
+ "["
+ new string(',', t.GetArrayRank() - 1)
+ "]";
}
return t.FullName ?? (t.IsGenericParameter ? t.Name : t.Namespace + "." + t.Name);
}
/// <summary>
/// Returns all fields of the specified type.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>All fields of the specified type.</returns>
public static IEnumerable<FieldInfo> GetAllFields(this Type type)
{
const BindingFlags AllFields =
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly;
var current = type;
while ((current != typeof(object)) && (current != null))
{
var fields = current.GetFields(AllFields);
foreach (var field in fields)
{
yield return field;
}
current = current.GetTypeInfo().BaseType;
}
}
/// <summary>
/// Returns <see langword="true"/> if <paramref name="field"/> is marked as
/// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise.
/// </summary>
/// <param name="field">The field.</param>
/// <returns>
/// <see langword="true"/> if <paramref name="field"/> is marked as
/// <see cref="FieldAttributes.NotSerialized"/>, <see langword="false"/> otherwise.
/// </returns>
public static bool IsNotSerialized(this FieldInfo field)
=> (field.Attributes & FieldAttributes.NotSerialized) == FieldAttributes.NotSerialized;
/// <summary>
/// decide whether the class is derived from Grain
/// </summary>
public static bool IsGrainClass(Type type)
{
var grainType = typeof(Grain);
var grainChevronType = typeof(Grain<>);
if (type.Assembly.ReflectionOnly)
{
grainType = ToReflectionOnlyType(grainType);
grainChevronType = ToReflectionOnlyType(grainChevronType);
}
if (grainType == type || grainChevronType == type) return false;
if (!grainType.IsAssignableFrom(type)) return false;
// exclude generated classes.
return !IsGeneratedType(type);
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints, bool complain)
{
complaints = null;
if (!IsGrainClass(type)) return false;
if (!type.GetTypeInfo().IsAbstract) return true;
complaints = complain ? new[] { string.Format("Grain type {0} is abstract and cannot be instantiated.", type.FullName) } : null;
return false;
}
public static bool IsConcreteGrainClass(Type type, out IEnumerable<string> complaints)
{
return IsConcreteGrainClass(type, out complaints, complain: true);
}
public static bool IsConcreteGrainClass(Type type)
{
IEnumerable<string> complaints;
return IsConcreteGrainClass(type, out complaints, complain: false);
}
public static bool IsGeneratedType(Type type)
{
return TypeHasAttribute(type, typeof(GeneratedCodeAttribute));
}
/// <summary>
/// Returns true if the provided <paramref name="type"/> is in any of the provided
/// <paramref name="namespaces"/>, false otherwise.
/// </summary>
/// <param name="type">The type to check.</param>
/// <param name="namespaces"></param>
/// <returns>
/// true if the provided <paramref name="type"/> is in any of the provided <paramref name="namespaces"/>, false
/// otherwise.
/// </returns>
public static bool IsInNamespace(Type type, List<string> namespaces)
{
if (type.Namespace == null)
{
return false;
}
foreach (var ns in namespaces)
{
if (ns.Length > type.Namespace.Length)
{
continue;
}
// If the candidate namespace is a prefix of the type's namespace, return true.
if (type.Namespace.StartsWith(ns, StringComparison.Ordinal)
&& (type.Namespace.Length == ns.Length || type.Namespace[ns.Length] == '.'))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>
/// true if <paramref name="type"/> has implementations of all serialization methods, false otherwise.
/// </returns>
public static bool HasAllSerializationMethods(Type type)
{
// Check if the type has any of the serialization methods.
var hasCopier = false;
var hasSerializer = false;
var hasDeserializer = false;
foreach (var method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
hasSerializer |= method.GetCustomAttribute<SerializerMethodAttribute>(false) != null;
hasDeserializer |= method.GetCustomAttribute<DeserializerMethodAttribute>(false) != null;
hasCopier |= method.GetCustomAttribute<CopierMethodAttribute>(false) != null;
}
var hasAllSerializationMethods = hasCopier && hasSerializer && hasDeserializer;
return hasAllSerializationMethods;
}
public static bool IsGrainMethodInvokerType(Type type)
{
var generalType = typeof(IGrainMethodInvoker);
if (type.Assembly.ReflectionOnly)
{
generalType = ToReflectionOnlyType(generalType);
}
return generalType.IsAssignableFrom(type) && TypeHasAttribute(type, typeof(MethodInvokerAttribute));
}
private static readonly Lazy<bool> canUseReflectionOnly = new Lazy<bool>(() =>
{
try
{
ReflectionOnlyTypeResolver.TryResolveType(typeof(TypeUtils).AssemblyQualifiedName, out _);
return true;
}
catch (PlatformNotSupportedException)
{
return false;
}
catch (Exception)
{
// if other exceptions not related to platform ocurr, assume that ReflectionOnly is supported
return true;
}
});
public static bool CanUseReflectionOnly => canUseReflectionOnly.Value;
public static Type ResolveReflectionOnlyType(string assemblyQualifiedName)
{
return ReflectionOnlyTypeResolver.ResolveType(assemblyQualifiedName);
}
public static Type ToReflectionOnlyType(Type type)
{
if (CanUseReflectionOnly)
{
return type.Assembly.ReflectionOnly ? type : ResolveReflectionOnlyType(type.AssemblyQualifiedName);
}
else
{
return type;
}
}
public static IEnumerable<Type> GetTypes(Assembly assembly, Predicate<Type> whereFunc, ILogger logger)
{
return assembly.IsDynamic ? Enumerable.Empty<Type>() : GetDefinedTypes(assembly, logger).Select(t => t.AsType()).Where(type => !type.GetTypeInfo().IsNestedPrivate && whereFunc(type));
}
public static IEnumerable<TypeInfo> GetDefinedTypes(Assembly assembly, ILogger logger=null)
{
try
{
return assembly.DefinedTypes;
}
catch (Exception exception)
{
if (logger != null && logger.IsEnabled(LogLevel.Warning))
{
var message =
$"Exception loading types from assembly '{assembly.FullName}': {LogFormatter.PrintException(exception)}.";
logger.Warn(ErrorCode.Loader_TypeLoadError_5, message, exception);
}
var typeLoadException = exception as ReflectionTypeLoadException;
if (typeLoadException != null)
{
return typeLoadException.Types?.Where(type => type != null).Select(type => type.GetTypeInfo()) ??
Enumerable.Empty<TypeInfo>();
}
return Enumerable.Empty<TypeInfo>();
}
}
/// <summary>
/// Returns a value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.
/// </summary>
/// <param name="methodInfo">The method.</param>
/// <returns>A value indicating whether or not the provided <paramref name="methodInfo"/> is a grain method.</returns>
public static bool IsGrainMethod(MethodInfo methodInfo)
{
if (methodInfo == null) throw new ArgumentNullException("methodInfo", "Cannot inspect null method info");
if (methodInfo.IsStatic || methodInfo.IsSpecialName || methodInfo.DeclaringType == null)
{
return false;
}
return methodInfo.DeclaringType.GetTypeInfo().IsInterface
&& typeof(IAddressable).IsAssignableFrom(methodInfo.DeclaringType);
}
public static bool TypeHasAttribute(Type type, Type attribType)
{
if (type.Assembly.ReflectionOnly || attribType.Assembly.ReflectionOnly)
{
type = ToReflectionOnlyType(type);
attribType = ToReflectionOnlyType(attribType);
// we can't use Type.GetCustomAttributes here because we could potentially be working with a reflection-only type.
return CustomAttributeData.GetCustomAttributes(type).Any(
attrib => attribType.IsAssignableFrom(attrib.AttributeType));
}
return TypeHasAttribute(type.GetTypeInfo(), attribType);
}
public static bool TypeHasAttribute(TypeInfo typeInfo, Type attribType)
{
return typeInfo.GetCustomAttributes(attribType, true).Any();
}
/// <summary>
/// Returns a sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </summary>
/// <param name="type">
/// The grain type.
/// </param>
/// <returns>
/// A sanitized version of <paramref name="type"/>s name which is suitable for use as a class name.
/// </returns>
public static string GetSuitableClassName(Type type)
{
return GetClassNameFromInterfaceName(type.GetUnadornedTypeName());
}
/// <summary>
/// Returns a class-like version of <paramref name="interfaceName"/>.
/// </summary>
/// <param name="interfaceName">
/// The interface name.
/// </param>
/// <returns>
/// A class-like version of <paramref name="interfaceName"/>.
/// </returns>
public static string GetClassNameFromInterfaceName(string interfaceName)
{
string cleanName;
if (interfaceName.StartsWith("i", StringComparison.OrdinalIgnoreCase))
{
cleanName = interfaceName.Substring(1);
}
else
{
cleanName = interfaceName;
}
return cleanName;
}
/// <summary>
/// Returns the non-generic type name without any special characters.
/// </summary>
/// <param name="type">
/// The type.
/// </param>
/// <returns>
/// The non-generic type name without any special characters.
/// </returns>
public static string GetUnadornedTypeName(this Type type)
{
var index = type.Name.IndexOf('`');
// An ampersand can appear as a suffix to a by-ref type.
return (index > 0 ? type.Name.Substring(0, index) : type.Name).TrimEnd('&');
}
/// <summary>
/// Returns the non-generic method name without any special characters.
/// </summary>
/// <param name="method">
/// The method.
/// </param>
/// <returns>
/// The non-generic method name without any special characters.
/// </returns>
public static string GetUnadornedMethodName(this MethodInfo method)
{
var index = method.Name.IndexOf('`');
return index > 0 ? method.Name.Substring(0, index) : method.Name;
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="options">The type formatting options.</param>
/// <param name="getNameFunc">The delegate used to get the unadorned, simple type name of <paramref name="type"/>.</param>
/// <returns>A string representation of the <paramref name="type"/>.</returns>
public static string GetParseableName(this Type type, TypeFormattingOptions options = null, Func<Type, string> getNameFunc = null)
{
options = options ?? TypeFormattingOptions.Default;
// If a naming function has been specified, skip the cache.
if (getNameFunc != null) return BuildParseableName();
return ParseableNameCache.GetOrAdd(Tuple.Create(type, options), _ => BuildParseableName());
string BuildParseableName()
{
var builder = new StringBuilder();
var typeInfo = type.GetTypeInfo();
GetParseableName(
type,
builder,
new Queue<Type>(
typeInfo.IsGenericTypeDefinition
? typeInfo.GetGenericArguments()
: typeInfo.GenericTypeArguments),
options,
getNameFunc ?? (t => t.GetUnadornedTypeName() + options.NameSuffix));
return builder.ToString();
}
}
/// <summary>Returns a string representation of <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="builder">The <see cref="StringBuilder"/> to append results to.</param>
/// <param name="typeArguments">The type arguments of <paramref name="type"/>.</param>
/// <param name="options">The type formatting options.</param>
/// <param name="getNameFunc">Delegate that returns name for a type.</param>
private static void GetParseableName(
Type type,
StringBuilder builder,
Queue<Type> typeArguments,
TypeFormattingOptions options,
Func<Type, string> getNameFunc)
{
var typeInfo = type.GetTypeInfo();
if (typeInfo.IsArray)
{
var elementType = typeInfo.GetElementType().GetParseableName(options);
if (!string.IsNullOrWhiteSpace(elementType))
{
builder.AppendFormat(
"{0}[{1}]",
elementType,
string.Concat(Enumerable.Range(0, type.GetArrayRank() - 1).Select(_ => ',')));
}
return;
}
if (typeInfo.IsGenericParameter)
{
if (options.IncludeGenericTypeParameters)
{
builder.Append(type.GetUnadornedTypeName());
}
return;
}
if (typeInfo.DeclaringType != null)
{
// This is not the root type.
GetParseableName(typeInfo.DeclaringType, builder, typeArguments, options, t => t.GetUnadornedTypeName());
builder.Append(options.NestedTypeSeparator);
}
else if (!string.IsNullOrWhiteSpace(type.Namespace) && options.IncludeNamespace)
{
// This is the root type, so include the namespace.
var namespaceName = type.Namespace;
if (options.NestedTypeSeparator != '.')
{
namespaceName = namespaceName.Replace('.', options.NestedTypeSeparator);
}
if (options.IncludeGlobal)
{
builder.AppendFormat("global::");
}
builder.AppendFormat("{0}{1}", namespaceName, options.NestedTypeSeparator);
}
if (type.IsConstructedGenericType)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = getNameFunc(type);
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(typeInfo.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(generic => GetParseableName(generic, options)));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else if (typeInfo.IsGenericTypeDefinition)
{
// Get the unadorned name, the generic parameters, and add them together.
var unadornedTypeName = getNameFunc(type);
builder.Append(EscapeIdentifier(unadornedTypeName));
var generics =
Enumerable.Range(0, Math.Min(type.GetGenericArguments().Count(), typeArguments.Count))
.Select(_ => typeArguments.Dequeue())
.ToList();
if (generics.Count > 0 && options.IncludeTypeParameters)
{
var genericParameters = string.Join(
",",
generics.Select(_ => options.IncludeGenericTypeParameters ? _.ToString() : string.Empty));
builder.AppendFormat("<{0}>", genericParameters);
}
}
else
{
builder.Append(EscapeIdentifier(getNameFunc(type)));
}
}
/// <summary>
/// Returns the namespaces of the specified types.
/// </summary>
/// <param name="types">
/// The types to include.
/// </param>
/// <returns>
/// The namespaces of the specified types.
/// </returns>
public static IEnumerable<string> GetNamespaces(params Type[] types)
{
return types.Select(type => "global::" + type.Namespace).Distinct();
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the property.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the property.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static PropertyInfo Property<T, TResult>(Expression<Func<T, TResult>> expression)
{
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member as PropertyInfo;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="PropertyInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="TResult">
/// The return type of the property.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="PropertyInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static PropertyInfo Property<TResult>(Expression<Func<TResult>> expression)
{
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member as PropertyInfo;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">
/// The containing type of the method.
/// </typeparam>
/// <typeparam name="TResult">
/// The return type of the method.
/// </typeparam>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.
/// </returns>
public static MemberInfo Member<T, TResult>(Expression<Func<T, TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MemberInfo"/> for the simple member access in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="TResult">The return type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MemberInfo"/> for the simple member access call in the provided <paramref name="expression"/>.</returns>
public static MemberInfo Member<TResult>(Expression<Func<TResult>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
var property = expression.Body as MemberExpression;
if (property != null)
{
return property.Member;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Func<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <typeparam name="T">The containing type of the method.</typeparam>
/// <param name="expression">The expression.</param>
/// <returns>The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.</returns>
public static MethodInfo Method<T>(Expression<Action<T>> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>
/// Returns the <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </summary>
/// <param name="expression">
/// The expression.
/// </param>
/// <returns>
/// The <see cref="MethodInfo"/> for the simple method call in the provided <paramref name="expression"/>.
/// </returns>
public static MethodInfo Method(Expression<Action> expression)
{
var methodCall = expression.Body as MethodCallExpression;
if (methodCall != null)
{
return methodCall.Method;
}
throw new ArgumentException("Expression type unsupported.");
}
/// <summary>Returns the namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</summary>
/// <param name="type">The type.</param>
/// <returns>The namespace of the provided type, or <see cref="string.Empty"/> if the type has no namespace.</returns>
public static string GetNamespaceOrEmpty(this Type type)
{
if (type == null || string.IsNullOrEmpty(type.Namespace))
{
return string.Empty;
}
return type.Namespace;
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
public static IList<Type> GetTypes(this Type type, bool includeMethods = false)
{
List<Type> results;
var key = Tuple.Create(type, includeMethods);
if (!ReferencedTypes.TryGetValue(key, out results))
{
results = GetTypes(type, includeMethods, null).ToList();
ReferencedTypes.TryAdd(key, results);
}
return results;
}
/// <summary>
/// Get a public or non-public constructor that matches the constructor arguments signature
/// </summary>
/// <param name="type">The type to use.</param>
/// <param name="constructorArguments">The constructor argument types to match for the signature.</param>
/// <returns>A constructor that matches the signature or <see langword="null"/>.</returns>
public static ConstructorInfo GetConstructorThatMatches(Type type, Type[] constructorArguments)
{
var constructorInfo = type.GetConstructor(
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
null,
constructorArguments,
null);
return constructorInfo;
}
/// <summary>
/// Returns a value indicating whether or not the provided assembly is the Orleans assembly or references it.
/// </summary>
/// <param name="assembly">The assembly.</param>
/// <returns>A value indicating whether or not the provided assembly is the Orleans assembly or references it.</returns>
internal static bool IsOrleansOrReferencesOrleans(Assembly assembly)
{
// We want to be loosely coupled to the assembly version if an assembly depends on an older Orleans,
// but we want a strong assembly match for the Orleans binary itself
// (so we don't load 2 different versions of Orleans by mistake)
var references = assembly.GetReferencedAssemblies();
return DoReferencesContain(references, OrleansCoreAssembly) || DoReferencesContain(references, OrleansAbstractionsAssembly)
|| string.Equals(assembly.GetName().FullName, OrleansCoreAssembly.FullName, StringComparison.Ordinal);
}
/// <summary>
/// Returns a value indicating whether or not the specified references contain the provided assembly name.
/// </summary>
/// <param name="references">The references.</param>
/// <param name="assemblyName">The assembly name.</param>
/// <returns>A value indicating whether or not the specified references contain the provided assembly name.</returns>
private static bool DoReferencesContain(IReadOnlyCollection<AssemblyName> references, AssemblyName assemblyName)
{
if (references.Count == 0)
{
return false;
}
return references.Any(asm => string.Equals(asm.Name, assemblyName.Name, StringComparison.Ordinal));
}
/// <summary>Returns the types referenced by the provided <paramref name="type"/>.</summary>
/// <param name="type">The type.</param>
/// <param name="includeMethods">Whether or not to include the types referenced in the methods of this type.</param>
/// <param name="exclude">Types to exclude</param>
/// <returns>The types referenced by the provided <paramref name="type"/>.</returns>
private static IEnumerable<Type> GetTypes(
this Type type,
bool includeMethods,
HashSet<Type> exclude)
{
exclude = exclude ?? new HashSet<Type>();
if (!exclude.Add(type))
{
yield break;
}
yield return type;
if (type.IsArray)
{
foreach (var elementType in type.GetElementType().GetTypes(false, exclude: exclude))
{
yield return elementType;
}
}
if (type.IsConstructedGenericType)
{
foreach (var genericTypeArgument in
type.GetGenericArguments().SelectMany(_ => GetTypes(_, false, exclude: exclude)))
{
yield return genericTypeArgument;
}
}
if (!includeMethods)
{
yield break;
}
foreach (var method in type.GetMethods())
{
foreach (var referencedType in GetTypes(method.ReturnType, false, exclude: exclude))
{
yield return referencedType;
}
foreach (var parameter in method.GetParameters())
{
foreach (var referencedType in GetTypes(parameter.ParameterType, false, exclude: exclude))
{
yield return referencedType;
}
}
}
}
private static string EscapeIdentifier(string identifier)
{
if (IsCSharpKeyword(identifier)) return "@" + identifier;
return identifier;
}
internal static bool IsCSharpKeyword(string identifier)
{
switch (identifier)
{
case "abstract":
case "add":
case "alias":
case "as":
case "ascending":
case "async":
case "await":
case "base":
case "bool":
case "break":
case "byte":
case "case":
case "catch":
case "char":
case "checked":
case "class":
case "const":
case "continue":
case "decimal":
case "default":
case "delegate":
case "descending":
case "do":
case "double":
case "dynamic":
case "else":
case "enum":
case "event":
case "explicit":
case "extern":
case "false":
case "finally":
case "fixed":
case "float":
case "for":
case "foreach":
case "from":
case "get":
case "global":
case "goto":
case "group":
case "if":
case "implicit":
case "in":
case "int":
case "interface":
case "internal":
case "into":
case "is":
case "join":
case "let":
case "lock":
case "long":
case "nameof":
case "namespace":
case "new":
case "null":
case "object":
case "operator":
case "orderby":
case "out":
case "override":
case "params":
case "partial":
case "private":
case "protected":
case "public":
case "readonly":
case "ref":
case "remove":
case "return":
case "sbyte":
case "sealed":
case "select":
case "set":
case "short":
case "sizeof":
case "stackalloc":
case "static":
case "string":
case "struct":
case "switch":
case "this":
case "throw":
case "true":
case "try":
case "typeof":
case "uint":
case "ulong":
case "unchecked":
case "unsafe":
case "ushort":
case "using":
case "value":
case "var":
case "virtual":
case "void":
case "volatile":
case "when":
case "where":
case "while":
case "yield":
return true;
default:
return false;
}
}
}
}
| |
using Ocelot.DownstreamRouteFinder.UrlMatcher;
using Ocelot.Responses;
using Shouldly;
using System.Collections.Generic;
using System.Linq;
using TestStack.BDDfy;
using Xunit;
namespace Ocelot.UnitTests.DownstreamRouteFinder.UrlMatcher
{
public class UrlPathPlaceholderNameAndValueFinderTests
{
private readonly IPlaceholderNameAndValueFinder _finder;
private string _downstreamUrlPath;
private string _downstreamPathTemplate;
private Response<List<PlaceholderNameAndValue>> _result;
private string _query;
public UrlPathPlaceholderNameAndValueFinderTests()
{
_finder = new UrlPathPlaceholderNameAndValueFinder();
}
[Fact]
public void can_match_down_stream_url()
{
this.Given(x => x.GivenIHaveAUpstreamPath(""))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate(""))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_nothing_then_placeholder_no_value_is_blank()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "")
};
this.Given(x => x.GivenIHaveAUpstreamPath(""))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_nothing_then_placeholder_value_is_test()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "test")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/test"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_match_everything_in_path_with_query()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{everything}", "test/toot")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot"))
.And(x => GivenIHaveAQuery("?$filter=Name%20eq%20'Sam'"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{everything}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_match_everything_in_path()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{everything}", "test/toot")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/test/toot"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{everything}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_forward_slash_then_placeholder_no_value_is_blank()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_forward_slash()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
};
this.Given(x => x.GivenIHaveAUpstreamPath("/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_forward_slash_then_placeholder_then_another_value()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{url}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/1/products"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/{url}/products"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_not_find_anything()
{
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void should_find_query_string()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAQuery("?productId=1"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products?productId={productId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_query_string_dont_include_hardcoded()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products?productId={productId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_multiple_query_string()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products?productId={productId}&categoryId={categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_multiple_query_string_and_path()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2"),
new PlaceholderNameAndValue("{account}", "3")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products/3"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products/{account}?productId={productId}&categoryId={categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void should_find_multiple_query_string_and_path_that_ends_with_slash()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2"),
new PlaceholderNameAndValue("{account}", "3")
};
this.Given(x => x.GivenIHaveAUpstreamPath("/products/3/"))
.And(x => x.GivenIHaveAQuery("?productId=1&categoryId=2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("/products/{account}/?productId={productId}&categoryId={categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_no_slash()
{
this.Given(x => x.GivenIHaveAUpstreamPath("api"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_one_slash()
{
this.Given(x => x.GivenIHaveAUpstreamPath("api/"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template()
{
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(new List<PlaceholderNameAndValue>()))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_one_place_holder()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_two_place_holders()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/2"))
.Given(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/{categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_two_place_holders_seperated_by_something()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/categories/{categoryId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_three_place_holders_seperated_by_something()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2"),
new PlaceholderNameAndValue("{variantId}", "123")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/123"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/categories/{categoryId}/variant/{variantId}"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_three_place_holders()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{productId}", "1"),
new PlaceholderNameAndValue("{categoryId}", "2")
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/1/categories/2/variant/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/product/products/{productId}/categories/{categoryId}/variant/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
[Fact]
public void can_match_down_stream_url_with_downstream_template_with_place_holder_to_final_url_path()
{
var expectedTemplates = new List<PlaceholderNameAndValue>
{
new PlaceholderNameAndValue("{finalUrlPath}", "product/products/categories/"),
};
this.Given(x => x.GivenIHaveAUpstreamPath("api/product/products/categories/"))
.And(x => x.GivenIHaveAnUpstreamUrlTemplate("api/{finalUrlPath}/"))
.When(x => x.WhenIFindTheUrlVariableNamesAndValues())
.And(x => x.ThenTheTemplatesVariablesAre(expectedTemplates))
.BDDfy();
}
private void ThenTheTemplatesVariablesAre(List<PlaceholderNameAndValue> expectedResults)
{
foreach (var expectedResult in expectedResults)
{
var result = _result.Data.First(t => t.Name == expectedResult.Name);
result.Value.ShouldBe(expectedResult.Value);
}
}
private void GivenIHaveAUpstreamPath(string downstreamPath)
{
_downstreamUrlPath = downstreamPath;
}
private void GivenIHaveAnUpstreamUrlTemplate(string downstreamUrlTemplate)
{
_downstreamPathTemplate = downstreamUrlTemplate;
}
private void WhenIFindTheUrlVariableNamesAndValues()
{
_result = _finder.Find(_downstreamUrlPath, _query, _downstreamPathTemplate);
}
private void GivenIHaveAQuery(string query)
{
_query = query;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace Sparrow.Binary
{
/// <summary>
/// Differently from the numeric representation a BitVector operation is left-aligned.
/// </summary>
[DebuggerDisplay("{ToDebugString()}")]
public class BitVector : IComparable<BitVector>, IEquatable<BitVector>
{
public const int BitsPerByte = 8;
public const int BitsPerWord = sizeof(ulong) * BitsPerByte;
public const int BytesPerWord = sizeof(ulong) / sizeof(byte);
public const uint Log2BitsPerWord = 6; // Math.Log( BitsPerWord, 2 )
public const uint WordMask = BitsPerWord - 1;
public const ulong Ones = 0xFFFFFFFFFFFFFFFFL;
public const uint FirstBitPosition = BitsPerWord - 1;
public const ulong FirstBitMask = 1UL << (int)FirstBitPosition;
public const ulong LastBitMask = 1UL;
public const uint LastBitPosition = 1;
public readonly ulong[] Bits;
public string ToDebugString()
{
unchecked
{
var builder = new StringBuilder();
if (this.Count <= BitsPerWord)
{
for (int i = 0; i < this.Count; i++)
builder.Append(this[i] ? 1 : 0);
}
else
{
int words = NumberOfWordsForBits(this.Count);
for (int i = 0; i < words; i++)
{
ulong v = this.GetWord(i);
builder.Append(v.ToString("X16"));
builder.Append(" ");
}
}
return builder.ToString();
}
}
private static ulong Reverse(ulong v)
{
int s = BitsPerWord; // bit size; must be power of 2
unchecked
{
ulong mask = (ulong)~0;
while ((s >>= 1) > 0)
{
mask ^= (mask << s);
v = ((v >> s) & mask) | ((v << s) & ~mask);
}
}
return v;
}
public BitVector(int size)
{
this.Count = size;
this.Bits = new ulong[size % BitVector.BitsPerWord == 0 ? size / BitVector.BitsPerWord : size / BitVector.BitsPerWord + 1];
}
protected BitVector(int size, params ulong[] values)
{
if (size / BitVector.BitsPerWord > values.Length)
throw new ArgumentException("The values passed as parameters does not have enough bits to fill the vector size.", nameof(values));
this.Count = size;
this.Bits = values;
}
public int Count
{
get;
private set;
}
public bool this[int idx]
{
get { return Get(idx); }
set { Set(idx, value); }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set(int idx)
{
Contract.Requires(idx >= 0 && idx < this.Count);
uint word = WordForBit(idx);
ulong mask = BitInWord(idx);
Bits[word] |= mask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Set(int idx, bool value)
{
Contract.Requires(idx >= 0 && idx < this.Count);
uint word = WordForBit(idx);
ulong mask = BitInWord(idx);
bool currentValue = (Bits[word] & mask) != 0;
if (currentValue != value)
Bits[word] ^= mask;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Get(int idx)
{
Contract.Requires(idx >= 0 && idx < this.Count);
uint word = WordForBit(idx);
ulong mask = BitInWord(idx);
return (Bits[word] & mask) != 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int GetByte(int idx)
{
int positionInWord = idx % BitVector.BytesPerWord;
ulong word = GetWord(idx / BitVector.BytesPerWord);
word <<= BitVector.BitsPerByte * positionInWord;
word >>= BitVector.BitsPerByte * (BitVector.BytesPerWord - 1);
return (int)word;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ulong GetWord(int wordIdx)
{
return Bits[wordIdx];
}
public void Fill(bool value)
{
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
unsafe
{
byte x = value ? (byte)0xFF : (byte)0x00;
fixed (ulong* array = this.Bits)
Memory.SetInline((byte*)array, x, this.Bits.Length * sizeof(ulong));
}
}
public void Fill(bool value, int from, int to)
{
Contract.Requires(from >= 0 && from < this.Count);
Contract.Requires(to >= 0 && to < this.Count);
Contract.Requires(from <= to);
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
unchecked
{
int bFrom = from / BitVector.BitsPerWord;
int bTo = to / BitVector.BitsPerWord;
if (bFrom == bTo)
{
ulong fill = (1UL << (to - from) - 1 << from);
if (value)
Bits[bFrom] |= fill;
else
Bits[bFrom] &= ~fill;
}
else
{
byte x = value ? (byte)0xFF : (byte)0x00;
unsafe
{
fixed (ulong* array = this.Bits)
Memory.SetInline((byte*)(array + bFrom + 1), x, bTo);
}
if (from % BitVector.BitsPerWord != 0)
{
if (value)
Bits[bFrom] |= (ulong)(-1L) << from % BitVector.BitsPerWord;
else
Bits[bFrom] &= (1UL << from % BitVector.BitsPerWord) - 1;
}
if (to % BitVector.BitsPerWord != 0)
{
if (value)
Bits[bTo] |= 1UL << to % BitVector.BitsPerWord - 1;
else
Bits[bTo] &= (ulong)(-1L) << to % BitVector.BitsPerWord;
}
}
}
}
public void Flip()
{
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
for (int i = 0; i < Bits.Length; i++)
Bits[i] ^= BitVector.Ones;
}
public void Flip(int idx)
{
Contract.Requires(idx >= 0 && idx < this.Count);
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
unchecked
{
uint wPos = WordForBit(idx);
Bits[wPos] ^= BitInWord((int)idx);
}
}
public void Flip(int from, int to)
{
Contract.Requires(from >= 0 && from < this.Count);
Contract.Requires(to >= 0 && to < this.Count);
Contract.Requires(from <= to);
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
unchecked
{
int bTo = to / BitVector.BitsPerWord;
int bFrom = from / BitVector.BitsPerWord;
if (bTo == bFrom)
{
if (from == to)
{
Bits[bFrom] ^= BitInWord((int)from);
}
else
{
ulong mask = Ones << BitVector.BitsPerWord - (to - from);
Bits[bFrom] ^= mask >> from;
}
}
else
{
int start = (from + BitVector.BitsPerWord - 1) / BitVector.BitsPerWord;
ulong mask = BitVector.Ones;
for (int i = bTo; i-- != start; )
Bits[i] ^= mask;
if (from % BitVector.BitsPerWord != 0)
Bits[bFrom] ^= (1UL << (BitVector.BitsPerWord - from) % BitVector.BitsPerWord) - 1;
if (to % BitVector.BitsPerWord != 0)
Bits[bTo] ^= Ones << BitVector.BitsPerWord - (to % BitVector.BitsPerWord);
}
}
}
public void Clear()
{
Array.Clear(this.Bits, 0, this.Bits.Length);
}
public BitVector And(BitVector v)
{
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
int words = Math.Min(Bits.Length, v.Bits.Length) - 1;
while (words >= 0)
{
Bits[words] &= v.Bits[words];
words--;
}
return this;
}
public BitVector Or(BitVector v)
{
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
int words = Math.Min(Bits.Length, v.Bits.Length) - 1;
while (words >= 0)
{
Bits[words] |= v.Bits[words];
words--;
}
return this;
}
public BitVector Xor(BitVector v)
{
// TODO: Avoid touching bits outside of the valid ones. (keep them as Zeroes)
int words = Math.Min(Bits.Length, v.Bits.Length) - 1;
while (words >= 0)
{
Bits[words] ^= v.Bits[words];
words--;
}
return this;
}
public static BitVector And(BitVector x, BitVector y)
{
if (x.Count < y.Count)
{
var t = new BitVector(x.Count);
x.CopyTo(t);
return t.And(y);
}
else
{
var t = new BitVector(y.Count);
y.CopyTo(t);
return t.And(x);
}
}
public static BitVector Or(BitVector x, BitVector y)
{
if (x.Count < y.Count)
{
var t = new BitVector(x.Count);
x.CopyTo(t);
return t.Or(y);
}
else
{
var t = new BitVector(y.Count);
y.CopyTo(t);
return t.Or(x);
}
}
public static BitVector Xor(BitVector x, BitVector y)
{
if (x.Count < y.Count)
{
var t = new BitVector(x.Count);
x.CopyTo(t);
return t.Xor(y);
}
else
{
var t = new BitVector(y.Count);
y.CopyTo(t);
return t.Xor(x);
}
}
public void CopyTo(BitVector dest)
{
Copy(this, dest);
}
public static void Copy(BitVector src, BitVector dest)
{
Contract.Requires(src.Count <= dest.Count);
dest.Count = src.Count;
unsafe
{
fixed (ulong* destPtr = dest.Bits)
fixed (ulong* srcPtr = src.Bits)
{
Memory.CopyInline((byte*)destPtr, (byte*)srcPtr, src.Bits.Length * sizeof(ulong));
}
}
}
private static void BitwiseCopySlow(BitVector src, int srcStart, BitVector dest, int destStart, int length)
{
unchecked
{
// Very inefficient. If this is a liability we will make it faster.
while ( length > 0 )
{
dest[destStart] = src[srcStart];
srcStart++;
destStart++;
length--;
}
}
}
public static BitVector OfLength(int size)
{
return new BitVector(size);
}
public static BitVector Of(bool prefixFree, params ulong[] values)
{
unsafe
{
fixed (ulong* ptr = values)
{
return Of(prefixFree, ptr, values.Length);
}
}
}
public static BitVector Of(params ulong[] values)
{
return Of(false, values);
}
public static BitVector Of(bool prefixFree, params uint[] values)
{
unsafe
{
fixed (uint* ptr = values)
{
return Of(prefixFree, ptr, values.Length);
}
}
}
public static BitVector Of(params uint[] values)
{
return Of(false, values);
}
public static BitVector Of(string value)
{
return Of(false, value);
}
public static BitVector Of(bool prefixFree, string value)
{
unsafe
{
fixed (char* ptr = value)
{
return Of(prefixFree, (ushort*)ptr, value.Length);
}
}
}
public static BitVector Of(bool prefixFree, params byte[] values)
{
unsafe
{
fixed (byte* ptr = values)
{
return Of(prefixFree, ptr, values.Length);
}
}
}
public static BitVector Of(params byte[] values)
{
return Of(false, values);
}
public unsafe static BitVector Of(bool prefixFree, ulong* values, int length)
{
int prefixAdjustment = (prefixFree ? 2 : 0);
ulong[] newValue = new ulong[length + prefixAdjustment];
fixed( ulong* newValuePtr = newValue)
{
Memory.CopyInline((byte*)newValuePtr, (byte*)values, length * sizeof(ulong));
}
return new BitVector(length * BitsPerWord + prefixAdjustment * BitVector.BitsPerByte, newValue);
}
public unsafe static BitVector Of(bool prefixFree, uint* values, int length)
{
int prefixAdjustment = (prefixFree ? 1 : 0);
int valueLength = length + prefixAdjustment;
int size = valueLength / 2;
if (valueLength % 2 != 0)
size++;
int lastLong = length / 2;
ulong[] newValue = new ulong[size];
for (int i = 0; i < lastLong; i++)
newValue[i] = (ulong)values[2 * i] << 32 | (ulong)values[2 * i + 1];
if (length % 2 == 1)
newValue[lastLong] = (ulong)values[length - 1] << 32;
return new BitVector(length * BitVector.BitsPerWord / 2 + prefixAdjustment * 2 * BitVector.BitsPerByte, newValue);
}
public unsafe static BitVector Of(bool prefixFree, ushort* values, int length)
{
int prefixAdjustment = (prefixFree ? 1 : 0);
int valueLength = length + prefixAdjustment;
int size = valueLength / 4;
if (valueLength % 4 != 0)
size++;
int position = 0;
int lastLong = length / 4;
ulong[] newValue = new ulong[size];
for (int i = 0; i < lastLong; i++)
{
newValue[i] = (ulong)values[position] << 48 | (ulong)values[position + 1] << 32 | (ulong)values[position + 2] << 16 | (ulong)values[position + 3];
position += 4;
}
switch (length % 4)
{
case 3: newValue[lastLong] = (ulong)values[position] << 48 | (ulong)values[position + 1] << 32 | (ulong)values[position + 2] << 16; break;
case 2: newValue[lastLong] = (ulong)values[position] << 48 | (ulong)values[position + 1] << 32; break;
case 1: newValue[lastLong] = (ulong)values[position] << 48; break;
default: break;
}
return new BitVector(valueLength * BitVector.BitsPerWord / 4, newValue);
}
public unsafe static BitVector Of(bool prefixFree, byte* values, int length)
{
int prefixAdjustment = (prefixFree ? 2 : 0);
int size = (length + prefixAdjustment) / 8;
int extraBytes = (length + prefixAdjustment) % sizeof(ulong);
if (extraBytes != 0)
size++;
ulong[] newValue = new ulong[size];
int lastLong = length / sizeof(ulong);
int position = 0;
for (int i = 0; i < lastLong; i++)
{
newValue[i] = (ulong)values[position] << 64 - 8 |
(ulong)values[position + 1] << 64 - 16 |
(ulong)values[position + 2] << 64 - 24 |
(ulong)values[position + 3] << 32 |
(ulong)values[position + 4] << 24 |
(ulong)values[position + 5] << 16 |
(ulong)values[position + 6] << 8 |
(ulong)values[position + 7];
position += sizeof(ulong);
}
int bytesLeft = length % sizeof(ulong);
if ( bytesLeft == 0)
{
if (lastLong != newValue.Length)
newValue[lastLong] = 0;
}
else
{
ulong lastValue = 0;
do
{
lastValue = lastValue << 8 | values[position];
position++;
bytesLeft--;
}
while (bytesLeft > 0);
newValue[lastLong] = lastValue << ((8 - length % sizeof(ulong)) * BitVector.BitsPerByte);
}
return new BitVector((length + prefixAdjustment) * BitVector.BitsPerByte, newValue);
}
public static BitVector Parse(string value)
{
var vector = new BitVector(value.Length);
for (int i = 0; i < value.Length; i++ )
{
if (value[i] != '0')
vector[i] = true;
}
return vector;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ulong BitInWord(int idx)
{
return 0x8000000000000000UL >> (idx % (int)BitVector.BitsPerWord);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint Bit(int idx)
{
Contract.Requires(idx < BitVector.BitsPerWord);
return WordMask & (uint)idx;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static uint WordForBit(int idx)
{
return (uint)(idx >> (int)Log2BitsPerWord);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int NumberOfWordsForBits(int size)
{
return (int)((size + WordMask) >> (int)Log2BitsPerWord);
}
public int CompareTo(BitVector other)
{
int bits;
return CompareToInline(other, out bits);
}
public int CompareTo(BitVector other, out int equalBits)
{
return CompareToInline(other, out equalBits);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int CompareToInline(BitVector other, out int equalBits)
{
var srcKey = this.Count;
var otherKey = other.Count;
var length = Math.Min(srcKey, otherKey);
unsafe
{
fixed (ulong* srcPtr = this.Bits)
fixed (ulong* destPtr = other.Bits)
{
int wholeBytes = length / BitsPerWord;
ulong* bpx = srcPtr;
ulong* bpy = destPtr;
for (int i = 0; i < wholeBytes; i++, bpx += 1, bpy += 1)
{
if (*((ulong*)bpx) != *((ulong*)bpy))
break;
}
// We always finish the last extent with a bit-wise comparison (bit vector is stored in big endian).
int from = (int)(bpx - srcPtr) * BitsPerWord;
int leftover = length - from;
if ( leftover == 0 )
{
equalBits = length;
return 0;
}
if (leftover > BitVector.BitsPerWord)
leftover = BitVector.BitsPerWord;
int shift = BitVector.BitsPerWord - leftover;
ulong thisWord = ((*bpx) >> shift);
ulong otherWord = ((*bpy) >> shift);
ulong cmp = thisWord ^ otherWord;
if (cmp == 0)
{
equalBits = length;
return 0;
}
int differentBit = Sparrow.Binary.Bits.MostSignificantBit(cmp);
equalBits = from + leftover - (differentBit + 1);
return thisWord > otherWord ? 1 : -1;
}
}
}
public int LongestCommonPrefixLength(BitVector other)
{
int differentBit;
CompareToInline( other, out differentBit );
return differentBit;
}
public BitVector SubVector(int start, int length)
{
Contract.Requires(start >= 0 && start < this.Count);
Contract.Requires(length >= 0 && start + length < this.Count);
var subVector = new BitVector(length);
if ( start % BitsPerWord == 0 )
{
int startWord = start / BitsPerWord;
int totalWords = length / BitsPerWord;
unsafe
{
fixed (ulong* sourcePtr = this.Bits)
fixed (ulong* destPtr = subVector.Bits)
{
Memory.Copy((byte*)destPtr, (byte*)(sourcePtr + startWord), totalWords * sizeof(ulong));
}
}
int remainder = length % BitsPerWord;
if ( remainder != 0 )
{
int shift = BitsPerWord - remainder;
ulong value = this.Bits[startWord + totalWords];
value = (value >> shift) << shift;
subVector.Bits[totalWords] = value;
}
}
else
{
// The cost to optimize this case is high and we are not using it.
BitVector.BitwiseCopySlow(this, start, subVector, 0, length);
}
return subVector;
}
public bool IsPrefix(BitVector other)
{
if (this.Count > other.Count)
return false;
int equalBits;
CompareToInline(other, out equalBits);
return equalBits == this.Count;
}
public bool IsPrefix(BitVector other, int length)
{
if (length > this.Count || length > other.Count)
return false;
int equalBits;
CompareToInline(other, out equalBits);
return equalBits >= length;
}
public bool IsProperPrefix(BitVector other)
{
if (this.Count >= other.Count)
return false;
int equalBits;
CompareToInline(other, out equalBits);
return equalBits == this.Count && equalBits != other.Count;
}
public bool Equals(BitVector other)
{
if (other == null) return false;
if (this == other) return true;
int dummy;
return CompareToInline(other, out dummy) == 0;
}
public string ToBinaryString()
{
var builder = new StringBuilder();
for ( int i = 0; i < this.Count; i++ )
{
if (i != 0 && i % 8 == 0)
builder.Append(" ");
builder.Append( this[i] ? "1" : "0");
}
return builder.ToString();
}
}
}
| |
using FlaUI.Core.AutomationElements;
using FlaUI.Core.AutomationElements.Infrastructure;
using FlaUI.Core.Definitions;
using FlaUI.Core.Input;
using FlaUI.Core.Tools;
using FlaUI.Core.WindowsAPI;
using System;
using System.Linq;
using VcEngineAutomation.Extensions;
using VcEngineAutomation.Panels;
using Button = FlaUI.Core.AutomationElements.Button;
using CheckBox = FlaUI.Core.AutomationElements.CheckBox;
using ComboBox = FlaUI.Core.AutomationElements.ComboBox;
using Menu = FlaUI.Core.AutomationElements.Menu;
using MenuItem = FlaUI.Core.AutomationElements.MenuItem;
using TextBox = FlaUI.Core.AutomationElements.TextBox;
namespace VcEngineAutomation.Ribbons
{
public class RibbonTab
{
private readonly VcEngine vcEngine;
private AutomationElement[] cachedRibbonGroups;
public RibbonTab(VcEngine vcEngine, TabItem tabItem)
{
this.vcEngine = vcEngine;
TabPage = tabItem;
}
public TabItem TabPage { get; }
public string AutomationId { get; set; }
public bool IsSelected => TabPage.IsSelected;
public void Select()
{
Wait.UntilResponsive(TabPage, VcEngine.DefaultTimeout);
if (!TabPage.IsSelected)
{
Mouse.LeftClick(TabPage.GetCenter());
Wait.UntilResponsive(TabPage, VcEngine.DefaultTimeout);
if (!TabPage.IsSelected)
{
if (this != vcEngine.Ribbon.HomeTab)
{
vcEngine.Ribbon.HomeTab.Select();
Wait.UntilResponsive(TabPage, VcEngine.DefaultTimeout);
}
Mouse.LeftClick(TabPage.GetCenter());
Wait.UntilResponsive(TabPage, VcEngine.DefaultTimeout);
if (!TabPage.IsSelected) throw new InvalidOperationException($"Ribbon tab ({AutomationId}) was not selected");
}
}
}
public AutomationElement[] Groups()
{
Select();
if (cachedRibbonGroups == null)
{
cachedRibbonGroups = TabPage.FindAllChildren(cf => cf.ByClassName("RibbonGroup"));
if (!cachedRibbonGroups.Any()) throw new InvalidOperationException($"Ribbon tab ({AutomationId}) does not contain ribbon group '{TabPage.Properties.AutomationId.Value}'");
}
return cachedRibbonGroups;
}
//[Obsolete("Use FindAutomationElement instead, as it will replace this method in future")]
public AutomationElement Group(int groupIndex)
{
AutomationElement[] groups = Groups();
if (groups.Length <= groupIndex) throw new InvalidOperationException("No ribbon ribbonGroup at specified index");
return groups.ElementAt(groupIndex);
}
//[Obsolete("Use FindAutomationElement instead, as it will replace this method in future")]
public AutomationElement Group(string name)
{
AutomationElement[] groups = Groups();
string groupNames = string.Join("', '", groups.Select(i => i.Properties.Name.Value));
AutomationElement ribbonGroup = groups.FirstOrDefault(g => string.Equals(g.Properties.Name, name, StringComparison.OrdinalIgnoreCase));
if (ribbonGroup == null) throw new InvalidOperationException($"No ribbon group found named '{name}', available choices are '{groupNames}'");
return ribbonGroup;
}
//[Obsolete("Use FindAutomationElement instead, as it will replace this method in future")]
private AutomationElement[] GetGroupItems<T>(AutomationElement ribbonGroup) where T : AutomationElement
{
if (typeof(T) == typeof(Button))
{
return ribbonGroup.FindAllChildren(cf => cf.ByControlType(ControlType.Button));
}
if (typeof(T) == typeof(CheckBox))
{
return ribbonGroup.FindAllChildren(cf => cf.ByControlType(ControlType.CheckBox));
}
throw new InvalidOperationException($"Unknown type '{typeof(T)}'");
}
//[Obsolete("Use InvokeButtonByAutomationId, as it will replace this method in future")]
public void ClickButton(string groupName, string buttonName)
{
ClickButton(groupName, buttonName, null);
}
public void ClickButton(string groupName, string buttonName, TimeSpan? waitTimeSpan)
{
var button = FindButtonByName(groupName, buttonName);
if (!button.IsEnabled) throw new InvalidOperationException($"Ribbon button '{buttonName}' is not enabled");
Invoke(button);
vcEngine.WaitWhileBusy(waitTimeSpan);
}
//[Obsolete("Use FindButtonByAutomationId, as it will replace this method in future")]
public Button FindButtonByName(string groupName, string buttonName)
{
vcEngine.CheckForCrash();
AutomationElement[] buttons = GetGroupItems<Button>(Group(groupName));
string itemNames = string.Join("', '", buttons.Select(i => i.Properties.Name.Value));
Button button = buttons.FirstOrDefault(b => string.Equals(b.Properties.Name, buttonName, StringComparison.OrdinalIgnoreCase))?.AsButton();
if (button == null) throw new InvalidOperationException($"No ribbon button found named '{buttonName}', available choices are '{itemNames}'");
return button;
}
private void Invoke(AutomationElement button)
{
var className = button.Properties.ClassName.Value;
if (className == "ToggleButtonTool")
{
Wait.UntilResponsive(button, VcEngine.DefaultTimeout);
if (button.Patterns.Toggle.Pattern.ToggleState.Value != ToggleState.On)
{
button.Click(true);
Wait.UntilResponsive(button, VcEngine.DefaultTimeout);
}
}
else if (className == "ButtonTool")
{
button.Patterns.Invoke.Pattern.Invoke();
}
else
{
throw new InvalidOperationException($"Neither Toggle or Invoke is supported for button ({button.ToDebugString()})");
}
}
//[Obsolete("Use InvokeButtonByAutomationId, as it will replace this method in future")]
public void ClickButton(int groupIndex, int buttonIndex)
{
ClickButton(groupIndex, buttonIndex, null);
}
public void ClickButton(int groupIndex, int buttonIndex, TimeSpan? waitTimeSpan)
{
vcEngine.CheckForCrash();
AutomationElement[] buttons = GetGroupItems<Button>(Group(groupIndex));
if (buttons.Length <= buttonIndex) throw new InvalidOperationException($"No ribbon button found at index {buttonIndex}, number of buttons are {buttons.Length}");
Button button = buttons[buttonIndex].AsButton();
if (!button.IsEnabled) throw new InvalidOperationException($"Ribbon button at index {buttonIndex} is not enabled");
Invoke(button);
vcEngine.WaitWhileBusy(waitTimeSpan);
}
//[Obsolete("Use InvokeButtonByAutomationId, as it will replace this method in future")]
public void ClickButton(string groupName, int buttonIndex)
{
ClickButton(groupName, buttonIndex, null);
}
public void ClickButton(string groupName, int buttonIndex, TimeSpan? waitTimeSpan)
{
vcEngine.CheckForCrash();
AutomationElement[] buttons = GetGroupItems<Button>(Group(groupName));
if (buttons.Length <= buttonIndex) throw new InvalidOperationException($"No ribbon button found at index {buttonIndex}, number of buttons are {buttons.Length}");
Button button = buttons[buttonIndex].AsButton();
if (!button.IsEnabled) throw new InvalidOperationException($"Ribbon button at index {buttonIndex} is not enabled");
Invoke(button);
vcEngine.WaitWhileBusy(waitTimeSpan);
}
//[Obsolete("Use InvokeCommandPanelButtonByAutomationId, as it will replace this method in future")]
public CommandPanel ClickCommandPanelButton(string groupName, string buttonName)
{
return ClickCommandPanelButton(groupName, buttonName, null, null);
}
[Obsolete("Use ClickCommandPanelButton without starttitle parameter")]
public CommandPanel ClickCommandPanelButton(string groupName, string buttonName, string startOfTitle)
{
return ClickCommandPanelButton(groupName, buttonName, startOfTitle, null);
}
[Obsolete("Use ClickCommandPanelButton without starttitle parameter")]
public CommandPanel ClickCommandPanelButton(string groupName, string buttonName, string startOfTitle, TimeSpan? waitTimeSpan)
{
ClickButton(groupName, buttonName, waitTimeSpan);
return vcEngine.GetCommandPanel();
}
//[Obsolete("Use InvokeCommandPanelButtonByAutomationId, as it will replace this method in future")]
public CommandPanel ClickCommandPanelButton(string groupName, int buttonIndex)
{
return ClickCommandPanelButton(groupName, buttonIndex, null, null);
}
[Obsolete("Use ClickCommandPanelButton without starttitle parameter")]
public CommandPanel ClickCommandPanelButton(string groupName, int buttonIndex, string startOfTitle)
{
return ClickCommandPanelButton(groupName, buttonIndex, startOfTitle, null);
}
[Obsolete("Use ClickCommandPanelButton without starttitle parameter")]
public CommandPanel ClickCommandPanelButton(string groupName, int buttonIndex, string startOfTitle, TimeSpan? waitTimeSpan)
{
ClickButton(groupName, buttonIndex, waitTimeSpan);
return vcEngine.GetCommandPanel();
}
public void SelectBigDropdownItem(string groupName, int index, int menuIndex)
{
SelectBigDropdownItem(groupName, index, menuIndex, null);
}
public void SelectBigDropdownItem(string groupName, int index, int menuIndex, TimeSpan? waitTimeSpan)
{
Menu menu = Group(groupName).FindAllChildren().ElementAtOrDefault(index)?.AsMenu();
if (menu == null) throw new InvalidOperationException("No ribbon menu at specified index");
if (!menu.IsEnabled) throw new InvalidOperationException("Ribbon menu item is not enabled");
Window popup = vcEngine.MainWindow.GetCreatedWindowsForAction(() => menu.AsComboBox().Expand()).First();
AutomationElement[] elements = popup.FindAllDescendants(cf => cf.ByControlType(ControlType.MenuItem));
if (elements.Length < menuIndex) throw new InvalidOperationException($"no menu item found at index '{menuIndex}'");
MenuItem menuItem = elements[menuIndex].AsMenuItem();
menuItem?.Invoke();
vcEngine.WaitWhileBusy(waitTimeSpan);
}
public void SelectBigDropdownItem(string groupName, int index, params string[] text)
{
SelectBigDropdownItem(groupName, index, null, text);
}
public void SelectBigDropdownItem(string groupName, int index, TimeSpan? waitTimeSpan, params string[] text)
{
Menu menu = Group(groupName).FindAllChildren().ElementAtOrDefault(index)?.AsMenu();
if (menu == null) throw new InvalidOperationException("No ribbon menu at specified index");
if (!menu.IsEnabled) throw new InvalidOperationException("Ribbon menu item is not enabled");
if (menu.Properties.Name == text.Last()) return;
Window popup = vcEngine.MainWindow.GetCreatedWindowsForAction(() => menu.AsComboBox().Expand()).First();
MenuItem[] menuItems = popup.FindAllChildren(cf => cf.ByControlType(ControlType.MenuItem)).Select(ae => ae.AsMenuItem()).ToArray();
MenuItem menuItem = null;
foreach (string s in text)
{
if (menuItems.Length == 0) throw new InvalidOperationException("No menu items found");
var menuItemsText = menuItems.Select(m => Tuple.Create(m, m.FindFirstDescendant(cf => cf.ByControlType(ControlType.Text)).AsLabel().Text)).ToArray();
menuItem = menuItemsText.Where(t => s.Equals(t.Item2, StringComparison.OrdinalIgnoreCase)).Select(t => t.Item1).FirstOrDefault();
if (menuItem == null) throw new InvalidOperationException($"No ribbon menu item found named '{s}' among '{string.Join("', '", menuItemsText.Select(t => t.Item2))}'");
if (s != text.Last())
{
menuItems = menuItem.Items.ToArray();
}
}
menuItem?.Invoke();
vcEngine.WaitWhileBusy(waitTimeSpan);
}
//[Obsolete("Use SelectDropdownItemByAutomationId, as it will replace this method in future")]
public void SelectDropdownItem(string groupName, string itemName, string text)
{
SelectDropdownItem(groupName, itemName, text, null);
}
public void SelectDropdownItem(string groupName, string itemName, string text, TimeSpan? waitTimeSpan)
{
GetDropdownMenuItem(FindMenu(groupName, itemName), text).Invoke();
vcEngine.WaitWhileBusy(waitTimeSpan);
}
//[Obsolete("Use SelectDropdownItemByAutomationId, as it will replace this method in future")]
public void SelectDropdownItem(string groupName, int itemIndex, string text)
{
SelectDropdownItem(groupName, itemIndex, text, null);
}
public void SelectDropdownItem(string groupName, int itemIndex, string text, TimeSpan? waitTimeSpan)
{
GetDropdownMenuItem(FindMenu(groupName, itemIndex), text).Invoke();
vcEngine.WaitWhileBusy(waitTimeSpan);
}
//[Obsolete("Use FindDropdownMenuItemByAutomationId, as it will replace this method in future")]
public void ToggleDropdownItem(string groupName, string itemName, string text, ToggleState toggleState)
{
ToggleDropdownItem(groupName, itemName, text, toggleState, null);
}
public void ToggleDropdownItem(string groupName, string itemName, string text, ToggleState toggleState, TimeSpan? waitTimeSpan)
{
Menu menu = FindMenu(groupName, itemName);
var togglePattern = GetDropdownMenuItem(menu, text).Patterns.Toggle.Pattern;
if (togglePattern.ToggleState != toggleState)
{
togglePattern.Toggle();
}
vcEngine.WaitWhileBusy(waitTimeSpan);
if (menu.Patterns.ExpandCollapse.Pattern.ExpandCollapseState.Value == ExpandCollapseState.Expanded)
{
// Disable as it throws an exception when collapsing
//menu.Patterns.ExpandCollapse.Pattern.Collapse();
menu.Click();
}
}
private MenuItem GetDropdownMenuItem(Menu menu, string text)
{
Window popup = vcEngine.MainWindow.GetCreatedWindowsForAction(() => menu.AsComboBox().Expand()).First();
MenuItem[] menuItems = popup.FindAllChildren(cf => cf.ByControlType(ControlType.MenuItem)).Select(ae => ae.AsMenuItem()).ToArray();
string menuItemNames = string.Join("', '", menuItems.Select(m => m.FindFirstChild().AsLabel().Text).ToArray());
MenuItem menuItem = menuItems.FirstOrDefault(m => m.FindFirstChild().AsLabel().Text.Equals(text, StringComparison.OrdinalIgnoreCase));
if (menuItem == null) throw new InvalidOperationException($"No ribbon menu item found named '{text}', available choices are '{menuItemNames}'");
return menuItem;
}
[Obsolete("Use SelectComboboxTextByAutomationId instead")]
public void SelectComboboxItem(string groupName, int itemIndex, string text)
{
AutomationElement item = Group(groupName).FindAllChildren().ElementAtOrDefault(itemIndex);
if (item == null) throw new InvalidOperationException($"No ribbon combobox found at specified index {itemIndex}");
ComboBox combobox = item.FindFirstDescendant(cf => cf.ByControlType(ControlType.ComboBox)).AsComboBox();
var comboboxItems = combobox?.Items.Select(i => Tuple.Create(i, i.FindFirstChild().AsLabel().Text)).ToArray();
var comboboxItem = comboboxItems?.FirstOrDefault(t => t.Item2.Equals(text, StringComparison.OrdinalIgnoreCase));
string itemNames = string.Join("', '", comboboxItems.Select(t => t.Item2).ToArray());
if (comboboxItem == null) throw new InvalidOperationException($"No list item found named '{text}', available choices are '{itemNames}'");
if (!comboboxItem.Item1.IsSelected)
{
comboboxItem.Item1.Select();
vcEngine.WaitWhileBusy();
}
}
public void SelectComboboxTextByAutomationId(string groupAutomationId, string automationId, string text)
{
var item = FindAutomationElementImpl(groupAutomationId, automationId);
ComboBox combobox = item.FindFirstDescendant(cf => cf.ByControlType(ControlType.ComboBox)).AsComboBox();
var comboboxItems = combobox?.Items.Select(i => Tuple.Create(i, i.FindFirstChild().AsLabel().Text)).ToArray();
var comboboxItem = comboboxItems?.FirstOrDefault(t => t.Item2.Equals(text, StringComparison.OrdinalIgnoreCase));
string itemNames = string.Join("', '", comboboxItems.Select(t => t.Item2).ToArray());
if (comboboxItem == null) throw new InvalidOperationException($"No list item found named '{text}', available choices are '{itemNames}'");
if (!comboboxItem.Item1.IsSelected)
{
comboboxItem.Item1.Select();
vcEngine.WaitWhileBusy();
}
}
[Obsolete("Use FindTextBoxByAutomationId, as it will replace this method in future")]
public TextBox FindTextBox(string groupName, int index)
{
AutomationElement element = Group(groupName).FindAllChildren(cf => cf.ByControlType(ControlType.Edit)).ElementAtOrDefault(index);
if (element == null) throw new InvalidOperationException($"No text box found in group '{groupName}' at index {index}");
Wait.UntilResponsive(element, VcEngine.DefaultTimeout);
return element.AsTextBox();
}
[Obsolete("Use EnterTextBoxByAutomationId, as it will replace this method in future")]
public void EnterIntoTexBox(string groupName, int index, string text)
{
TextBox textbox = FindTextBox(groupName, index);
if (!textbox.IsEnabled) throw new InvalidOperationException($"Text box {groupName} at index {index} was not enabled");
Wait.UntilResponsive(textbox, VcEngine.DefaultTimeout);
textbox.Text = text;
}
[Obsolete("Use FindComboBoxByAutomationId, as it will replace this method in future")]
public ComboBox FindComboBox(string groupName, int index)
{
AutomationElement element = Group(groupName).FindAllDescendants(cf => cf.ByClassName("ComboBox").And(cf.ByAutomationId("PART_FocusSite"))).ElementAtOrDefault(index);
if (element == null) throw new InvalidOperationException($"No text combo box found in group '{groupName}' at index {index}");
Wait.UntilResponsive(element, VcEngine.DefaultTimeout);
element.Click();
Wait.UntilResponsive(element, VcEngine.DefaultTimeout);
return element.AsComboBox();
}
[Obsolete("Use FindCheckBoxByAutomationId, as it will replace this method in future")]
public CheckBox FindCheckBox(string groupName, int index)
{
AutomationElement element = Group(groupName).FindAllChildren(cf => cf.ByClassName("ToggleButtonTool")).ElementAtOrDefault(index);
if (element == null) throw new InvalidOperationException($"No check box found in group '{groupName}' at index {index}");
Wait.UntilResponsive(element, VcEngine.DefaultTimeout);
return element.AsCheckBox();
}
[Obsolete("Use FindCheckBoxByAutomationId, as it will replace this method in future")]
public CheckBox FindCheckBox(string groupName, string labelName)
{
AutomationElement element = Group(groupName).FindFirstDescendant(cf => cf.ByClassName("ToggleButtonTool").And(cf.ByName(labelName)));
if (element == null) throw new InvalidOperationException($"No check box found in group '{groupName}' with name {labelName}");
Wait.UntilResponsive(element, VcEngine.DefaultTimeout);
return element.AsCheckBox();
}
[Obsolete("Use FindMenuByAutomationId, as it will replace this method in future")]
public Menu FindMenu(string groupName, string itemName)
{
AutomationElement[] menues = Group(groupName).FindAllChildren();
string itemNames = string.Join("', '", menues.Select(i => i.Properties.Name.Value));
Menu menu = menues.FirstOrDefault(b => string.Equals(b.Properties.Name, itemName, StringComparison.OrdinalIgnoreCase))?.AsMenu();
if (menu == null) throw new InvalidOperationException($"No ribbon menu found named '{itemName}', available choices are '{itemNames}'");
return menu;
}
[Obsolete("Use FindMenuByAutomationId, as it will replace this method in future")]
public Menu FindMenu(string groupName, int itemIndex)
{
var elements = Group(groupName).FindAllChildren();
if (elements.Length <= itemIndex) throw new InvalidOperationException($"No ribbon menu found at the specified index {itemIndex}");
return elements[itemIndex].AsMenu();
}
[Obsolete("Use FindDropdownMenuItemByAutomationId, as it will replace this method in future")]
public MenuItem FindDropdownMenuItem(string groupName, string itemName, string text)
{
return GetDropdownMenuItem(FindMenu(groupName, itemName), text);
}
public AutomationElement FindAutomationElement(string groupAutomationId, string itemAutomationId)
{
vcEngine.CheckForCrash();
Select();
var automationElement = vcEngine.IsR9OrAbove
? TabPage.FindFirstChild(cf => cf.ByAutomationId($"{TabPage.AutomationId}{groupAutomationId}"))?.FindFirstChild(cf => cf.ByAutomationId($"{TabPage.AutomationId}{groupAutomationId}{itemAutomationId}"))
: TabPage.FindFirstDescendant(cf => cf.ByAutomationId($"{TabPage.AutomationId}{groupAutomationId}{itemAutomationId}"));
if (automationElement != null)
{
Wait.UntilResponsive(automationElement, VcEngine.DefaultTimeout);
}
return automationElement;
}
private AutomationElement FindAutomationElementImpl(string groupAutomationId, string automationId)
{
var automationElement = FindAutomationElement(groupAutomationId, automationId);
if (automationElement == null) throw new InvalidOperationException($"No control found with AutomationId={automationId}");
return automationElement;
}
public TextBox FindTextBoxByAutomationId(string groupAutomationId, string automationId)
{
return FindAutomationElementImpl(groupAutomationId, automationId).AsTextBox();
}
public void EnterIntoTexBoxByAutomationId(string groupAutomationId, string automationId, string text)
{
TextBox textbox = FindTextBoxByAutomationId(groupAutomationId, automationId);
if (!textbox.IsEnabled) throw new InvalidOperationException($"Text box {automationId} was not enabled");
Wait.UntilResponsive(textbox, VcEngine.DefaultTimeout);
textbox.Text = text;
Keyboard.Type(VirtualKeyShort.ENTER);
}
public CheckBox FindCheckBoxByAutomationId(string groupAutomationId, string automationId)
{
return FindAutomationElementImpl(groupAutomationId, automationId).AsCheckBox();
}
public Button FindButtonByAutomationId(string groupAutomationId, string automationId)
{
return FindAutomationElementImpl(groupAutomationId, automationId).AsButton();
}
public ComboBox FindComboBoxByAutomationId(string groupAutomationId, string automationId)
{
return FindAutomationElementImpl(groupAutomationId, automationId).FindFirstChild(cf => cf.ByControlType(ControlType.ComboBox)).AsComboBox();
}
public Menu FindMenuByAutomationId(string groupAutomationId, string automationId)
{
return FindAutomationElement(groupAutomationId, automationId).AsMenu();
}
public void InvokeButtonByAutomationId(string groupAutomationId, string automationId)
{
InvokeButtonByAutomationId(groupAutomationId, automationId, null);
}
public void InvokeButtonByAutomationId(string groupAutomationId, string automationId, TimeSpan? waitTimeSpan)
{
var button = FindAutomationElementImpl(groupAutomationId, automationId).AsButton();
if (!button.IsEnabled) throw new InvalidOperationException($"Ribbon button with automationId='{automationId}' is not enabled");
Invoke(button);
vcEngine.WaitWhileBusy(waitTimeSpan);
}
public CommandPanel InvokeCommandPanelButtonByAutomationId(string groupAutomationId, string automationId)
{
return InvokeCommandPanelButtonByAutomationId(groupAutomationId, automationId, null);
}
public CommandPanel InvokeCommandPanelButtonByAutomationId(string groupAutomationId, string automationId, TimeSpan? waitTimeSpan)
{
InvokeButtonByAutomationId(groupAutomationId, automationId, waitTimeSpan);
return vcEngine.GetCommandPanel();
}
public MenuItem FindDropdownMenuItemByAutomationId(string groupAutomationId, string menuAutomationId, string menuItemAutomationId)
{
var menu = FindAutomationElementImpl(groupAutomationId, menuAutomationId).AsMenu();
return FindDropdownMenuItemByAutomationId(menu, menuItemAutomationId);
}
private MenuItem FindDropdownMenuItemByAutomationId(Menu menu, string automationId)
{
Window popup = vcEngine.MainWindow.GetCreatedWindowsForAction(() => menu.AsComboBox().Expand()).First();
var menuItem = popup.FindFirstDescendant(cf => cf.ByAutomationId(automationId))?.AsMenuItem();
if (menuItem == null) throw new InvalidOperationException($"No ribbon menu item with automationId='{automationId}'");
return menuItem;
}
public void ToggleDropdownItemByAutomationId(string groupAutomationId, string menuAutomationId, string menuItemAutiomationId, ToggleState toggleState)
{
ToggleDropdownItemByAutomationId(groupAutomationId, menuAutomationId, menuItemAutiomationId, toggleState, null);
}
public void ToggleDropdownItemByAutomationId(string groupAutomationId, string menuAutomationId, string menuItemAutiomationId, ToggleState toggleState, TimeSpan? waitTimeSpan)
{
var menu = FindAutomationElementImpl(groupAutomationId, menuAutomationId).AsMenu();
var togglePattern = FindDropdownMenuItemByAutomationId(menu, menuItemAutiomationId).Patterns.Toggle.Pattern;
if (togglePattern.ToggleState != toggleState)
{
togglePattern.Toggle();
vcEngine.WaitWhileBusy(waitTimeSpan);
}
if (menu.Patterns.ExpandCollapse.Pattern.ExpandCollapseState.Value == ExpandCollapseState.Expanded)
{
// Disable as it throws an exception when collapsing
Retry.WhileException(() => menu.Patterns.ExpandCollapse.Pattern.Collapse(), VcEngine.DefaultTimeout, VcEngine.DefaultRetryInternal);
//menu.Click();
}
}
}
}
| |
namespace Fonet.Render.Pdf.Fonts {
internal class Symbol : Base14Font {
private static readonly int[] CodePointWidths;
private static readonly CodePointMapping DefaultMapping
= CodePointMapping.GetMapping("SymbolEncoding");
public Symbol()
: base("Symbol", null, 1010, 1010, -293, 32, 255, CodePointWidths, DefaultMapping) {}
static Symbol() {
CodePointWidths = new int[256];
CodePointWidths[0x0020] = 250;
CodePointWidths[0x0021] = 333;
CodePointWidths[0x22] = 713;
CodePointWidths[0x0023] = 500;
CodePointWidths[0x24] = 549;
CodePointWidths[0x0025] = 833;
CodePointWidths[0x0026] = 778;
CodePointWidths[0x27] = 439;
CodePointWidths[0x0028] = 333;
CodePointWidths[0x0029] = 333;
CodePointWidths[0x2A] = 500;
CodePointWidths[0x002B] = 549;
CodePointWidths[0x002C] = 250;
CodePointWidths[0x2D] = 549;
CodePointWidths[0x002E] = 250;
CodePointWidths[0x002F] = 278;
CodePointWidths[0x0030] = 500;
CodePointWidths[0x0031] = 500;
CodePointWidths[0x0032] = 500;
CodePointWidths[0x0033] = 500;
CodePointWidths[0x0034] = 500;
CodePointWidths[0x0035] = 500;
CodePointWidths[0x0036] = 500;
CodePointWidths[0x0037] = 500;
CodePointWidths[0x0038] = 500;
CodePointWidths[0x0039] = 500;
CodePointWidths[0x003A] = 278;
CodePointWidths[0x003B] = 278;
CodePointWidths[0x003C] = 549;
CodePointWidths[0x003D] = 549;
CodePointWidths[0x003E] = 549;
CodePointWidths[0x003F] = 444;
CodePointWidths[0x40] = 549;
CodePointWidths[0x41] = 722;
CodePointWidths[0x42] = 667;
CodePointWidths[0x43] = 722;
CodePointWidths[0x44] = 612;
CodePointWidths[0x45] = 611;
CodePointWidths[0x46] = 763;
CodePointWidths[0x47] = 603;
CodePointWidths[0x48] = 722;
CodePointWidths[0x49] = 333;
CodePointWidths[0x4A] = 631;
CodePointWidths[0x4B] = 722;
CodePointWidths[0x4C] = 686;
CodePointWidths[0x4D] = 889;
CodePointWidths[0x4E] = 722;
CodePointWidths[0x4F] = 722;
CodePointWidths[0x50] = 768;
CodePointWidths[0x51] = 741;
CodePointWidths[0x52] = 556;
CodePointWidths[0x53] = 592;
CodePointWidths[0x54] = 611;
CodePointWidths[0x55] = 690;
CodePointWidths[0x56] = 439;
CodePointWidths[0x57] = 768;
CodePointWidths[0x58] = 645;
CodePointWidths[0x59] = 795;
CodePointWidths[0x5A] = 611;
CodePointWidths[0x005B] = 333;
CodePointWidths[0x5C] = 863;
CodePointWidths[0x005D] = 333;
CodePointWidths[0x5E] = 658;
CodePointWidths[0x005F] = 500;
CodePointWidths[0x60] = 500;
CodePointWidths[0x61] = 631;
CodePointWidths[0x62] = 549;
CodePointWidths[0x63] = 549;
CodePointWidths[0x64] = 494;
CodePointWidths[0x65] = 439;
CodePointWidths[0x66] = 521;
CodePointWidths[0x67] = 411;
CodePointWidths[0x68] = 603;
CodePointWidths[0x69] = 329;
CodePointWidths[0x6A] = 603;
CodePointWidths[0x6B] = 549;
CodePointWidths[0x6C] = 549;
CodePointWidths[0x006D] = 576;
CodePointWidths[0x00B5] = 576;
CodePointWidths[0x6E] = 521;
CodePointWidths[0x6F] = 549;
CodePointWidths[0x70] = 549;
CodePointWidths[0x71] = 521;
CodePointWidths[0x72] = 549;
CodePointWidths[0x73] = 603;
CodePointWidths[0x74] = 439;
CodePointWidths[0x75] = 576;
CodePointWidths[0x76] = 713;
CodePointWidths[0x77] = 686;
CodePointWidths[0x78] = 493;
CodePointWidths[0x79] = 686;
CodePointWidths[0x7A] = 494;
CodePointWidths[0x007B] = 480;
CodePointWidths[0x007C] = 200;
CodePointWidths[0x007D] = 480;
CodePointWidths[0x7E] = 549;
CodePointWidths[0xA1] = 620;
CodePointWidths[0xA2] = 247;
CodePointWidths[0xA3] = 549;
CodePointWidths[0xA4] = 167;
CodePointWidths[0xA5] = 713;
CodePointWidths[0x0083] = 500;
CodePointWidths[0xA7] = 753;
CodePointWidths[0xA8] = 753;
CodePointWidths[0xA9] = 753;
CodePointWidths[0xAA] = 753;
CodePointWidths[0xAB] = 1042;
CodePointWidths[0xAC] = 987;
CodePointWidths[0xAD] = 603;
CodePointWidths[0xAE] = 987;
CodePointWidths[0xAF] = 603;
CodePointWidths[0x00B0] = 400;
CodePointWidths[0x00B1] = 549;
CodePointWidths[0xB2] = 411;
CodePointWidths[0xB3] = 549;
CodePointWidths[0x00D7] = 549;
CodePointWidths[0xB5] = 713;
CodePointWidths[0xB6] = 494;
CodePointWidths[0x0095] = 460;
CodePointWidths[0x00F7] = 549;
CodePointWidths[0xB9] = 549;
CodePointWidths[0xBA] = 549;
CodePointWidths[0xBB] = 549;
CodePointWidths[0x0085] = 1000;
CodePointWidths[0xBD] = 603;
CodePointWidths[0xBE] = 1000;
CodePointWidths[0xBF] = 658;
CodePointWidths[0xC0] = 823;
CodePointWidths[0xC1] = 686;
CodePointWidths[0xC2] = 795;
CodePointWidths[0xC3] = 987;
CodePointWidths[0xC4] = 768;
CodePointWidths[0xC5] = 768;
CodePointWidths[0xC6] = 823;
CodePointWidths[0xC7] = 768;
CodePointWidths[0xC8] = 768;
CodePointWidths[0xC9] = 713;
CodePointWidths[0xCA] = 713;
CodePointWidths[0xCB] = 713;
CodePointWidths[0xCC] = 713;
CodePointWidths[0xCD] = 713;
CodePointWidths[0xCE] = 713;
CodePointWidths[0xCF] = 713;
CodePointWidths[0xD0] = 768;
CodePointWidths[0xD1] = 713;
CodePointWidths[0xD2] = 790;
CodePointWidths[0xD3] = 790;
CodePointWidths[0xD4] = 890;
CodePointWidths[0xD5] = 823;
CodePointWidths[0xD6] = 549;
CodePointWidths[0xD7] = 250;
CodePointWidths[0x00AC] = 713;
CodePointWidths[0xD9] = 603;
CodePointWidths[0xDA] = 603;
CodePointWidths[0xDB] = 1042;
CodePointWidths[0xDC] = 987;
CodePointWidths[0xDD] = 603;
CodePointWidths[0xDE] = 987;
CodePointWidths[0xDF] = 603;
CodePointWidths[0xE0] = 494;
CodePointWidths[0xE1] = 329;
CodePointWidths[0xE2] = 790;
CodePointWidths[0xE3] = 790;
CodePointWidths[0xE4] = 786;
CodePointWidths[0xE5] = 713;
CodePointWidths[0xE6] = 384;
CodePointWidths[0xE7] = 384;
CodePointWidths[0xE8] = 384;
CodePointWidths[0xE9] = 384;
CodePointWidths[0xEA] = 384;
CodePointWidths[0xEB] = 384;
CodePointWidths[0xEC] = 494;
CodePointWidths[0xED] = 494;
CodePointWidths[0xEE] = 494;
CodePointWidths[0xEF] = 494;
CodePointWidths[0xF1] = 329;
CodePointWidths[0xF2] = 274;
CodePointWidths[0xF3] = 686;
CodePointWidths[0xF4] = 686;
CodePointWidths[0xF5] = 686;
CodePointWidths[0xF6] = 384;
CodePointWidths[0xF7] = 384;
CodePointWidths[0xF8] = 384;
CodePointWidths[0xF9] = 384;
CodePointWidths[0xFA] = 384;
CodePointWidths[0xFB] = 384;
CodePointWidths[0xFC] = 494;
CodePointWidths[0xFD] = 494;
CodePointWidths[0xFE] = 494;
}
}
}
| |
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 MvxDemo.WebApi.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Data;
using System.Web.Security;
using System.Configuration.Provider;
using System.Collections.Specialized;
using System.Configuration;
using System.Diagnostics;
using System.Web;
using System.Globalization;
using System.Reflection;
using System.Runtime.Remoting;
using CsDO.Lib;
using System.Collections;
namespace CsDO.Membership
{
public sealed class CsDORoleProvider : RoleProvider
{
#region Private Fields
private Type _rolesObjectType;
internal PropertyInfo _Role_Name;
internal Type _UsersInRolesObjectType;
internal PropertyInfo _UsersInRoles_User;
internal PropertyInfo _UsersInRoles_Role;
private string assemblyName;
private string userType;
#endregion
#region Helper Functions
internal DataObject NewRole()
{
return (DataObject)Activator.CreateInstance(_rolesObjectType);
}
private PropertyInfo GetRoleProperty(Type customAttribute)
{
foreach (PropertyInfo pi in _rolesObjectType.GetProperties())
if (pi.GetType().GetCustomAttributes(customAttribute, true).Length > 0)
return pi;
return null;
}
internal DataObject NewUsersInRoles()
{
return (DataObject)Activator.CreateInstance(_UsersInRolesObjectType);
}
private PropertyInfo GetUsersInRolesProperty(Type customAttribute)
{
foreach (PropertyInfo pi in _UsersInRolesObjectType.GetProperties())
if (pi.GetType().GetCustomAttributes(customAttribute, true).Length > 0)
return pi;
return null;
}
internal DataObject GetRole(string rolename)
{
DataObject role = NewRole();
_Role_Name.SetValue(role, rolename, null);
role.find();
if (role.fetch())
return role;
else
return null;
}
internal void SetupParameters(string assemblyName, string roleObjectType, string usersInRolesObjectType)
{
ObjectHandle obj = Activator.CreateInstance(assemblyName, roleObjectType);
_rolesObjectType = obj.Unwrap().GetType();
if (!_rolesObjectType.IsSubclassOf(typeof(DataObject)) &&
_rolesObjectType != typeof(DataObject))
throw new ProviderException("Role Data Object should be a subtype of CsDO.Lib.DataObject .");
_Role_Name = GetRoleProperty(typeof(Role_Name));
if (_Role_Name == null)
throw new ProviderException("Role must have Name field.");
obj = Activator.CreateInstance(assemblyName, usersInRolesObjectType);
_UsersInRolesObjectType = obj.Unwrap().GetType();
if (!_UsersInRolesObjectType.IsSubclassOf(typeof(DataObject)) &&
_UsersInRolesObjectType != typeof(DataObject))
throw new ProviderException("Users In Roles Data Object should be a subtype of CsDO.Lib.DataObject .");
_UsersInRoles_User = GetUsersInRolesProperty(typeof(UsersInRoles_User));
if (_UsersInRoles_User == null)
throw new ProviderException("Role must have Name field.");
_UsersInRoles_Role = GetUsersInRolesProperty(typeof(UsersInRoles_Role));
if (_UsersInRoles_Role == null)
throw new ProviderException("Role must have Name field.");
}
#endregion
#region RoleProvider Properties
private string _ApplicationName;
public override string ApplicationName
{
get { return _ApplicationName; }
set { _ApplicationName = value; }
}
#endregion
#region RoleProvider Methods
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (name == null || name.Length == 0)
name = "CsDORoleProvider";
if (String.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "CsDO Role Provider");
}
// Initialize the abstract base class.
base.Initialize(name, config);
if (config["applicationName"] == null || config["applicationName"].Trim() == "")
{
_ApplicationName = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath;
}
else
{
_ApplicationName = config["applicationName"];
}
assemblyName = config["assemblyName"];
userType = config["userObjectType"];
SetupParameters(config["assemblyName"], config["roleObjectType"], config["usersInRolesObjectType"]);
}
public override void AddUsersToRoles(string[] usernames, string[] rolenames)
{
foreach (string rolename in rolenames)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role name not found.");
}
}
foreach (string username in usernames)
{
if (username.IndexOf(',') > 0)
{
throw new ArgumentException("User names cannot contain commas.");
}
foreach (string rolename in rolenames)
{
if (IsUserInRole(username, rolename))
{
throw new ProviderException("User is already in role.");
}
}
}
CsDOMembershipProvider mp = new CsDOMembershipProvider();
mp.SetupParameters(assemblyName, userType);
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
DataObject data = NewUsersInRoles();
_UsersInRoles_Role.SetValue(data, GetRole(rolename), null);
_UsersInRoles_User.SetValue(data, mp.GetUser(username), null);
data.insert();
}
}
}
public override void CreateRole(string rolename)
{
if (rolename.IndexOf(',') > 0)
{
throw new ArgumentException("Role names cannot contain commas.");
}
if (RoleExists(rolename))
{
throw new ProviderException("Role name already exists.");
}
DataObject data = NewRole();
_Role_Name.SetValue(data, rolename, null);
data.insert();
}
public override bool DeleteRole(string rolename, bool throwOnPopulatedRole)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role does not exist.");
}
if (throwOnPopulatedRole && GetUsersInRole(rolename).Length > 0)
{
throw new ProviderException("Cannot delete a populated role.");
}
DataObject data = NewRole();
_UsersInRoles_Role.SetValue(data, rolename, null);
data.find();
data.fetch();
DataObject usersInRoles = NewUsersInRoles();
_UsersInRoles_Role.SetValue(usersInRoles, data, null);
IList users = usersInRoles.ToArray(true);
foreach (DataObject user in users)
if (!user.delete())
return false;
return data.delete();
}
public override string[] GetAllRoles()
{
string tmpRoleNames = "";
DataObject data = NewRole();
IList roles = data.ToArray(true);
foreach (DataObject role in roles)
tmpRoleNames += _Role_Name.GetValue(role, null).ToString();
if (tmpRoleNames.Length > 0)
{
tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
return tmpRoleNames.Split(',');
}
return new string[0];
}
public override string[] GetRolesForUser(string username)
{
string tmpRoleNames = "";
DataObject data = NewRole();
_UsersInRoles_User.SetValue(data, username, null);
IList roles = data.ToArray(true);
foreach(DataObject role in roles)
{
tmpRoleNames += _Role_Name.GetValue(
_UsersInRoles_Role.GetValue(role, null), null).ToString() + ",";
}
if (tmpRoleNames.Length > 0)
{
// Remove trailing comma.
tmpRoleNames = tmpRoleNames.Substring(0, tmpRoleNames.Length - 1);
return tmpRoleNames.Split(',');
}
return new string[0];
}
public override string[] GetUsersInRole(string rolename)
{
string tmpUserNames = "";
DataObject data = NewRole();
_UsersInRoles_Role.SetValue(data, rolename, null);
IList users = data.ToArray(true);
foreach(DataObject user in users)
{
CsDOMembershipProvider mp = new CsDOMembershipProvider();
mp.SetupParameters(assemblyName, userType);
tmpUserNames += mp._User_Name.GetValue(
_UsersInRoles_User.GetValue(user, null), null).ToString() + ",";
}
if (tmpUserNames.Length > 0)
{
// Remove trailing comma.
tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1);
return tmpUserNames.Split(',');
}
return new string[0];
}
public override bool IsUserInRole(string username, string rolename)
{
bool userIsInRole = false;
DataObject data = NewRole();
_UsersInRoles_Role.SetValue(data, rolename, null);
_UsersInRoles_User.SetValue(data, username, null);
IList users = data.ToArray(true);
if (users.Count > 0)
{
userIsInRole = true;
}
return userIsInRole;
}
public override void RemoveUsersFromRoles(string[] usernames, string[] rolenames)
{
foreach (string rolename in rolenames)
{
if (!RoleExists(rolename))
{
throw new ProviderException("Role name not found.");
}
}
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
if (!IsUserInRole(username, rolename))
{
throw new ProviderException("User is not in role.");
}
}
}
CsDOMembershipProvider mp = new CsDOMembershipProvider();
mp.SetupParameters(assemblyName, userType);
foreach (string username in usernames)
{
foreach (string rolename in rolenames)
{
DataObject role = NewRole();
_Role_Name.SetValue(role, rolename, null);
role.find();
role.fetch();
DataObject user = mp.NewUser();
mp._User_Name.SetValue(user, username, null);
role.find();
role.fetch();
DataObject usersInRoles = NewUsersInRoles();
_UsersInRoles_Role.SetValue(usersInRoles, role, null);
_UsersInRoles_User.SetValue(usersInRoles, user, null);
IList users = usersInRoles.ToArray(true);
foreach (DataObject item in users)
item.delete();
}
}
}
public override bool RoleExists(string rolename)
{
bool exists = false;
DataObject roles = NewRole();
_Role_Name.SetValue(roles, rolename, null);
IList users = roles.ToArray(true);
if (users.Count > 0)
{
exists = true;
}
return exists;
}
public override string[] FindUsersInRole(string rolename, string usernameToMatch)
{
string tmpUserNames = "";
CsDOMembershipProvider mp = new CsDOMembershipProvider();
mp.SetupParameters(assemblyName, userType);
DataObject role = NewRole();
_Role_Name.SetValue(role, rolename, null);
role.find();
role.fetch();
DataObject user = mp.NewUser();
mp._User_Name.SetValue(user, usernameToMatch, null);
role.find();
role.fetch();
DataObject usersInRoles = NewUsersInRoles();
_UsersInRoles_Role.SetValue(usersInRoles, role, null);
_UsersInRoles_User.SetValue(usersInRoles, user, null);
IList users = usersInRoles.ToArray(true);
foreach(DataObject item in users)
{
tmpUserNames += mp._User_Name.GetValue(item, null).ToString() + ",";
}
if (tmpUserNames.Length > 0)
{
// Remove trailing comma.
tmpUserNames = tmpUserNames.Substring(0, tmpUserNames.Length - 1);
return tmpUserNames.Split(',');
}
return new string[0];
}
#endregion
}
}
| |
//Copyright (C) 2005 Richard J. Northedge
//
// 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 program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//This file is based on the Parse.java source file found in the
//original java implementation of OpenNLP. That source file contains the following header:
//Copyright (C) 2003 Thomas Morton
//
//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 program; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
using System;
using System.Collections.Generic;
using System.Linq;
//using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Text;
using System.Text.RegularExpressions;
using System.Runtime.Serialization;
namespace OpenNLP.Tools.Parser
{
/// <summary>
/// Exception class for problems detected during parsing.
/// </summary>
[Serializable]
public class ParseException : Exception
{
public ParseException(){}
public ParseException(string message) : base(message){}
public ParseException(string message, Exception innerException) : base(message, innerException){}
//protected ParseException(SerializationInfo info, StreamingContext context) : base(info, context){}
}
/// <summary>
/// Class for holding constituents.
/// </summary>
public class Parse : IComparable
{
/// <summary>
/// The sub-constituents of this parse.
/// </summary>
private List<Parse> _parts;
/// <summary>
/// The string buffer used to track the derivation of this parse.
/// </summary>
private StringBuilder _derivation;
// property accessors and methods for manipulating properties -------
/// <summary>
/// The text string on which this parse is based. This object is shared among all parses for the same sentence.
/// </summary>
public virtual string Text{ get; private set; }
/// /// <summary>
/// The character offsets into the text for this constituent.
/// </summary>
public virtual Util.Span Span { get; private set; }
/// <summary>
/// The syntactic type of this parse.
/// </summary>
public virtual string Type { get; set; }
public string Value
{
get { return this.Text.Substring(this.Span.Start, this.Span.Length()); }
}
public bool IsLeaf
{
get { return !this.GetChildren().Any(); }
}
/// <summary>
/// The sub-constituents of this parse.
/// </summary>
public virtual Parse[] GetChildren()
{
return _parts.ToArray();
}
/// <summary>
/// The number of children for this parse node.
/// </summary>
public int ChildCount
{
get
{
return _parts.Count;
}
}
/// <summary>
/// The head parse of this parse. A parse can be its own head.
/// </summary>
public virtual Parse Head { get; private set; }
/// <summary>
/// The outcome assigned to this parse during construction of its parent parse.
/// </summary>
public virtual string Label { get; set; }
/// <summary>
/// The parent parse of this parse.
/// </summary>
public virtual Parse Parent { get; set; }
///<summary>
///Returns the log of the product of the probability associated with all the decisions which formed this constituent.
///</summary>
public virtual double Probability { get; private set; }
public virtual string Derivation
{
get
{
return _derivation.ToString();
}
}
public virtual bool IsPosTag
{
get
{
return (_parts.Count == 1 && (_parts[0]).Type == MaximumEntropyParser.TokenNode);
}
}
///<summary>Returns whether this parse is complete.</summary>
///<returns>Returns true if the parse contains a single top-most node.</returns>
public virtual bool IsComplete
{
get
{
return (_parts.Count == 1);
}
}
// Methods ---------------------
/// <summary>
/// Replaces the child at the specified index with a new child with the specified label.
/// </summary>
/// <param name="index">
/// The index of the child to be replaced.
/// </param>
/// <param name="label">
/// The label to be assigned to the new child.
/// </param>
public void SetChild(int index, string label)
{
var newChild = (Parse)(_parts[index]).Clone();
newChild.Label = label;
_parts[index] = newChild;
}
/// <summary>
/// Returns the index of this specified child.
/// </summary>
/// <param name="child">
/// A child of this parse.
/// </param>
/// <returns>
/// the index of this specified child or -1 if the specified child is not a child of this parse.
/// </returns>
public int IndexOf(Parse child)
{
return _parts.IndexOf(child);
}
///<summary>
///Adds the specified probability log to this current log for this parse.
///</summary>
///<param name="logProbability">
///The probaility of an action performed on this parse.
///</param>
internal void AddProbability(double logProbability)
{
Probability += logProbability;
}
internal void InitializeDerivationBuffer()
{
_derivation = new StringBuilder(100);
}
internal void AppendDerivationBuffer(string derivationData)
{
_derivation.Append(derivationData);
}
// IClonable implementation ---------------------------
public object Clone()
{
var clonedParse = (Parse)base.MemberwiseClone();
clonedParse._parts = new List<Parse>(_parts);
if (_derivation != null)
{
clonedParse.InitializeDerivationBuffer();
clonedParse.AppendDerivationBuffer(_derivation.ToString());
}
return (clonedParse);
}
// IComparable implementation ------------------------
public virtual int CompareTo(object o)
{
if (!(o is Parse))
{
throw new ArgumentException("A Parse object is required for comparison.");
}
var testParse = (Parse) o;
if (this.Probability > testParse.Probability)
{
return - 1;
}
else if (this.Probability < testParse.Probability)
{
return 1;
}
return 0;
}
// constructors -----------------------
public Parse(string parseText, Util.Span span, string type, double probability)
{
Text = parseText;
Span = span;
Type = type;
Probability = probability;
Head = this;
_parts = new List<Parse>();
Label = null;
Parent = null;
}
public Parse(string parseText, Util.Span span, string type, double probability, Parse head) : this(parseText, span, type, probability)
{
Head = head;
}
// System.Object overrides -------------------------
public override string ToString()
{
return Text.Substring(Span.Start, Span.Length());
}
//public override bool Equals (Object o)
//{
// if (o == null) return false;
// if (this.GetType() != o.GetType())
// {
// return false;
// }
// Parse testParse = (Parse)o;
// return (this.Probability == testParse.Probability);
//}
//public override int GetHashCode ()
//{
// return _probability.GetHashCode();
//}
///<summary>
///Returns the probability associated with the pos-tag sequence assigned to this parse.
///</summary>
///<returns>
///The probability associated with the pos-tag sequence assigned to this parse.
///</returns>
public virtual double GetTagSequenceProbability()
{
//System.Console.Error.WriteLine("Parse.GetTagSequenceProbability: " + _type + " " + this);
if (_parts.Count == 1 && (_parts[0]).Type == MaximumEntropyParser.TokenNode)
{
//System.Console.Error.WriteLine(this + " " + mParseProbability);
return Math.Log(Probability);
}
else
{
if (_parts.Count == 0)
{
throw new ParseException("Parse.GetTagSequenceProbability(): Wrong base case!");
//return 0.0;
}
else
{
double sum = 0.0;
foreach (Parse oChildParse in _parts)
{
sum += oChildParse.GetTagSequenceProbability();
}
return sum;
}
}
}
///<summary>
///Inserts the specified constituent into this parse based on its text span. This
///method assumes that the specified constituent can be inserted into this parse.
///</summary>
///<param name="constituent">
///The constituent to be inserted.
///</param>
public virtual void Insert(Parse constituent)
{
Util.Span constituentSpan = constituent.Span;
if (Span.Contains(constituentSpan))
{
int currentPart;
int partCount = _parts.Count;
for (currentPart = 0; currentPart < partCount; currentPart++)
{
Parse subPart = _parts[currentPart];
Util.Span subPartSpan = subPart.Span;
if (subPartSpan.Start > constituentSpan.End)
{
break;
}
// constituent Contains subPart
else if (constituentSpan.Contains(subPartSpan))
{
_parts.RemoveAt(currentPart);
currentPart--;
constituent._parts.Add(subPart);
subPart.Parent = constituent;
partCount = _parts.Count;
}
else if (subPartSpan.Contains(constituentSpan))
{
//System.Console.WriteLine("Parse.insert:subPart contains con");
subPart.Insert(constituent);
return;
}
}
_parts.Insert(currentPart, constituent);
constituent.Parent = this;
}
else
{
throw new ParseException("Inserting constituent not contained in the sentence!");
}
}
///<summary>
///Displays this parse using Penn Treebank-style formatting.
///</summary>
public virtual string Show()
{
var buffer = new StringBuilder();
int start = Span.Start;
if (Type != MaximumEntropyParser.TokenNode)
{
buffer.Append("(");
buffer.Append(Type + " ");
}
foreach (Parse childParse in _parts)
{
Util.Span childSpan = childParse.Span;
if (start < childSpan.Start)
{
//System.Console.Out.WriteLine("pre " + start + " " + childSpan.Start);
buffer.Append(Text.Substring(start, (childSpan.Start) - (start)));
}
buffer.Append(childParse.Show());
start = childSpan.End;
}
buffer.Append(Text.Substring(start, this.Span.End - start));
if (Type != MaximumEntropyParser.TokenNode)
{
buffer.Append(")");
}
return buffer.ToString();
}
/// <summary>
/// Computes the head parses for this parse and its sub-parses and stores this information
/// in the parse data structure.
/// </summary>
/// <param name="rules">
/// The head rules which determine how the head of the parse is computed.
/// </param>
public virtual void UpdateHeads(IHeadRules rules)
{
if (_parts != null && _parts.Count != 0)
{
for (int currentPart = 0, partCount = _parts.Count; currentPart < partCount; currentPart++)
{
Parse currentParse = _parts[currentPart];
currentParse.UpdateHeads(rules);
}
Head = rules.GetHead(_parts.ToArray(), Type) ?? this;
}
else
{
Head = this;
}
}
/// <summary>
/// Returns the parse nodes which are children of this node and which are pos tags.
/// </summary>
/// <returns>
/// the parse nodes which are children of this node and which are pos tags.
/// </returns>
public virtual Parse[] GetTagNodes()
{
var tags = new List<Parse>();
var nodes = new List<Parse>(_parts);
while (nodes.Count != 0)
{
Parse currentParse = nodes[0];
nodes.RemoveAt(0);
if (currentParse.IsPosTag)
{
tags.Add(currentParse);
}
else
{
nodes.InsertRange(0, currentParse.GetChildren());
}
}
return tags.ToArray();
}
/// <summary>
/// Returns the deepest shared parent of this node and the specified node.
/// If the nodes are identical then their parent is returned.
/// If one node is the parent of the other then the parent node is returned.
/// </summary>
/// <param name="node">
/// The node from which parents are compared to this node's parents.
/// </param>
/// <returns>
/// the deepest shared parent of this node and the specified node.
/// </returns>
public virtual Parse GetCommonParent(Parse node)
{
if (this == node)
{
return this.Parent;
}
var parents = new Util.HashSet<Parse>();
Parse parentParse = this;
while (parentParse != null)
{
parents.Add(parentParse);
parentParse = parentParse.Parent;
}
while (node != null)
{
if (parents.Contains(node))
{
return node;
}
node = node.Parent;
}
return null;
}
protected internal void UpdateChildParents()
{
foreach (Parse childParse in _parts)
{
childParse.Parent = this;
childParse.UpdateChildParents();
}
}
// static methods used to create a Parse from a Penn Treebank parse string ----
/// <summary>
/// The pattern used to find the base constituent label of a Penn Treebank labeled constituent.
/// </summary>
private static readonly Regex TypePattern = new Regex("^([^ =-]+)", RegexOptions.Compiled);
/// <summary>
/// The pattern used to identify tokens in Penn Treebank labeled constituents.
/// </summary>
private static readonly Regex TokenPattern = new Regex("^[^ ()]+ ([^ ()]+)\\s*\\)", RegexOptions.Compiled);
private static string GetType(string rest)
{
if (rest.StartsWith("-LCB-"))
{
return "-LCB-";
}
else if (rest.StartsWith("-RCB-"))
{
return "-RCB-";
}
else if (rest.StartsWith("-LRB-"))
{
return "-LRB-";
}
else if (rest.StartsWith("-RRB-"))
{
return "-RRB-";
}
else
{
MatchCollection typeMatches = TypePattern.Matches(rest);
if (typeMatches.Count > 0)
{
return typeMatches[0].Groups[1].Value;
}
}
return null;
}
private static string GetToken(string rest)
{
MatchCollection tokenMatches = TokenPattern.Matches(rest);
if (tokenMatches.Count > 0)
{
return tokenMatches[0].Groups[1].Value;
}
return null;
// int start = rest.IndexOf(" ");
// if (start > -1)
// {
// int end = rest.IndexOfAny(new char[] {'(', ')'}, start);
// if ((end > -1) && (end - start > 1))
// {
// return rest.Substring(start + 1, end - start - 1);
// }
// }
// return null;
}
/// <summary>
/// Generates a Parse structure from the specified tree-bank style parse string.
/// </summary>
/// <param name="parse">
/// A tree-bank style parse string.
/// </param>
/// <returns>
/// a Parse structure for the specified tree-bank style parse string.
/// </returns>
public static Parse FromParseString(string parse)
{
var textBuffer = new StringBuilder();
int offset = 0;
var parseStack = new Stack<Tuple<string, int>>();
var consitutents = new List<Tuple<string, Util.Span>>();
for (int currentChar = 0, charCount = parse.Length; currentChar < charCount; currentChar++)
{
char c = parse[currentChar];
if (c == '(')
{
string rest = parse.Substring(currentChar + 1);
string type = GetType(rest);
if (type == null)
{
throw new ParseException("null type for: " + rest);
}
string token = GetToken(rest);
parseStack.Push(new Tuple<string, int>(type, offset));
if ((object) token != null && type != "-NONE-")
{
consitutents.Add(new Tuple<string, Util.Span>(MaximumEntropyParser.TokenNode, new Util.Span(offset, offset + token.Length)));
textBuffer.Append(token).Append(" ");
offset += token.Length + 1;
}
}
else if (c == ')')
{
Tuple<string, int> parts = parseStack.Pop();
string type = parts.Item1;
if (type != "-NONE-")
{
int start = parts.Item2;
consitutents.Add(new Tuple<string, Util.Span>(parts.Item1, new Util.Span(start, offset - 1)));
}
}
}
string text = textBuffer.ToString();
var rootParse = new Parse(text, new Util.Span(0, text.Length), MaximumEntropyParser.TopNode, 1);
for (int currentConstituent = 0, constituentCount = consitutents.Count; currentConstituent < constituentCount; currentConstituent++)
{
Tuple<string, Util.Span> parts = consitutents[currentConstituent];
string type = parts.Item1;
if (type != MaximumEntropyParser.TopNode)
{
var newConstituent = new Parse(text, parts.Item2, type, 1);
rootParse.Insert(newConstituent);
}
}
return rootParse;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using Microsoft.Xunit.Performance;
using System;
using System.Diagnostics;
using Xunit;
[assembly: OptimizeForBenchmarks]
[assembly: MeasureInstructionsRetired]
namespace ConsoleMandel
{
public static class Program
{
private const int Pass = 100;
private const int Fail = -1;
private static bool s_silent = false;
private static void DoNothing(int x, int y, int count) { }
private static void DrawDot(int x, int y, int count)
{
if (x == 0)
Console.WriteLine();
Console.Write((count < 1000) ? ' ' : '*');
}
private static Algorithms.FractalRenderer.Render GetRenderer(Action<int, int, int> draw, int which)
{
return Algorithms.FractalRenderer.SelectRender(draw, Abort, IsVector(which), IsDouble(which), IsMulti(which), UsesADT(which), !UseIntTypes(which));
}
private static bool Abort() { return false; }
private static bool UseIntTypes(int num) { return (num & 8) == 0; }
private static bool IsVector(int num) { return num > 7; }
private static bool IsDouble(int num) { return (num & 4) != 0; }
private static bool IsMulti(int num) { return (num & 2) != 0; }
private static bool UsesADT(int num) { return (num & 1) != 0; }
private static void PrintDescription(int i)
{
Console.WriteLine("{0}: {1} {2}-Precision {3}Threaded using {4} and {5} int types", i,
IsVector(i) ? "Vector" : "Scalar",
IsDouble(i) ? "Double" : "Single",
IsMulti(i) ? "Multi" : "Single",
UsesADT(i) ? "ADT" : "Raw Values",
UseIntTypes(i) ? "using" : "not using any");
}
private static void PrintUsage()
{
Console.WriteLine("Usage:\n ConsoleMandel [0-23] -[bench #] where # is the number of iterations.");
for (int i = 0; i < 24; i++)
{
PrintDescription(i);
}
Console.WriteLine("The numeric argument selects the implementation number;");
Console.WriteLine("If not specified, all are run.");
Console.WriteLine("In non-benchmark mode, dump a text view of the Mandelbrot set.");
Console.WriteLine("In benchmark mode, a larger set is computed but nothing is dumped.");
}
private static int Main(string[] args)
{
try
{
int which = -1;
bool verbose = false;
bool bench = false;
int iters = 1;
int argNum = 0;
while (argNum < args.Length)
{
if (args[argNum].ToUpperInvariant() == "-BENCH")
{
bench = true;
if ((args.Length <= (argNum + 1)) || !Int32.TryParse(args[argNum + 1], out iters))
{
iters = 5;
}
argNum++;
}
else if (args[argNum].ToUpperInvariant() == "-V")
{
verbose = true;
}
else if (args[argNum].ToUpperInvariant() == "-S")
{
s_silent = true;
}
else if (!Int32.TryParse(args[argNum], out which))
{
PrintUsage();
return Fail;
}
argNum++;
}
if (bench)
{
Bench(iters, which);
return Pass;
}
if (which == -1)
{
PrintUsage();
return Pass;
}
if (verbose)
{
PrintDescription(which);
}
if (IsVector(which))
{
if (verbose)
{
Console.WriteLine(" Vector Count is {0}", IsDouble(which) ? System.Numerics.Vector<Double>.Count : System.Numerics.Vector<Single>.Count);
Console.WriteLine(" {0} Accelerated.", System.Numerics.Vector.IsHardwareAccelerated ? "IS" : "IS NOT");
}
}
var render = GetRenderer(DrawDot, which);
render(-1.5f, .5f, -1f, 1f, 2.0f / 60.0f);
return Pass;
}
catch (System.Exception)
{
return Fail;
}
}
public static void Bench(int iters, int which)
{
float XC = -1.248f;
float YC = -.0362f;
float Range = .001f;
float xmin = XC - Range;
float xmax = XC + Range;
float ymin = YC - Range;
float ymax = YC + Range;
float step = Range / 1000f; // This will render one million pixels
float warm = Range / 100f; // To warm up, just render 10000 pixels :-)
Algorithms.FractalRenderer.Render[] renderers = new Algorithms.FractalRenderer.Render[24];
// Warm up each renderer
if (!s_silent)
{
Console.WriteLine("Warming up...");
}
Stopwatch timer = new Stopwatch();
int firstRenderer = (which == -1) ? 0 : which;
int lastRenderer = (which == -1) ? (renderers.Length - 1) : which;
for (int i = firstRenderer; i <= lastRenderer; i++)
{
renderers[i] = GetRenderer(DoNothing, i);
timer.Restart();
renderers[i](xmin, xmax, ymin, ymax, warm);
timer.Stop();
if (!s_silent)
{
Console.WriteLine("{0}{1}{2}{3}{4} Complete [{5} ms]",
UseIntTypes(i) ? "IntBV " : "Strict ",
IsVector(i) ? "Vector " : "Scalar ",
IsDouble(i) ? "Double " : "Single ",
UsesADT(i) ? "ADT " : "Raw ",
IsMulti(i) ? "Multi " : "Single ",
timer.ElapsedMilliseconds);
}
}
if (!s_silent)
{
Console.WriteLine(" Run Type : Min Max Average Std-Dev");
}
for (int i = firstRenderer; i <= lastRenderer; i++)
{
long totalTime = 0;
long min = long.MaxValue;
long max = long.MinValue;
for (int count = 0; count < iters; count++)
{
timer.Restart();
renderers[i](xmin, xmax, ymin, ymax, step);
timer.Stop();
long time = timer.ElapsedMilliseconds;
max = Math.Max(time, max);
min = Math.Min(time, min);
totalTime += time;
}
double avg = totalTime / (double)iters;
double stdDev = Math.Sqrt(totalTime / (iters - 1.0)) / avg;
if (s_silent)
{
Console.WriteLine("Average: {0,0:0.0}", avg);
}
else
{
Console.WriteLine("{0}{1}{2}{3}{4}: {5,8} {6,8} {7,10:0.0} {8,10:P}",
UseIntTypes(i) ? "IntBV " : "Strict ",
IsVector(i) ? "Vector " : "Scalar ",
IsDouble(i) ? "Double " : "Single ",
UsesADT(i) ? "ADT " : "Raw ",
IsMulti(i) ? "Multi " : "Single ",
min, max, avg, stdDev);
}
}
}
public static void XBench(int iters, int which)
{
float XC = -1.248f;
float YC = -.0362f;
float Range = .001f;
float xmin = XC - Range;
float xmax = XC + Range;
float ymin = YC - Range;
float ymax = YC + Range;
float step = Range / 100f;
Algorithms.FractalRenderer.Render renderer = GetRenderer(DoNothing, which);
for (int count = 0; count < iters; count++)
{
renderer(xmin, xmax, ymin, ymax, step);
}
}
[Benchmark]
public static void VectorFloatSinglethreadRawNoInt()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
XBench(10, 8);
}
}
}
[Benchmark]
public static void VectorFloatSinglethreadADTNoInt()
{
foreach (var iteration in Benchmark.Iterations)
{
using (iteration.StartMeasurement())
{
XBench(10, 9);
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using xgc3.Core;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
namespace xgc3.GameObjects
{
public class View : GameObject
{
public int X;
public int Y;
public bool MouseIsIn = false;
public bool AcceptsFocus = false;
public int Width = 50;
public int Height = 50;
public event EventDelegate KeyPress;
public event EventDelegate LeftMouseDown;
public event EventDelegate LeftMouseUp;
public event EventDelegate RightMouseDown;
public event EventDelegate RightMouseUp;
public event EventDelegate MouseOver;
public event EventDelegate MouseIn;
public event EventDelegate MouseOut;
public event EventDelegate Draw;
public event EventDelegate GotFocus;
public event EventDelegate LostFocus;
public void Raise_LeftMouseDown(Instance self, Instance other, string extra)
{
if (LeftMouseDown != null) { LeftMouseDown(self, other, extra); }
}
public void Raise_LeftMouseUp(Instance self, Instance other, string extra)
{
if (LeftMouseUp != null) { LeftMouseUp(self, other, extra); }
}
public void Raise_RightMouseDown(Instance self, Instance other, string extra)
{
if (RightMouseDown != null) { RightMouseDown(self, other, extra); }
}
public void Raise_RightMouseUp(Instance self, Instance other, string extra)
{
if (RightMouseUp != null) { RightMouseUp(self, other, extra); }
}
public void Raise_Draw(Instance self, Instance other, string extra)
{
if (Draw != null) { Draw(self, other, extra); }
}
public void Raise_MouseOver(Instance self, Instance other, string extra)
{
if (MouseOver != null) { MouseOver(self, other, extra); }
}
public void Raise_MouseIn(Instance self, Instance other, string extra)
{
if (MouseIn != null) { MouseIn(self, other, extra); }
}
public void Raise_MouseOut(Instance self, Instance other, string extra)
{
if (MouseOut != null) { MouseOut(self, other, extra); }
}
public void Raise_GotFocus(Instance self, Instance other, string extra)
{
if (GotFocus != null) { GotFocus(self, other, extra); }
}
public void Raise_LostFocus(Instance self, Instance other, string extra)
{
if (LostFocus != null) { LostFocus(self, other, extra); }
}
public bool HitTest(int x, int y)
{
return ((x > X) && (x < X + Width) && (y > Y) && (y < Y + Height));
// TODO: Fasater?
//Microsoft.Xna.Framework.Rectangle rc = new Microsoft.Xna.Framework.Rectangle((int)Location.X, (int)Location.Y, (int)W, (int)H);
//if (rc.Contains(new Point((int)pos.X, (int)pos.Y)))
//{
// return true;
//}
//return false;
#if TEST
// Top-Left
Microsoft.Xna.Framework.Graphics.Texture2D Texture;
Microsoft.Xna.Framework.Rectangle rcSrc = new Microsoft.Xna.Framework.Rectangle( 0,0,3,3);
Microsoft.Xna.Framework.Rectangle rcDst = new Microsoft.Xna.Framework.Rectangle( 0,0,3,3);;
this.GameMgr.Game.GameComponent.SpriteB.Draw(self.Texture, rcDst, rcSrc, Color.White);
Microsoft.Xna.Framework.Rectangle rcSrc = new Microsoft.Xna.Framework.Rectangle( 3, 0, 1, 3);
Microsoft.Xna.Framework.Rectangle rcDst = new Microsoft.Xna.Framework.Rectangle(3, 0, this.Width - 6, 3);
this.GameMgr.Game.GameComponent.SpriteB.Draw(self.Texture, rcDst, rcSrc, Color.White);
Microsoft.Xna.Framework.Rectangle rcSrc = new Microsoft.Xna.Framework.Rectangle( Texture.Width-3, 0, 3, 3);
Microsoft.Xna.Framework.Rectangle rcDst = new Microsoft.Xna.Framework.Rectangle( this.Width-3, 0, 3, 3);
this.GameMgr.Game.GameComponent.SpriteB.Draw(self.Texture, rcDst, rcSrc, Color.White);
#endif
//this.GameMgr.Game.GameComponent.SpriteB.Draw((self.Texture, rcDst, rcSrc, Color.White);
//Microsoft.Xna.Framework.Graphics.Texture2D t = new Microsoft.Xna.Framework.Graphics.Texture2D();
}
/// <summary>
/// Splits a texture into 3x3 grid (assuming top,left is tileSize x tileSize). Same for bottom,right.
///
/// Then scales the texture onto a sprite batch.
///
/// Good for scaling things like buttons.
/// </summary>
/// <param name="sb"></param>
/// <param name="texture"></param>
/// <param name="p"></param>
/// <param name="color"></param>
/// <param name="tileSize"></param>
public void DrawTiledTexture(SpriteBatch sb, Texture2D texture, int x, int y, int w, int h, Color color, int tileSize)
{
Microsoft.Xna.Framework.Rectangle rcSrc = new Microsoft.Xna.Framework.Rectangle(0, 0, tileSize, tileSize);
Microsoft.Xna.Framework.Rectangle rcDst = new Microsoft.Xna.Framework.Rectangle(x, y, tileSize, tileSize); ;
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
rcSrc = new Microsoft.Xna.Framework.Rectangle(tileSize, 0, texture.Width - (tileSize + tileSize), tileSize);
rcDst = new Microsoft.Xna.Framework.Rectangle(x + tileSize, y, this.Width - (tileSize + tileSize), tileSize);
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
rcSrc = new Microsoft.Xna.Framework.Rectangle(texture.Width - tileSize, 0, tileSize, tileSize);
rcDst = new Microsoft.Xna.Framework.Rectangle(x + this.Width - tileSize, y, tileSize, tileSize);
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
// Middle row
rcSrc = new Microsoft.Xna.Framework.Rectangle(0, tileSize, tileSize, texture.Height - (tileSize + tileSize));
rcDst = new Microsoft.Xna.Framework.Rectangle(x, y + tileSize, tileSize, h - (tileSize + tileSize)); ;
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
rcSrc = new Microsoft.Xna.Framework.Rectangle(tileSize, tileSize, texture.Width - (tileSize + tileSize), texture.Height - (tileSize + tileSize));
rcDst = new Microsoft.Xna.Framework.Rectangle(x + tileSize, y + tileSize, this.Width - (tileSize + tileSize), h - (tileSize + tileSize));
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
rcSrc = new Microsoft.Xna.Framework.Rectangle(texture.Width - tileSize, tileSize, tileSize, texture.Height - (tileSize + tileSize));
rcDst = new Microsoft.Xna.Framework.Rectangle(x + this.Width - tileSize, y + tileSize, tileSize, h - (tileSize + tileSize));
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
// Last row
rcSrc = new Microsoft.Xna.Framework.Rectangle(0, texture.Height - tileSize, tileSize, tileSize);
rcDst = new Microsoft.Xna.Framework.Rectangle(x, y + this.Height - tileSize, tileSize, tileSize); ;
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
rcSrc = new Microsoft.Xna.Framework.Rectangle(tileSize, texture.Height - tileSize, 1, tileSize);
rcDst = new Microsoft.Xna.Framework.Rectangle(x + tileSize, y + this.Height - tileSize, this.Width - 6, tileSize);
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
rcSrc = new Microsoft.Xna.Framework.Rectangle(texture.Width - tileSize, texture.Height - tileSize, tileSize, tileSize);
rcDst = new Microsoft.Xna.Framework.Rectangle(x + this.Width - tileSize, y + this.Height - tileSize, tileSize, tileSize);
this.GameMgr.Game.GameComponent.SpriteB.Draw(texture, rcDst, rcSrc, Color.White);
//this.GameMgr.Game.GameComponent.SpriteB.DrawString(self.GameMgr.Game.FontMgr.Courier, self.Text, p, Color.Black, 0, prop, 1, SpriteEffects.
}
public enum TextAlignment
{
Top,
Left,
Middle,
Right,
Bottom,
TopLeft,
TopRight,
BottomLeft,
BottomRight
}
/// <summary>
/// Draws a string.
/// </summary>
/// <param name="sb">A reference to a SpriteBatch object that will draw the text.</param>
/// <param name="fnt">A reference to a SpriteFont object.</param>
/// <param name="text">The text to be drawn. <remarks>If the text contains \n it
/// will be treated as a new line marker and the text will drawn acordingy.</remarks></param>
/// <param name="r">The screen rectangle that the rext should be drawn inside of.</param>
/// <param name="col">The color of the text that will be drawn.</param>
/// <param name="align">Specified the alignment within the specified screen rectangle.</param>
/// <param name="performWordWrap">If true the words within the text will be aranged to rey and
/// fit within the bounds of the specified screen rectangle.</param>
/// <param name="offsett">Draws the text at a specified offset relative to the screen
/// rectangles top left position. </param>
/// <param name="textBounds">Returns a rectangle representing the size of the bouds of
/// the text that was drawn.</param>
public static void DrawString(SpriteBatch sb, SpriteFont fnt, string text, Rectangle r,
Color col, TextAlignment align, bool performWordWrap, Vector2 offsett, out Rectangle textBounds)
{
// check if there is text to draw
textBounds = r;
if (text == null) return;
if (text == string.Empty) return;
List<string> lines = new List<string>();
lines.AddRange(text.Split(new string[] { "\\n" }, StringSplitOptions.RemoveEmptyEntries));
// calc the size of the rect for all the text
Rectangle tmprect = ProcessLines(fnt, r, performWordWrap, lines);
// setup the position where drawing will start
Vector2 pos = new Vector2(r.X, r.Y);
int aStyle = 0;
switch (align)
{
case TextAlignment.Bottom:
pos.Y = r.Bottom - tmprect.Height;
aStyle = 1;
break;
case TextAlignment.BottomLeft:
pos.Y = r.Bottom - tmprect.Height;
aStyle = 0;
break;
case TextAlignment.BottomRight:
pos.Y = r.Bottom - tmprect.Height;
aStyle = 2;
break;
case TextAlignment.Left:
pos.Y = r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 0;
break;
case TextAlignment.Middle:
pos.Y = r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 1;
break;
case TextAlignment.Right:
pos.Y = r.Y + ((r.Height / 2) - (tmprect.Height / 2));
aStyle = 2;
break;
case TextAlignment.Top:
aStyle = 1;
break;
case TextAlignment.TopLeft:
aStyle = 0;
break;
case TextAlignment.TopRight:
aStyle = 2;
break;
}
// draw text
for (int idx = 0; idx < lines.Count; idx++)
{
string txt = lines[idx];
Vector2 size = fnt.MeasureString(txt);
switch (aStyle)
{
case 0:
pos.X = r.X;
break;
case 1:
pos.X = r.X + ((r.Width / 2) - (size.X / 2));
break;
case 2:
pos.X = r.Right - size.X;
break;
}
// draw the line of text
sb.DrawString(fnt, txt, pos + offsett, col);
pos.Y += fnt.LineSpacing;
}
textBounds = tmprect;
}
internal static Rectangle ProcessLines(SpriteFont fnt, Rectangle r, bool performWordWrap, List<string> lines)
{
// llop through each line in the collection
Rectangle bounds = r;
bounds.Width = 0;
bounds.Height = 0;
int index = 0;
float Width = 0;
bool lineInserted = false;
while (index < lines.Count)
{
// get a line of text
string linetext = lines[index];
//measure the line of text
Vector2 size = fnt.MeasureString(linetext);
// check if the line of text is geater then then the rect we want to draw it inside of
if (performWordWrap && size.X > r.Width)
{
// find last space character in line
string endspace = string.Empty;
// deal with trailing spaces
if (linetext.EndsWith(" "))
{
endspace = " ";
linetext = linetext.TrimEnd();
}
// get the index of the last space character
int i = linetext.LastIndexOf(" ");
if (i != -1)
{
// if there was a space grab the last word in the line
string lastword = linetext.Substring(i + 1);
// move word to next line
if (index == lines.Count - 1)
{
lines.Add(lastword);
lineInserted = true;
}
else
{
// prepend last word to begining of next line
if (lineInserted)
{
lines[index + 1] = lastword + endspace + lines[index + 1];
}
else
{
lines.Insert(index + 1, lastword);
lineInserted = true;
}
}
// crop last word from the line that is being processed
lines[index] = linetext.Substring(0, i + 1);
}
else
{
// there appear to be no space characters on this line s move to the next line
lineInserted = false;
size = fnt.MeasureString(lines[index]);
if (size.X > bounds.Width) Width = size.X;
bounds.Height += fnt.LineSpacing;// size.Y - 1;
index++;
}
}
else
{
// this line will fit so we can skip to the next line
lineInserted = false;
size = fnt.MeasureString(lines[index]);
if (size.X > bounds.Width) bounds.Width = (int)size.X;
bounds.Height += fnt.LineSpacing;//size.Y - 1;
index++;
}
}
// returns the size of the text
return bounds;
}
}
}
| |
using System.Linq;
using Avalonia.Data.Core;
using Avalonia.Markup.Parsers;
using Xunit;
namespace Avalonia.Markup.UnitTests.Parsers
{
public class SelectorGrammarTests
{
[Fact]
public void OfType()
{
var result = SelectorGrammar.Parse("Button");
Assert.Equal(
new[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button", Xmlns = "" } },
result);
}
[Fact]
public void NamespacedOfType()
{
var result = SelectorGrammar.Parse("x|Button");
Assert.Equal(
new[] { new SelectorGrammar.OfTypeSyntax { TypeName = "Button", Xmlns = "x" } },
result);
}
[Fact]
public void Name()
{
var result = SelectorGrammar.Parse("#foo");
Assert.Equal(
new[] { new SelectorGrammar.NameSyntax { Name = "foo" }, },
result);
}
[Fact]
public void OfType_Name()
{
var result = SelectorGrammar.Parse("Button#foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NameSyntax { Name = "foo" },
},
result);
}
[Fact]
public void Is()
{
var result = SelectorGrammar.Parse(":is(Button)");
Assert.Equal(
new[] { new SelectorGrammar.IsSyntax { TypeName = "Button", Xmlns = "" } },
result);
}
[Fact]
public void Is_Name()
{
var result = SelectorGrammar.Parse(":is(Button)#foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.IsSyntax { TypeName = "Button" },
new SelectorGrammar.NameSyntax { Name = "foo" },
},
result);
}
[Fact]
public void NamespacedIs_Name()
{
var result = SelectorGrammar.Parse(":is(x|Button)#foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.IsSyntax { TypeName = "Button", Xmlns = "x" },
new SelectorGrammar.NameSyntax { Name = "foo" },
},
result);
}
[Fact]
public void Class()
{
var result = SelectorGrammar.Parse(".foo");
Assert.Equal(
new[] { new SelectorGrammar.ClassSyntax { Class = "foo" } },
result);
}
[Fact]
public void Pseudoclass()
{
var result = SelectorGrammar.Parse(":foo");
Assert.Equal(
new[] { new SelectorGrammar.ClassSyntax { Class = ":foo" } },
result);
}
[Fact]
public void OfType_Class()
{
var result = SelectorGrammar.Parse("Button.foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Child_Class()
{
var result = SelectorGrammar.Parse("Button > .foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.ChildSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Child_Class_No_Spaces()
{
var result = SelectorGrammar.Parse("Button>.foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.ChildSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Descendant_Class()
{
var result = SelectorGrammar.Parse("Button .foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.DescendantSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Template_Class()
{
var result = SelectorGrammar.Parse("Button /template/ .foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.TemplateSyntax { },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void OfType_Property()
{
var result = SelectorGrammar.Parse("Button[Foo=bar]");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.PropertySyntax { Property = "Foo", Value = "bar" },
},
result);
}
[Fact]
public void Not_OfType()
{
var result = SelectorGrammar.Parse(":not(Button)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.NotSyntax
{
Argument = new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
},
}
},
result);
}
[Fact]
public void OfType_Not_Class()
{
var result = SelectorGrammar.Parse("Button:not(.foo)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NotSyntax
{
Argument = new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
}
},
result);
}
[Theory]
[InlineData(":nth-child(xn+2)")]
[InlineData(":nth-child(2n+b)")]
[InlineData(":nth-child(2n+)")]
[InlineData(":nth-child(2na)")]
[InlineData(":nth-child(2x+1)")]
public void NthChild_Invalid_Inputs(string input)
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(input));
}
[Theory]
[InlineData(":nth-child(+1)", 0, 1)]
[InlineData(":nth-child(1)", 0, 1)]
[InlineData(":nth-child(-1)", 0, -1)]
[InlineData(":nth-child(2n+1)", 2, 1)]
[InlineData(":nth-child(n)", 1, 0)]
[InlineData(":nth-child(+n)", 1, 0)]
[InlineData(":nth-child(-n)", -1, 0)]
[InlineData(":nth-child(-2n)", -2, 0)]
[InlineData(":nth-child(n+5)", 1, 5)]
[InlineData(":nth-child(n-5)", 1, -5)]
[InlineData(":nth-child( 2n + 1 )", 2, 1)]
[InlineData(":nth-child( 2n - 1 )", 2, -1)]
public void NthChild_Variations(string input, int step, int offset)
{
var result = SelectorGrammar.Parse(input);
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.NthChildSyntax()
{
Step = step,
Offset = offset
}
},
result);
}
[Theory]
[InlineData(":nth-last-child(+1)", 0, 1)]
[InlineData(":nth-last-child(1)", 0, 1)]
[InlineData(":nth-last-child(-1)", 0, -1)]
[InlineData(":nth-last-child(2n+1)", 2, 1)]
[InlineData(":nth-last-child(n)", 1, 0)]
[InlineData(":nth-last-child(+n)", 1, 0)]
[InlineData(":nth-last-child(-n)", -1, 0)]
[InlineData(":nth-last-child(-2n)", -2, 0)]
[InlineData(":nth-last-child(n+5)", 1, 5)]
[InlineData(":nth-last-child(n-5)", 1, -5)]
[InlineData(":nth-last-child( 2n + 1 )", 2, 1)]
[InlineData(":nth-last-child( 2n - 1 )", 2, -1)]
public void NthLastChild_Variations(string input, int step, int offset)
{
var result = SelectorGrammar.Parse(input);
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.NthLastChildSyntax()
{
Step = step,
Offset = offset
}
},
result);
}
[Fact]
public void OfType_NthChild()
{
var result = SelectorGrammar.Parse("Button:nth-child(2n+1)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Without_Offset()
{
var result = SelectorGrammar.Parse("Button:nth-child(2147483647n)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = int.MaxValue,
Offset = 0
}
},
result);
}
[Fact]
public void OfType_NthLastChild()
{
var result = SelectorGrammar.Parse("Button:nth-last-child(2n+1)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthLastChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Odd()
{
var result = SelectorGrammar.Parse("Button:nth-child(odd)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 1
}
},
result);
}
[Fact]
public void OfType_NthChild_Even()
{
var result = SelectorGrammar.Parse("Button:nth-child(even)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.NthChildSyntax()
{
Step = 2,
Offset = 0
}
},
result);
}
[Fact]
public void Is_Descendent_Not_OfType_Class()
{
var result = SelectorGrammar.Parse(":is(Control) :not(Button.foo)");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.IsSyntax { TypeName = "Control" },
new SelectorGrammar.DescendantSyntax { },
new SelectorGrammar.NotSyntax
{
Argument = new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "Button" },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
}
},
result);
}
[Fact]
public void OfType_Comma_Is_Class()
{
var result = SelectorGrammar.Parse("TextBlock, :is(Button).foo");
Assert.Equal(
new SelectorGrammar.ISyntax[]
{
new SelectorGrammar.OfTypeSyntax { TypeName = "TextBlock" },
new SelectorGrammar.CommaSyntax(),
new SelectorGrammar.IsSyntax { TypeName = "Button" },
new SelectorGrammar.ClassSyntax { Class = "foo" },
},
result);
}
[Fact]
public void Namespace_Alone_Fails()
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse("ns|"));
}
[Fact]
public void Dot_Alone_Fails()
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(". dot"));
}
[Fact]
public void Invalid_Identifier_Fails()
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse("%foo"));
}
[Fact]
public void Invalid_Class_Fails()
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(".%foo"));
}
[Fact]
public void Not_Without_Argument_Fails()
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(":not()"));
}
[Fact]
public void Not_Without_Closing_Parenthesis_Fails()
{
Assert.Throws<ExpressionParseException>(() => SelectorGrammar.Parse(":not(Button"));
}
}
}
| |
// 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.Buffers;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Security;
using ZErrorCode = System.IO.Compression.ZLibNative.ErrorCode;
using ZFlushCode = System.IO.Compression.ZLibNative.FlushCode;
namespace System.IO.Compression
{
/// <summary>
/// Provides a wrapper around the ZLib compression API.
/// </summary>
internal sealed class Deflater : IDisposable
{
private ZLibNative.ZLibStreamHandle _zlibStream;
private MemoryHandle _inputBufferHandle;
private bool _isDisposed;
private const int minWindowBits = -15; // WindowBits must be between -8..-15 to write no header, 8..15 for a
private const int maxWindowBits = 31; // zlib header, or 24..31 for a GZip header
// Note, DeflateStream or the deflater do not try to be thread safe.
// The lock is just used to make writing to unmanaged structures atomic to make sure
// that they do not get inconsistent fields that may lead to an unmanaged memory violation.
// To prevent *managed* buffer corruption or other weird behaviour users need to synchronise
// on the stream explicitly.
private object SyncLock => this;
internal Deflater(CompressionLevel compressionLevel, int windowBits)
{
Debug.Assert(windowBits >= minWindowBits && windowBits <= maxWindowBits);
ZLibNative.CompressionLevel zlibCompressionLevel;
int memLevel;
switch (compressionLevel)
{
// See the note in ZLibNative.CompressionLevel for the recommended combinations.
case CompressionLevel.Optimal:
zlibCompressionLevel = ZLibNative.CompressionLevel.DefaultCompression;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.Fastest:
zlibCompressionLevel = ZLibNative.CompressionLevel.BestSpeed;
memLevel = ZLibNative.Deflate_DefaultMemLevel;
break;
case CompressionLevel.NoCompression:
zlibCompressionLevel = ZLibNative.CompressionLevel.NoCompression;
memLevel = ZLibNative.Deflate_NoCompressionMemLevel;
break;
default:
throw new ArgumentOutOfRangeException(nameof(compressionLevel));
}
ZLibNative.CompressionStrategy strategy = ZLibNative.CompressionStrategy.DefaultStrategy;
DeflateInit(zlibCompressionLevel, windowBits, memLevel, strategy);
}
~Deflater()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
[SecuritySafeCritical]
private void Dispose(bool disposing)
{
if (!_isDisposed)
{
if (disposing)
_zlibStream.Dispose();
DeallocateInputBufferHandle();
_isDisposed = true;
}
}
public bool NeedsInput() => 0 == _zlibStream.AvailIn;
internal unsafe void SetInput(ReadOnlyMemory<byte> inputBuffer)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.HasPointer);
if (0 == inputBuffer.Length)
{
return;
}
lock (SyncLock)
{
_inputBufferHandle = inputBuffer.Retain(pin: true);
_zlibStream.NextIn = (IntPtr)_inputBufferHandle.Pointer;
_zlibStream.AvailIn = (uint)inputBuffer.Length;
}
}
internal unsafe void SetInput(byte* inputBufferPtr, int count)
{
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(inputBufferPtr != null);
Debug.Assert(!_inputBufferHandle.HasPointer);
if (count == 0)
{
return;
}
lock (SyncLock)
{
_zlibStream.NextIn = (IntPtr)inputBufferPtr;
_zlibStream.AvailIn = (uint)count;
}
}
internal int GetDeflateOutput(byte[] outputBuffer)
{
Contract.Ensures(Contract.Result<int>() >= 0 && Contract.Result<int>() <= outputBuffer.Length);
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(!NeedsInput(), "GetDeflateOutput should only be called after providing input");
try
{
int bytesRead;
ReadDeflateOutput(outputBuffer, ZFlushCode.NoFlush, out bytesRead);
return bytesRead;
}
finally
{
// Before returning, make sure to release input buffer if necessary:
if (0 == _zlibStream.AvailIn)
{
DeallocateInputBufferHandle();
}
}
}
private unsafe ZErrorCode ReadDeflateOutput(byte[] outputBuffer, ZFlushCode flushCode, out int bytesRead)
{
Debug.Assert(outputBuffer?.Length > 0);
lock (SyncLock)
{
fixed (byte* bufPtr = &outputBuffer[0])
{
_zlibStream.NextOut = (IntPtr)bufPtr;
_zlibStream.AvailOut = (uint)outputBuffer.Length;
ZErrorCode errC = Deflate(flushCode);
bytesRead = outputBuffer.Length - (int)_zlibStream.AvailOut;
return errC;
}
}
}
internal bool Finish(byte[] outputBuffer, out int bytesRead)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.HasPointer);
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
ZErrorCode errC = ReadDeflateOutput(outputBuffer, ZFlushCode.Finish, out bytesRead);
return errC == ZErrorCode.StreamEnd;
}
/// <summary>
/// Returns true if there was something to flush. Otherwise False.
/// </summary>
internal bool Flush(byte[] outputBuffer, out int bytesRead)
{
Debug.Assert(null != outputBuffer, "Can't pass in a null output buffer!");
Debug.Assert(outputBuffer.Length > 0, "Can't pass in an empty output buffer!");
Debug.Assert(NeedsInput(), "We have something left in previous input!");
Debug.Assert(!_inputBufferHandle.HasPointer);
// Note: we require that NeedsInput() == true, i.e. that 0 == _zlibStream.AvailIn.
// If there is still input left we should never be getting here; instead we
// should be calling GetDeflateOutput.
return ReadDeflateOutput(outputBuffer, ZFlushCode.SyncFlush, out bytesRead) == ZErrorCode.Ok;
}
private void DeallocateInputBufferHandle()
{
lock (SyncLock)
{
_zlibStream.AvailIn = 0;
_zlibStream.NextIn = ZLibNative.ZNullPtr;
_inputBufferHandle.Dispose();
}
}
[SecuritySafeCritical]
private void DeflateInit(ZLibNative.CompressionLevel compressionLevel, int windowBits, int memLevel,
ZLibNative.CompressionStrategy strategy)
{
ZErrorCode errC;
try
{
errC = ZLibNative.CreateZLibStreamForDeflate(out _zlibStream, compressionLevel,
windowBits, memLevel, strategy);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
return;
case ZErrorCode.MemError:
throw new ZLibException(SR.ZLibErrorNotEnoughMemory, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.VersionError:
throw new ZLibException(SR.ZLibErrorVersionMismatch, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorIncorrectInitParameters, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflateInit2_", (int)errC, _zlibStream.GetErrorMessage());
}
}
[SecuritySafeCritical]
private ZErrorCode Deflate(ZFlushCode flushCode)
{
ZErrorCode errC;
try
{
errC = _zlibStream.Deflate(flushCode);
}
catch (Exception cause)
{
throw new ZLibException(SR.ZLibErrorDLLLoadError, cause);
}
switch (errC)
{
case ZErrorCode.Ok:
case ZErrorCode.StreamEnd:
return errC;
case ZErrorCode.BufError:
return errC; // This is a recoverable error
case ZErrorCode.StreamError:
throw new ZLibException(SR.ZLibErrorInconsistentStream, "deflate", (int)errC, _zlibStream.GetErrorMessage());
default:
throw new ZLibException(SR.ZLibErrorUnexpected, "deflate", (int)errC, _zlibStream.GetErrorMessage());
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DevTestLabs
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// The DevTest Labs Client.
/// </summary>
public partial class DevTestLabsClient : ServiceClient<DevTestLabsClient>, IDevTestLabsClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Gets Azure subscription credentials.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Client API version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// The name of the resource group.
/// </summary>
public string ResourceGroupName { get; set; }
/// <summary>
/// The subscription ID.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the ILabsOperations.
/// </summary>
public virtual ILabsOperations Labs { get; private set; }
/// <summary>
/// Gets the IGlobalSchedulesOperations.
/// </summary>
public virtual IGlobalSchedulesOperations GlobalSchedules { get; private set; }
/// <summary>
/// Gets the IArtifactSourcesOperations.
/// </summary>
public virtual IArtifactSourcesOperations ArtifactSources { get; private set; }
/// <summary>
/// Gets the IArmTemplatesOperations.
/// </summary>
public virtual IArmTemplatesOperations ArmTemplates { get; private set; }
/// <summary>
/// Gets the IArtifactsOperations.
/// </summary>
public virtual IArtifactsOperations Artifacts { get; private set; }
/// <summary>
/// Gets the ICostsOperations.
/// </summary>
public virtual ICostsOperations Costs { get; private set; }
/// <summary>
/// Gets the ICustomImagesOperations.
/// </summary>
public virtual ICustomImagesOperations CustomImages { get; private set; }
/// <summary>
/// Gets the IFormulasOperations.
/// </summary>
public virtual IFormulasOperations Formulas { get; private set; }
/// <summary>
/// Gets the IGalleryImagesOperations.
/// </summary>
public virtual IGalleryImagesOperations GalleryImages { get; private set; }
/// <summary>
/// Gets the INotificationChannelsOperations.
/// </summary>
public virtual INotificationChannelsOperations NotificationChannels { get; private set; }
/// <summary>
/// Gets the IPolicySetsOperations.
/// </summary>
public virtual IPolicySetsOperations PolicySets { get; private set; }
/// <summary>
/// Gets the IPoliciesOperations.
/// </summary>
public virtual IPoliciesOperations Policies { get; private set; }
/// <summary>
/// Gets the ISchedulesOperations.
/// </summary>
public virtual ISchedulesOperations Schedules { get; private set; }
/// <summary>
/// Gets the IServiceRunnersOperations.
/// </summary>
public virtual IServiceRunnersOperations ServiceRunners { get; private set; }
/// <summary>
/// Gets the IUsersOperations.
/// </summary>
public virtual IUsersOperations Users { get; private set; }
/// <summary>
/// Gets the IDisksOperations.
/// </summary>
public virtual IDisksOperations Disks { get; private set; }
/// <summary>
/// Gets the IEnvironmentsOperations.
/// </summary>
public virtual IEnvironmentsOperations Environments { get; private set; }
/// <summary>
/// Gets the ISecretsOperations.
/// </summary>
public virtual ISecretsOperations Secrets { get; private set; }
/// <summary>
/// Gets the IVirtualMachinesOperations.
/// </summary>
public virtual IVirtualMachinesOperations VirtualMachines { get; private set; }
/// <summary>
/// Gets the IVirtualMachineSchedulesOperations.
/// </summary>
public virtual IVirtualMachineSchedulesOperations VirtualMachineSchedules { get; private set; }
/// <summary>
/// Gets the IVirtualNetworksOperations.
/// </summary>
public virtual IVirtualNetworksOperations VirtualNetworks { get; private set; }
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DevTestLabsClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DevTestLabsClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DevTestLabsClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DevTestLabsClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public DevTestLabsClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public DevTestLabsClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public DevTestLabsClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DevTestLabsClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Gets Azure subscription credentials.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public DevTestLabsClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Labs = new LabsOperations(this);
this.GlobalSchedules = new GlobalSchedulesOperations(this);
this.ArtifactSources = new ArtifactSourcesOperations(this);
this.ArmTemplates = new ArmTemplatesOperations(this);
this.Artifacts = new ArtifactsOperations(this);
this.Costs = new CostsOperations(this);
this.CustomImages = new CustomImagesOperations(this);
this.Formulas = new FormulasOperations(this);
this.GalleryImages = new GalleryImagesOperations(this);
this.NotificationChannels = new NotificationChannelsOperations(this);
this.PolicySets = new PolicySetsOperations(this);
this.Policies = new PoliciesOperations(this);
this.Schedules = new SchedulesOperations(this);
this.ServiceRunners = new ServiceRunnersOperations(this);
this.Users = new UsersOperations(this);
this.Disks = new DisksOperations(this);
this.Environments = new EnvironmentsOperations(this);
this.Secrets = new SecretsOperations(this);
this.VirtualMachines = new VirtualMachinesOperations(this);
this.VirtualMachineSchedules = new VirtualMachineSchedulesOperations(this);
this.VirtualNetworks = new VirtualNetworksOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2016-05-15";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
//
// Mono.System.Xml.Serialization.XmlReflectionImporter
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Erik LeBel (eriklebel@yahoo.ca)
// Lluis Sanchez Gual (lluis@ximian.com)
//
// Copyright (C) Tim Coleman, 2002
// (C) 2003 Erik LeBel
//
//
// 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 global::System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using Mono.System.Xml.Schema;
namespace Mono.System.Xml.Serialization {
public class XmlReflectionImporter {
string initialDefaultNamespace;
XmlAttributeOverrides attributeOverrides;
ArrayList includedTypes;
ReflectionHelper helper = new ReflectionHelper();
int arrayChoiceCount = 1;
ArrayList relatedMaps = new ArrayList ();
bool allowPrivateTypes = false;
static readonly string errSimple = "Cannot serialize object of type '{0}'. Base " +
"type '{1}' has simpleContent and can be only extended by adding XmlAttribute " +
"elements. Please consider changing XmlText member of the base class to string array";
static readonly string errSimple2 = "Cannot serialize object of type '{0}'. " +
"Consider changing type of XmlText member '{1}' from '{2}' to string or string array";
#region Constructors
public XmlReflectionImporter ()
: this (null, null)
{
}
public XmlReflectionImporter (string defaultNamespace)
: this (null, defaultNamespace)
{
}
public XmlReflectionImporter (XmlAttributeOverrides attributeOverrides)
: this (attributeOverrides, null)
{
}
public XmlReflectionImporter (XmlAttributeOverrides attributeOverrides, string defaultNamespace)
{
if (defaultNamespace == null)
this.initialDefaultNamespace = String.Empty;
else
this.initialDefaultNamespace = defaultNamespace;
if (attributeOverrides == null)
this.attributeOverrides = new XmlAttributeOverrides();
else
this.attributeOverrides = attributeOverrides;
}
/* void Reset ()
{
helper = new ReflectionHelper();
arrayChoiceCount = 1;
}
*/
internal bool AllowPrivateTypes
{
get { return allowPrivateTypes; }
set { allowPrivateTypes = value; }
}
#endregion // Constructors
#region Methods
public XmlMembersMapping ImportMembersMapping (string elementName,
string ns,
XmlReflectionMember [] members,
bool hasWrapperElement)
{
return ImportMembersMapping (elementName, ns, members, hasWrapperElement, true);
}
#if NET_2_0
[MonoTODO]
public
#endif
XmlMembersMapping ImportMembersMapping (string elementName,
string ns,
XmlReflectionMember[] members,
bool hasWrapperElement,
bool rpc)
{
return ImportMembersMapping (elementName, ns, members, hasWrapperElement, rpc, true);
}
#if NET_2_0
[MonoTODO]
public
#endif
XmlMembersMapping ImportMembersMapping (string elementName,
string ns,
XmlReflectionMember[] members,
bool hasWrapperElement,
bool rpc,
bool openModel)
{
return ImportMembersMapping (elementName, ns, members, hasWrapperElement, rpc, openModel, XmlMappingAccess.Read | XmlMappingAccess.Write);
}
#if NET_2_0
[MonoTODO] // FIXME: handle writeAccessors, validate, and mapping access
public
#endif
XmlMembersMapping ImportMembersMapping (string elementName,
string ns,
XmlReflectionMember[] members,
bool hasWrapperElement,
bool rpc,
bool openModel,
XmlMappingAccess access)
{
// Reset (); Disabled. See ChangeLog
ArrayList mapping = new ArrayList ();
for (int n=0; n<members.Length; n++)
{
XmlTypeMapMember mapMem = CreateMapMember (null, members[n], ns);
mapMem.GlobalIndex = n;
mapMem.CheckOptionalValueType (members);
mapping.Add (new XmlMemberMapping (members[n].MemberName, ns, mapMem, false));
}
elementName = XmlConvert.EncodeLocalName (elementName);
XmlMembersMapping mps = new XmlMembersMapping (elementName, ns, hasWrapperElement, false, (XmlMemberMapping[])mapping.ToArray (typeof(XmlMemberMapping)));
mps.RelatedMaps = relatedMaps;
mps.Format = SerializationFormat.Literal;
Type[] extraTypes = includedTypes != null ? (Type[])includedTypes.ToArray(typeof(Type)) : null;
#if !NET_2_1
mps.Source = new MembersSerializationSource (elementName, hasWrapperElement, members, false, true, ns, extraTypes);
if (allowPrivateTypes) mps.Source.CanBeGenerated = false;
#endif
return mps;
}
public XmlTypeMapping ImportTypeMapping (Type type)
{
return ImportTypeMapping (type, null, null);
}
public XmlTypeMapping ImportTypeMapping (Type type, string defaultNamespace)
{
return ImportTypeMapping (type, null, defaultNamespace);
}
public XmlTypeMapping ImportTypeMapping (Type type, XmlRootAttribute root)
{
return ImportTypeMapping (type, root, null);
}
public XmlTypeMapping ImportTypeMapping (Type type, XmlRootAttribute root, string defaultNamespace)
{
if (type == null)
throw new ArgumentNullException ("type");
if (type == typeof (void))
throw new NotSupportedException ("The type " + type.FullName + " may not be serialized.");
return ImportTypeMapping (TypeTranslator.GetTypeData (type), root,
defaultNamespace);
}
internal XmlTypeMapping ImportTypeMapping (TypeData typeData, string defaultNamespace)
{
return ImportTypeMapping (typeData, (XmlRootAttribute) null,
defaultNamespace);
}
private XmlTypeMapping ImportTypeMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
{
if (typeData == null)
throw new ArgumentNullException ("typeData");
if (typeData.Type == null)
throw new ArgumentException ("Specified TypeData instance does not have Type set.");
if (defaultNamespace == null) defaultNamespace = initialDefaultNamespace;
if (defaultNamespace == null) defaultNamespace = string.Empty;
try {
XmlTypeMapping map;
switch (typeData.SchemaType) {
case SchemaTypes.Class: map = ImportClassMapping (typeData, root, defaultNamespace); break;
case SchemaTypes.Array: map = ImportListMapping (typeData, root, defaultNamespace, null, 0); break;
case SchemaTypes.XmlNode: map = ImportXmlNodeMapping (typeData, root, defaultNamespace); break;
case SchemaTypes.Primitive: map = ImportPrimitiveMapping (typeData, root, defaultNamespace); break;
case SchemaTypes.Enum: map = ImportEnumMapping (typeData, root, defaultNamespace); break;
case SchemaTypes.XmlSerializable: map = ImportXmlSerializableMapping (typeData, root, defaultNamespace); break;
default: throw new NotSupportedException ("Type " + typeData.Type.FullName + " not supported for XML stialization");
}
#if NET_2_0
// bug #372780
map.SetKey (typeData.Type.ToString ());
#endif
map.RelatedMaps = relatedMaps;
map.Format = SerializationFormat.Literal;
Type[] extraTypes = includedTypes != null ? (Type[]) includedTypes.ToArray (typeof (Type)) : null;
#if !NET_2_1
map.Source = new XmlTypeSerializationSource (typeData.Type, root, attributeOverrides, defaultNamespace, extraTypes);
if (allowPrivateTypes) map.Source.CanBeGenerated = false;
#endif
return map;
} catch (InvalidOperationException ex) {
throw new InvalidOperationException (string.Format (CultureInfo.InvariantCulture,
"There was an error reflecting type '{0}'.", typeData.Type.FullName), ex);
}
}
XmlTypeMapping CreateTypeMapping (TypeData typeData, XmlRootAttribute root, string defaultXmlType, string defaultNamespace)
{
bool hasTypeNamespace = !string.IsNullOrEmpty (defaultNamespace);
string rootNamespace = null;
string typeNamespace = null;
string elementName;
bool includeInSchema = true;
XmlAttributes atts = null;
bool nullable = CanBeNull (typeData);
if (defaultXmlType == null) defaultXmlType = typeData.XmlType;
if (!typeData.IsListType)
{
if (attributeOverrides != null)
atts = attributeOverrides[typeData.Type];
if (atts != null && typeData.SchemaType == SchemaTypes.Primitive)
throw new InvalidOperationException ("XmlRoot and XmlType attributes may not be specified for the type " + typeData.FullTypeName);
}
if (atts == null)
atts = new XmlAttributes (typeData.Type);
if (atts.XmlRoot != null && root == null)
root = atts.XmlRoot;
if (atts.XmlType != null)
{
if (atts.XmlType.Namespace != null) {
typeNamespace = atts.XmlType.Namespace;
hasTypeNamespace = true;
}
if (atts.XmlType.TypeName != null && atts.XmlType.TypeName != string.Empty)
defaultXmlType = XmlConvert.EncodeLocalName (atts.XmlType.TypeName);
includeInSchema = atts.XmlType.IncludeInSchema;
}
elementName = defaultXmlType;
if (root != null)
{
if (root.ElementName.Length != 0)
elementName = XmlConvert.EncodeLocalName(root.ElementName);
if (root.Namespace != null) {
rootNamespace = root.Namespace;
hasTypeNamespace = true;
}
nullable = root.IsNullable;
}
rootNamespace = rootNamespace ?? defaultNamespace ?? string.Empty;
typeNamespace = typeNamespace ?? rootNamespace;
XmlTypeMapping map;
switch (typeData.SchemaType) {
case SchemaTypes.XmlSerializable:
map = new XmlSerializableMapping (root, elementName, rootNamespace, typeData, defaultXmlType, typeNamespace);
break;
case SchemaTypes.Primitive:
if (!typeData.IsXsdType)
map = new XmlTypeMapping (elementName, rootNamespace,
typeData, defaultXmlType, XmlSerializer.WsdlTypesNamespace);
else
map = new XmlTypeMapping (elementName, rootNamespace,
typeData, defaultXmlType, typeNamespace);
break;
default:
map = new XmlTypeMapping (elementName, rootNamespace, typeData, defaultXmlType, hasTypeNamespace ? typeNamespace : null);
break;
}
map.IncludeInSchema = includeInSchema;
map.IsNullable = nullable;
relatedMaps.Add (map);
return map;
}
XmlTypeMapping ImportClassMapping (Type type, XmlRootAttribute root, string defaultNamespace)
{
TypeData typeData = TypeTranslator.GetTypeData (type);
return ImportClassMapping (typeData, root, defaultNamespace);
}
XmlTypeMapping ImportClassMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
{
Type type = typeData.Type;
XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
if (map != null) return map;
if (!allowPrivateTypes)
ReflectionHelper.CheckSerializableType (type, false);
map = CreateTypeMapping (typeData, root, null, defaultNamespace);
helper.RegisterClrType (map, type, map.XmlTypeNamespace);
helper.RegisterSchemaType (map, map.XmlType, map.XmlTypeNamespace);
// Import members
ClassMap classMap = new ClassMap ();
map.ObjectMap = classMap;
var members = GetReflectionMembers (type);
bool? isOrderExplicit = null;
foreach (XmlReflectionMember rmember in members)
{
int? order = rmember.XmlAttributes.Order;
if (isOrderExplicit == null)
{
if (order != null)
isOrderExplicit = (int) order >= 0;
}
else if (order != null && isOrderExplicit != ((int) order >= 0))
throw new InvalidOperationException ("Inconsistent XML sequence was detected. If there are XmlElement/XmlArray/XmlAnyElement attributes with explicit Order, then every other member must have an explicit order too.");
}
if (isOrderExplicit == true)
members.Sort ((m1, m2) => (int) m1.XmlAttributes.SortableOrder - (int) m2.XmlAttributes.SortableOrder);
foreach (XmlReflectionMember rmember in members)
{
string ns = map.XmlTypeNamespace;
if (rmember.XmlAttributes.XmlIgnore) continue;
if (rmember.DeclaringType != null && rmember.DeclaringType != type) {
XmlTypeMapping bmap = ImportClassMapping (rmember.DeclaringType, root, defaultNamespace);
if (bmap.HasXmlTypeNamespace)
ns = bmap.XmlTypeNamespace;
}
try {
XmlTypeMapMember mem = CreateMapMember (type, rmember, ns);
mem.CheckOptionalValueType (type);
classMap.AddMember (mem);
} catch (Exception ex) {
throw new InvalidOperationException (string.Format (
CultureInfo.InvariantCulture, "There was an error" +
" reflecting field '{0}'.", rmember.MemberName), ex);
}
}
// Import extra classes
if (type == typeof (object) && includedTypes != null)
{
foreach (Type intype in includedTypes)
map.DerivedTypes.Add (ImportTypeMapping (intype, defaultNamespace));
}
// Register inheritance relations
if (type.BaseType != null)
{
XmlTypeMapping bmap = ImportClassMapping (type.BaseType, root, defaultNamespace);
ClassMap cbmap = bmap.ObjectMap as ClassMap;
if (type.BaseType != typeof (object)) {
map.BaseMap = bmap;
if (!cbmap.HasSimpleContent)
classMap.SetCanBeSimpleType (false);
}
// At this point, derived classes of this map must be already registered
RegisterDerivedMap (bmap, map);
if (cbmap.HasSimpleContent && classMap.ElementMembers != null && classMap.ElementMembers.Count != 1)
throw new InvalidOperationException (String.Format (errSimple, map.TypeData.TypeName, map.BaseMap.TypeData.TypeName));
}
ImportIncludedTypes (type, defaultNamespace);
if (classMap.XmlTextCollector != null && !classMap.HasSimpleContent)
{
XmlTypeMapMember mem = classMap.XmlTextCollector;
if (mem.TypeData.Type != typeof(string) &&
mem.TypeData.Type != typeof(string[]) &&
mem.TypeData.Type != typeof(XmlNode[]) &&
mem.TypeData.Type != typeof(object[]))
throw new InvalidOperationException (String.Format (errSimple2, map.TypeData.TypeName, mem.Name, mem.TypeData.TypeName));
}
return map;
}
void RegisterDerivedMap (XmlTypeMapping map, XmlTypeMapping derivedMap)
{
map.DerivedTypes.Add (derivedMap);
map.DerivedTypes.AddRange (derivedMap.DerivedTypes);
if (map.BaseMap != null)
RegisterDerivedMap (map.BaseMap, derivedMap);
else {
XmlTypeMapping obmap = ImportTypeMapping (typeof(object));
if (obmap != map)
obmap.DerivedTypes.Add (derivedMap);
}
}
string GetTypeNamespace (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
{
string typeNamespace = null;
XmlAttributes atts = null;
if (!typeData.IsListType)
{
if (attributeOverrides != null)
atts = attributeOverrides[typeData.Type];
}
if (atts == null)
atts = new XmlAttributes (typeData.Type);
if (atts.XmlType != null)
{
if (atts.XmlType.Namespace != null && atts.XmlType.Namespace.Length != 0 && typeData.SchemaType != SchemaTypes.Enum)
typeNamespace = atts.XmlType.Namespace;
}
if (typeNamespace != null && typeNamespace.Length != 0) return typeNamespace;
if (atts.XmlRoot != null && root == null)
root = atts.XmlRoot;
if (root != null)
{
if (root.Namespace != null && root.Namespace.Length != 0)
return root.Namespace;
}
if (defaultNamespace == null) return "";
else return defaultNamespace;
}
XmlTypeMapping ImportListMapping (Type type, XmlRootAttribute root, string defaultNamespace, XmlAttributes atts, int nestingLevel)
{
TypeData typeData = TypeTranslator.GetTypeData (type);
return ImportListMapping (typeData, root, defaultNamespace, atts, nestingLevel);
}
XmlTypeMapping ImportListMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace, XmlAttributes atts, int nestingLevel)
{
Type type = typeData.Type;
ListMap obmap = new ListMap ();
if (!allowPrivateTypes)
ReflectionHelper.CheckSerializableType (type, true);
if (atts == null) atts = new XmlAttributes();
Type itemType = typeData.ListItemType;
// warning: byte[][] should not be considered multiarray
bool isMultiArray = (type.IsArray && (TypeTranslator.GetTypeData(itemType).SchemaType == SchemaTypes.Array) && itemType.IsArray);
XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
foreach (XmlArrayItemAttribute att in atts.XmlArrayItems)
{
if (att.Namespace != null && att.Form == XmlSchemaForm.Unqualified)
throw new InvalidOperationException ("XmlArrayItemAttribute.Form must not be Unqualified when it has an explicit Namespace value.");
if (att.NestingLevel != nestingLevel) continue;
Type elemType = (att.Type != null) ? att.Type : itemType;
XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData(elemType, att.DataType));
elem.Namespace = att.Namespace != null ? att.Namespace : defaultNamespace;
if (elem.Namespace == null) elem.Namespace = "";
elem.Form = att.Form;
if (att.Form == XmlSchemaForm.Unqualified)
elem.Namespace = string.Empty;
elem.IsNullable = att.IsNullable && CanBeNull (elem.TypeData);
elem.NestingLevel = att.NestingLevel;
if (isMultiArray) {
elem.MappedType = ImportListMapping (elemType, null, elem.Namespace, atts, nestingLevel + 1);
} else if (elem.TypeData.IsComplexType) {
elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
}
if (att.ElementName.Length != 0) {
elem.ElementName = XmlConvert.EncodeLocalName (att.ElementName);
} else if (elem.MappedType != null) {
elem.ElementName = elem.MappedType.ElementName;
} else {
elem.ElementName = TypeTranslator.GetTypeData (elemType).XmlType;
}
list.Add (elem);
}
if (list.Count == 0)
{
XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (null, TypeTranslator.GetTypeData (itemType));
if (isMultiArray)
elem.MappedType = ImportListMapping (itemType, null, defaultNamespace, atts, nestingLevel + 1);
else if (elem.TypeData.IsComplexType)
elem.MappedType = ImportTypeMapping (itemType, null, defaultNamespace);
if (elem.MappedType != null) {
elem.ElementName = elem.MappedType.XmlType;
} else {
elem.ElementName = TypeTranslator.GetTypeData (itemType).XmlType;
}
elem.Namespace = (defaultNamespace != null) ? defaultNamespace : "";
elem.IsNullable = CanBeNull (elem.TypeData);
list.Add (elem);
}
obmap.ItemInfo = list;
// If there can be different element names (types) in the array, then its name cannot
// be "ArrayOfXXX" it must be something like ArrayOfChoiceNNN
string baseName;
if (list.Count > 1) {
baseName = "ArrayOfChoice" + (arrayChoiceCount++);
} else {
XmlTypeMapElementInfo elem = ((XmlTypeMapElementInfo) list[0]);
if (elem.MappedType != null) {
baseName = TypeTranslator.GetArrayName (elem.MappedType.XmlType);
} else {
baseName = TypeTranslator.GetArrayName (elem.ElementName);
}
}
// Avoid name colisions
int nameCount = 1;
string name = baseName;
do {
XmlTypeMapping foundMap = helper.GetRegisteredSchemaType (name, defaultNamespace);
if (foundMap == null) nameCount = -1;
else if (obmap.Equals (foundMap.ObjectMap) && typeData.Type == foundMap.TypeData.Type) return foundMap;
else name = baseName + (nameCount++);
}
while (nameCount != -1);
XmlTypeMapping map = CreateTypeMapping (typeData, root, name, defaultNamespace);
map.ObjectMap = obmap;
// Register any of the including types as a derived class of object
XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
XmlTypeMapping objectMapping = ImportTypeMapping (typeof(object));
for (int i = 0; i < includes.Length; i++)
{
Type includedType = includes[i].Type;
objectMapping.DerivedTypes.Add(ImportTypeMapping (includedType, null, defaultNamespace));
}
// Register this map as a derived class of object
helper.RegisterSchemaType (map, name, defaultNamespace);
ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
return map;
}
XmlTypeMapping ImportXmlNodeMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
{
Type type = typeData.Type;
XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
if (map != null) return map;
map = CreateTypeMapping (typeData, root, null, defaultNamespace);
helper.RegisterClrType (map, type, map.XmlTypeNamespace);
if (type.BaseType != null)
{
XmlTypeMapping bmap = ImportTypeMapping (type.BaseType, root, defaultNamespace);
if (type.BaseType != typeof (object))
map.BaseMap = bmap;
RegisterDerivedMap (bmap, map);
}
return map;
}
XmlTypeMapping ImportPrimitiveMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
{
Type type = typeData.Type;
XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
if (map != null) return map;
map = CreateTypeMapping (typeData, root, null, defaultNamespace);
helper.RegisterClrType (map, type, map.XmlTypeNamespace);
return map;
}
XmlTypeMapping ImportEnumMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
{
Type type = typeData.Type;
XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
if (map != null) return map;
if (!allowPrivateTypes)
ReflectionHelper.CheckSerializableType (type, false);
map = CreateTypeMapping (typeData, root, null, defaultNamespace);
map.IsNullable = false;
helper.RegisterClrType (map, type, map.XmlTypeNamespace);
ArrayList members = new ArrayList();
string [] names = Enum.GetNames (type);
foreach (string name in names) {
FieldInfo field = type.GetField (name);
string xmlName = null;
if (field.IsDefined(typeof(XmlIgnoreAttribute), false))
continue;
object[] atts = field.GetCustomAttributes (typeof(XmlEnumAttribute), false);
if (atts.Length > 0) xmlName = ((XmlEnumAttribute)atts[0]).Name;
if (xmlName == null) xmlName = name;
long value = ((IConvertible) field.GetValue (null)).ToInt64 (CultureInfo.InvariantCulture);
members.Add (new EnumMap.EnumMapMember (xmlName, name, value));
}
bool isFlags = type.IsDefined (typeof (FlagsAttribute), false);
map.ObjectMap = new EnumMap ((EnumMap.EnumMapMember[])members.ToArray (typeof(EnumMap.EnumMapMember)), isFlags);
ImportTypeMapping (typeof(object)).DerivedTypes.Add (map);
return map;
}
XmlTypeMapping ImportXmlSerializableMapping (TypeData typeData, XmlRootAttribute root, string defaultNamespace)
{
Type type = typeData.Type;
XmlTypeMapping map = helper.GetRegisteredClrType (type, GetTypeNamespace (typeData, root, defaultNamespace));
if (map != null) return map;
if (!allowPrivateTypes)
ReflectionHelper.CheckSerializableType (type, false);
map = CreateTypeMapping (typeData, root, null, defaultNamespace);
helper.RegisterClrType (map, type, map.XmlTypeNamespace);
return map;
}
void ImportIncludedTypes (Type type, string defaultNamespace)
{
XmlIncludeAttribute[] includes = (XmlIncludeAttribute[])type.GetCustomAttributes (typeof (XmlIncludeAttribute), false);
for (int n=0; n<includes.Length; n++)
{
Type includedType = includes[n].Type;
ImportTypeMapping (includedType, null, defaultNamespace);
}
}
List<XmlReflectionMember> GetReflectionMembers (Type type)
{
// First we want to find the inheritance hierarchy in reverse order.
Type currentType = type;
ArrayList typeList = new ArrayList();
typeList.Add(currentType);
while (currentType != typeof(object))
{
currentType = currentType.BaseType; // Read the base type.
typeList.Insert(0, currentType); // Insert at 0 to reverse the order.
}
// Read all Fields via reflection.
ArrayList fieldList = new ArrayList();
FieldInfo[] tfields = type.GetFields (BindingFlags.Instance | BindingFlags.Public);
#if TARGET_JVM
// This statement ensures fields are ordered starting from the base type.
for (int ti=0; ti<typeList.Count; ti++) {
for (int i=0; i<tfields.Length; i++) {
FieldInfo field = tfields[i];
if (field.DeclaringType == typeList[ti])
fieldList.Add (field);
}
}
#else
currentType = null;
int currentIndex = 0;
foreach (FieldInfo field in tfields)
{
// This statement ensures fields are ordered starting from the base type.
if (currentType != field.DeclaringType)
{
currentType = field.DeclaringType;
currentIndex=0;
}
fieldList.Insert(currentIndex++, field);
}
#endif
// Read all Properties via reflection.
ArrayList propList = new ArrayList();
PropertyInfo[] tprops = type.GetProperties (BindingFlags.Instance | BindingFlags.Public);
#if TARGET_JVM
// This statement ensures properties are ordered starting from the base type.
for (int ti=0; ti<typeList.Count; ti++) {
for (int i=0; i<tprops.Length; i++) {
PropertyInfo prop = tprops[i];
if (!prop.CanRead) continue;
if (prop.GetIndexParameters().Length > 0) continue;
if (prop.DeclaringType == typeList[ti])
propList.Add (prop);
}
}
#else
currentType = null;
currentIndex = 0;
foreach (PropertyInfo prop in tprops)
{
// This statement ensures properties are ordered starting from the base type.
if (currentType != prop.DeclaringType)
{
currentType = prop.DeclaringType;
currentIndex = 0;
}
if (!prop.CanRead) continue;
if (prop.GetIndexParameters().Length > 0) continue;
propList.Insert(currentIndex++, prop);
}
#endif
var members = new List<XmlReflectionMember>();
int fieldIndex=0;
int propIndex=0;
// We now step through the type hierarchy from the base (object) through
// to the supplied class, as each step outputting all Fields, and then
// all Properties. This is the exact same ordering as .NET 1.0/1.1.
foreach (Type t in typeList)
{
// Add any fields matching the current DeclaringType.
while (fieldIndex < fieldList.Count)
{
FieldInfo field = (FieldInfo)fieldList[fieldIndex];
if (field.DeclaringType==t)
{
fieldIndex++;
XmlAttributes atts = attributeOverrides[type, field.Name];
if (atts == null) atts = new XmlAttributes (field);
if (atts.XmlIgnore) continue;
XmlReflectionMember member = new XmlReflectionMember(field.Name, field.FieldType, atts);
member.DeclaringType = field.DeclaringType;
members.Add(member);
}
else break;
}
// Add any properties matching the current DeclaringType.
while (propIndex < propList.Count)
{
PropertyInfo prop = (PropertyInfo)propList[propIndex];
if (prop.DeclaringType==t)
{
propIndex++;
XmlAttributes atts = attributeOverrides[type, prop.Name];
if (atts == null) atts = new XmlAttributes (prop);
if (atts.XmlIgnore) continue;
if (!prop.CanWrite) {
if (prop.PropertyType.IsGenericType && TypeData.GetGenericListItemType (prop.PropertyType) == null) continue; // check this before calling GetTypeData() which raises error for missing Add(). See bug #704813.
if (TypeTranslator.GetTypeData (prop.PropertyType).SchemaType != SchemaTypes.Array || prop.PropertyType.IsArray) continue;
}
XmlReflectionMember member = new XmlReflectionMember(prop.Name, prop.PropertyType, atts);
member.DeclaringType = prop.DeclaringType;
members.Add(member);
}
else break;
}
}
return members;
}
private XmlTypeMapMember CreateMapMember (Type declaringType, XmlReflectionMember rmember, string defaultNamespace)
{
XmlTypeMapMember mapMember;
XmlAttributes atts = rmember.XmlAttributes;
TypeData typeData = TypeTranslator.GetTypeData (rmember.MemberType);
if (atts.XmlArray != null) {
if (atts.XmlArray.Namespace != null && atts.XmlArray.Form == XmlSchemaForm.Unqualified)
throw new InvalidOperationException ("XmlArrayAttribute.Form must not be Unqualified when it has an explicit Namespace value.");
if (typeData.SchemaType != SchemaTypes.Array &&
!(typeData.SchemaType == SchemaTypes.Primitive && typeData.Type == typeof (byte [])))
throw new InvalidOperationException ("XmlArrayAttribute can be applied to members of array or collection type.");
}
if (atts.XmlAnyAttribute != null)
{
if ( (rmember.MemberType.FullName == "Mono.System.Xml.XmlAttribute[]") ||
(rmember.MemberType.FullName == "Mono.System.Xml.XmlNode[]") )
{
mapMember = new XmlTypeMapMemberAnyAttribute();
}
else
throw new InvalidOperationException ("XmlAnyAttributeAttribute can only be applied to members of type XmlAttribute[] or XmlNode[]");
}
else
if (atts.XmlAnyElements != null && atts.XmlAnyElements.Count > 0)
{
// no XmlNode type check is done here (seealso: bug #553032).
XmlTypeMapMemberAnyElement member = new XmlTypeMapMemberAnyElement();
member.ElementInfo = ImportAnyElementInfo (defaultNamespace, rmember, member, atts);
mapMember = member;
}
else if (atts.Xmlns)
{
XmlTypeMapMemberNamespaces mapNamespaces = new XmlTypeMapMemberNamespaces ();
mapMember = mapNamespaces;
}
else if (atts.XmlAttribute != null)
{
// An attribute
if (atts.XmlElements != null && atts.XmlElements.Count > 0)
throw new Exception ("XmlAttributeAttribute and XmlElementAttribute cannot be applied to the same member");
XmlTypeMapMemberAttribute mapAttribute = new XmlTypeMapMemberAttribute ();
if (atts.XmlAttribute.AttributeName.Length == 0)
mapAttribute.AttributeName = rmember.MemberName;
else
mapAttribute.AttributeName = atts.XmlAttribute.AttributeName;
mapAttribute.AttributeName = XmlConvert.EncodeLocalName (mapAttribute.AttributeName);
if (typeData.IsComplexType)
mapAttribute.MappedType = ImportTypeMapping (typeData.Type, null, defaultNamespace);
if (atts.XmlAttribute.Namespace != null && atts.XmlAttribute.Namespace != defaultNamespace)
{
if (atts.XmlAttribute.Form == XmlSchemaForm.Unqualified)
throw new InvalidOperationException ("The Form property may not be 'Unqualified' when an explicit Namespace property is present");
mapAttribute.Form = XmlSchemaForm.Qualified;
mapAttribute.Namespace = atts.XmlAttribute.Namespace;
}
else
{
mapAttribute.Form = atts.XmlAttribute.Form;
if (atts.XmlAttribute.Form == XmlSchemaForm.Qualified)
mapAttribute.Namespace = defaultNamespace;
else
mapAttribute.Namespace = "";
}
typeData = TypeTranslator.GetTypeData(rmember.MemberType, atts.XmlAttribute.DataType);
mapMember = mapAttribute;
}
else if (typeData.SchemaType == SchemaTypes.Array)
{
// If the member has a single XmlElementAttribute and the type is the type of the member,
// then it is not a flat list
if (atts.XmlElements.Count > 1 ||
(atts.XmlElements.Count == 1 && atts.XmlElements[0].Type != typeData.Type) ||
(atts.XmlText != null))
{
// A flat list
// check that it does not have XmlArrayAttribute
if (atts.XmlArray != null)
throw new InvalidOperationException ("XmlArrayAttribute cannot be used with members which also attributed with XmlElementAttribute or XmlTextAttribute.");
XmlTypeMapMemberFlatList member = new XmlTypeMapMemberFlatList ();
member.ListMap = new ListMap ();
member.ListMap.ItemInfo = ImportElementInfo (declaringType, XmlConvert.EncodeLocalName (rmember.MemberName), defaultNamespace, typeData.ListItemType, member, atts);
member.ElementInfo = member.ListMap.ItemInfo;
member.ListMap.ChoiceMember = member.ChoiceMember;
mapMember = member;
}
else
{
// A list
XmlTypeMapMemberList member = new XmlTypeMapMemberList ();
// Creates an ElementInfo that identifies the array instance.
member.ElementInfo = new XmlTypeMapElementInfoList();
XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, typeData);
elem.ElementName = XmlConvert.EncodeLocalName((atts.XmlArray != null && atts.XmlArray.ElementName.Length != 0) ? atts.XmlArray.ElementName : rmember.MemberName);
// note that it could be changed below (when Form is Unqualified)
elem.Namespace = (atts.XmlArray != null && atts.XmlArray.Namespace != null) ? atts.XmlArray.Namespace : defaultNamespace;
elem.MappedType = ImportListMapping (rmember.MemberType, null, elem.Namespace, atts, 0);
elem.IsNullable = (atts.XmlArray != null) ? atts.XmlArray.IsNullable : false;
elem.Form = (atts.XmlArray != null) ? atts.XmlArray.Form : XmlSchemaForm.Qualified;
elem.ExplicitOrder = (atts.XmlArray != null) ? atts.XmlArray.Order : -1;
// This is a bit tricky, but is done
// after filling descendant members, so
// that array items could be serialized
// with proper namespace.
if (atts.XmlArray != null && atts.XmlArray.Form == XmlSchemaForm.Unqualified)
elem.Namespace = String.Empty;
member.ElementInfo.Add (elem);
mapMember = member;
}
}
else
{
// An element
XmlTypeMapMemberElement member = new XmlTypeMapMemberElement ();
member.ElementInfo = ImportElementInfo (declaringType, XmlConvert.EncodeLocalName(rmember.MemberName), defaultNamespace, rmember.MemberType, member, atts);
mapMember = member;
}
mapMember.DefaultValue = GetDefaultValue (typeData, atts.XmlDefaultValue);
mapMember.TypeData = typeData;
mapMember.Name = rmember.MemberName;
mapMember.IsReturnValue = rmember.IsReturnValue;
return mapMember;
}
XmlTypeMapElementInfoList ImportElementInfo (Type cls, string defaultName, string defaultNamespace, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts)
{
EnumMap choiceEnumMap = null;
Type choiceEnumType = null;
XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
ImportTextElementInfo (list, defaultType, member, atts, defaultNamespace);
if (atts.XmlChoiceIdentifier != null) {
if (cls == null)
throw new InvalidOperationException ("XmlChoiceIdentifierAttribute not supported in this context.");
member.ChoiceMember = atts.XmlChoiceIdentifier.MemberName;
MemberInfo[] mems = cls.GetMember (member.ChoiceMember, BindingFlags.Instance|BindingFlags.Public);
if (mems.Length == 0)
throw new InvalidOperationException ("Choice member '" + member.ChoiceMember + "' not found in class '" + cls);
if (mems[0] is PropertyInfo) {
PropertyInfo pi = (PropertyInfo)mems[0];
if (!pi.CanWrite || !pi.CanRead)
throw new InvalidOperationException ("Choice property '" + member.ChoiceMember + "' must be read/write.");
choiceEnumType = pi.PropertyType;
}
else choiceEnumType = ((FieldInfo)mems[0]).FieldType;
member.ChoiceTypeData = TypeTranslator.GetTypeData (choiceEnumType);
if (choiceEnumType.IsArray)
choiceEnumType = choiceEnumType.GetElementType ();
choiceEnumMap = ImportTypeMapping (choiceEnumType).ObjectMap as EnumMap;
if (choiceEnumMap == null)
throw new InvalidOperationException ("The member '" + mems[0].Name + "' is not a valid target for XmlChoiceIdentifierAttribute.");
}
if (atts.XmlElements.Count == 0 && list.Count == 0)
{
XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType));
elem.ElementName = defaultName;
elem.Namespace = defaultNamespace;
if (elem.TypeData.IsComplexType)
elem.MappedType = ImportTypeMapping (defaultType, null, defaultNamespace);
list.Add (elem);
}
bool multiType = (atts.XmlElements.Count > 1);
foreach (XmlElementAttribute att in atts.XmlElements)
{
Type elemType = (att.Type != null) ? att.Type : defaultType;
XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(elemType, att.DataType));
elem.Form = att.Form;
if (elem.Form != XmlSchemaForm.Unqualified)
elem.Namespace = (att.Namespace != null) ? att.Namespace : defaultNamespace;
// elem may already be nullable, and IsNullable property in XmlElement is false by default
if (att.IsNullable && !elem.IsNullable)
elem.IsNullable = att.IsNullable;
elem.ExplicitOrder = att.Order;
if (elem.IsNullable && !elem.TypeData.IsNullable)
throw new InvalidOperationException ("IsNullable may not be 'true' for value type " + elem.TypeData.FullTypeName + " in member '" + defaultName + "'");
if (elem.TypeData.IsComplexType)
{
if (att.DataType.Length != 0) throw new InvalidOperationException (
string.Format(CultureInfo.InvariantCulture, "'{0}' is "
+ "an invalid value for '{1}.{2}' of type '{3}'. "
+ "The property may only be specified for primitive types.",
att.DataType, cls.FullName, defaultName,
elem.TypeData.FullTypeName));
elem.MappedType = ImportTypeMapping (elemType, null, elem.Namespace);
}
if (att.ElementName.Length != 0) {
elem.ElementName = XmlConvert.EncodeLocalName(att.ElementName);
} else if (multiType) {
if (elem.MappedType != null) {
elem.ElementName = elem.MappedType.ElementName;
} else {
elem.ElementName = TypeTranslator.GetTypeData (elemType).XmlType;
}
} else {
elem.ElementName = defaultName;
}
if (choiceEnumMap != null) {
string cname = choiceEnumMap.GetEnumName (choiceEnumType.FullName, elem.ElementName);
if (cname == null)
throw new InvalidOperationException (string.Format (
CultureInfo.InvariantCulture, "Type {0} is missing"
+ " enumeration value '{1}' for element '{1} from"
+ " namespace '{2}'.", choiceEnumType, elem.ElementName,
elem.Namespace));
elem.ChoiceValue = Enum.Parse (choiceEnumType, cname, false);
}
list.Add (elem);
}
return list;
}
XmlTypeMapElementInfoList ImportAnyElementInfo (string defaultNamespace, XmlReflectionMember rmember, XmlTypeMapMemberElement member, XmlAttributes atts)
{
XmlTypeMapElementInfoList list = new XmlTypeMapElementInfoList();
ImportTextElementInfo (list, rmember.MemberType, member, atts, defaultNamespace);
foreach (XmlAnyElementAttribute att in atts.XmlAnyElements)
{
XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(typeof(XmlElement)));
if (att.Name.Length != 0)
{
elem.ElementName = XmlConvert.EncodeLocalName(att.Name);
elem.Namespace = (att.Namespace != null) ? att.Namespace : "";
}
else
{
elem.IsUnnamedAnyElement = true;
elem.Namespace = defaultNamespace;
if (att.Namespace != null)
throw new InvalidOperationException ("The element " + rmember.MemberName + " has been attributed with an XmlAnyElementAttribute and a namespace '" + att.Namespace + "', but no name. When a namespace is supplied, a name is also required. Supply a name or remove the namespace.");
}
elem.ExplicitOrder = att.Order;
list.Add (elem);
}
return list;
}
void ImportTextElementInfo (XmlTypeMapElementInfoList list, Type defaultType, XmlTypeMapMemberElement member, XmlAttributes atts, string defaultNamespace)
{
if (atts.XmlText != null)
{
member.IsXmlTextCollector = true;
if (atts.XmlText.Type != null) {
TypeData td = TypeTranslator.GetTypeData (defaultType);
if ((td.SchemaType == SchemaTypes.Primitive || td.SchemaType == SchemaTypes.Enum) && atts.XmlText.Type != defaultType) {
throw new InvalidOperationException ("The type for XmlText may not be specified for primitive types.");
}
defaultType = atts.XmlText.Type;
}
if (defaultType == typeof(XmlNode)) defaultType = typeof(XmlText); // Nodes must be text nodes
XmlTypeMapElementInfo elem = new XmlTypeMapElementInfo (member, TypeTranslator.GetTypeData(defaultType, atts.XmlText.DataType));
if (elem.TypeData.SchemaType != SchemaTypes.Primitive &&
elem.TypeData.SchemaType != SchemaTypes.Enum &&
elem.TypeData.SchemaType != SchemaTypes.XmlNode &&
!(elem.TypeData.SchemaType == SchemaTypes.Array && elem.TypeData.ListItemTypeData.SchemaType == SchemaTypes.XmlNode)
)
throw new InvalidOperationException ("XmlText cannot be used to encode complex types");
if (elem.TypeData.IsComplexType)
elem.MappedType = ImportTypeMapping (defaultType, null, defaultNamespace);
elem.IsTextElement = true;
elem.WrappedElement = false;
list.Add (elem);
}
}
bool CanBeNull (TypeData type)
{
#if !NET_2_0 // idiotic compatibility
if (type.Type == typeof (XmlQualifiedName))
return false;
#endif
return !type.Type.IsValueType || type.IsNullable;
}
public void IncludeType (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
if (includedTypes == null) includedTypes = new ArrayList ();
if (!includedTypes.Contains (type))
includedTypes.Add (type);
if (relatedMaps.Count > 0) {
foreach (XmlTypeMapping map in (ArrayList) relatedMaps.Clone ()) {
if (map.TypeData.Type == typeof(object))
map.DerivedTypes.Add (ImportTypeMapping (type));
}
}
}
public void IncludeTypes (ICustomAttributeProvider provider)
{
object[] ats = provider.GetCustomAttributes (typeof(XmlIncludeAttribute), true);
foreach (XmlIncludeAttribute at in ats)
IncludeType (at.Type);
}
private object GetDefaultValue (TypeData typeData, object defaultValue)
{
if (defaultValue == DBNull.Value || typeData.SchemaType != SchemaTypes.Enum)
return defaultValue;
// get string representation of enum value
string namedValue = Enum.Format (typeData.Type, defaultValue, "g");
// get decimal representation of enum value
string decimalValue = Enum.Format (typeData.Type, defaultValue, "d");
// if decimal representation matches string representation, then
// the value is not defined in the enum type (as the "g" format
// will return the decimal equivalent of the value if the value
// is not equal to a combination of named enumerated constants
if (namedValue == decimalValue) {
string msg = string.Format (CultureInfo.InvariantCulture,
"Value '{0}' cannot be converted to {1}.", defaultValue,
defaultValue.GetType ().FullName);
throw new InvalidOperationException (msg);
}
// XmlSerializer expects integral enum value
//return namedValue.Replace (',', ' ');
return defaultValue;
}
#endregion // Methods
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.