context stringlengths 2.52k 185k | gt stringclasses 1
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 Debugger.Common;
using Debugger.RemoteTargetRpc;
using DebuggerApi;
using DebuggerCommonApi;
using DebuggerGrpcClient.Interfaces;
using System;
using System.Collections.Generic;
using YetiCommon;
namespace DebuggerGrpcClient
{
// <summary>
// Creates RemoteTarget objects.
// </summary>
public class GrpcTargetFactory
{
public virtual RemoteTarget Create(GrpcConnection connection, GrpcSbTarget grpcSbTarget)
{
return new RemoteTargetProxy(connection, grpcSbTarget);
}
}
// <summary>
// Implementation of the RemoteTarget interface that uses GRPC to make RPCs to a remote
// endpoint.
// </summary>
class RemoteTargetProxy : RemoteTarget
{
readonly GrpcConnection connection;
readonly GrpcSbTarget grpcSbTarget;
readonly RemoteTargetRpcService.RemoteTargetRpcServiceClient client;
readonly GrpcBreakpointFactory breakpointFactory;
readonly GrpcErrorFactory errorFactory;
readonly GrpcProcessFactory processFactory;
readonly GrpcModuleFactory moduleFactory;
readonly GrpcWatchpointFactory watchpointFactory;
readonly GrpcAddressFactory addressFactory;
public RemoteTargetProxy(GrpcConnection connection, GrpcSbTarget grpcSbTarget) : this(
connection, grpcSbTarget,
new RemoteTargetRpcService.RemoteTargetRpcServiceClient(connection.CallInvoker),
new GrpcBreakpointFactory(), new GrpcErrorFactory(), new GrpcProcessFactory(),
new GrpcModuleFactory(), new GrpcWatchpointFactory(), new GrpcAddressFactory())
{ }
public RemoteTargetProxy(GrpcConnection connection, GrpcSbTarget grpcSbTarget,
RemoteTargetRpcService.RemoteTargetRpcServiceClient client,
GrpcBreakpointFactory breakpointFactory, GrpcErrorFactory errorFactory,
GrpcProcessFactory processFactory, GrpcModuleFactory moduleFactory,
GrpcWatchpointFactory watchpointFactory, GrpcAddressFactory addressFactory)
{
this.connection = connection;
this.grpcSbTarget = grpcSbTarget;
this.client = client;
this.breakpointFactory = breakpointFactory;
this.errorFactory = errorFactory;
this.processFactory = processFactory;
this.moduleFactory = moduleFactory;
this.watchpointFactory = watchpointFactory;
this.addressFactory = addressFactory;
}
public SbProcess AttachToProcessWithID(SbListener listener, ulong pid, out SbError error)
{
var request = new AttachToProcessWithIDRequest()
{
Target = grpcSbTarget,
Listener = new GrpcSbListener() { Id = listener.GetId() },
Pid = pid,
};
AttachToProcessWithIDResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.AttachToProcessWithID(request);
}))
{
error = errorFactory.Create(response.Error);
if (response.Process == null)
{
return null;
}
return processFactory.Create(connection, response.Process);
}
var grpcError = new GrpcSbError
{
Success = false,
Error = "Rpc error while calling AttachToProcessWithId."
};
error = errorFactory.Create(grpcError);
return null;
}
public RemoteBreakpoint BreakpointCreateByLocation(string file, uint line)
{
var request = new BreakpointCreateByLocationRequest()
{
Target = grpcSbTarget,
File = file,
Line = line,
};
BreakpointCreateByLocationResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.BreakpointCreateByLocation(request);
}))
{
if (response.Breakpoint != null && response.Breakpoint.Id != 0)
{
return breakpointFactory.Create(connection, response.Breakpoint);
}
}
return null;
}
public RemoteBreakpoint BreakpointCreateByName(string symbolName)
{
var request = new BreakpointCreateByNameRequest()
{
Target = grpcSbTarget,
SymbolName = symbolName,
};
BreakpointCreateByNameResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.BreakpointCreateByName(request);
}))
{
if (response.Breakpoint != null && response.Breakpoint.Id != 0)
{
return breakpointFactory.Create(connection, response.Breakpoint);
}
}
return null;
}
public RemoteBreakpoint BreakpointCreateByAddress(ulong address)
{
var request = new BreakpointCreateByAddressRequest()
{
Target = grpcSbTarget,
Address = address,
};
BreakpointCreateByAddressResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.BreakpointCreateByAddress(request);
}))
{
if (response.Breakpoint != null && response.Breakpoint.Id != 0)
{
return breakpointFactory.Create(connection, response.Breakpoint);
}
}
return null;
}
public BreakpointErrorPair CreateFunctionOffsetBreakpoint(string symbolName, uint offset)
{
var request = new CreateFunctionOffsetBreakpointRequest()
{
Target = grpcSbTarget,
SymbolName = symbolName,
Offset = offset
};
CreateFunctionOffsetBreakpointResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.CreateFunctionOffsetBreakpoint(request);
}))
{
if (response.Breakpoint != null && response.Breakpoint.Id != 0)
{
return new BreakpointErrorPair(
breakpointFactory.Create(connection, response.Breakpoint),
EnumUtil.ConvertTo<DebuggerApi.BreakpointError>(response.Error));
}
}
return new BreakpointErrorPair(null,
EnumUtil.ConvertTo<DebuggerApi.BreakpointError>(response.Error));
}
public bool BreakpointDelete(int breakpointId)
{
BreakpointDeleteResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.BreakpointDelete(
new BreakpointDeleteRequest
{
Target = grpcSbTarget,
BreakpointId = breakpointId
});
}))
{
return response.Success;
}
return false;
}
public int GetNumModules()
{
var request = new GetNumModulesRequest()
{
Target = grpcSbTarget,
};
GetNumModulesResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetNumModules(request);
}))
{
return response.Result;
}
return 0;
}
public SbModule GetModuleAtIndex(int index)
{
var request = new GetModuleAtIndexRequest()
{
Target = grpcSbTarget,
Index = index,
};
GetModuleAtIndexResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.GetModuleAtIndex(request);
}))
{
if (response.Module != null && response.Module.Id != 0)
{
return moduleFactory.Create(connection, response.Module);
}
}
return null;
}
public long GetId()
{
return grpcSbTarget.Id;
}
public SbWatchpoint WatchAddress(long address, ulong size, bool read, bool write,
out SbError error)
{
WatchAddressResponse response = null;
error = null;
if (connection.InvokeRpc(() =>
{
response = client.WatchAddress(
new WatchAddressRequest
{
Target = grpcSbTarget,
Address = address,
Size = size,
Read = read,
Write = write
});
}))
{
error = errorFactory.Create(response.Error);
if (response.Watchpoint != null && response.Watchpoint.Id != 0)
{
return watchpointFactory.Create(connection, response.Watchpoint);
}
return null;
}
var grpcError = new GrpcSbError
{
Success = false,
Error = "Rpc error while calling WatchAddress."
};
error = errorFactory.Create(grpcError);
return null;
}
public bool DeleteWatchpoint(int watchId)
{
DeleteWatchpointResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.DeleteWatchpoint(
new DeleteWatchpointRequest
{
Target = grpcSbTarget,
WatchId = watchId
});
}))
{
return response.Success;
}
return false;
}
public RemoteBreakpoint FindBreakpointById(int id)
{
throw new NotImplementedException();
}
public SbAddress ResolveLoadAddress(ulong address)
{
var request = new ResolveLoadAddressRequest()
{
Target = grpcSbTarget,
Address = address,
};
ResolveLoadAddressResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.ResolveLoadAddress(request);
}))
{
if (response.Address != null && response.Address.Id != 0)
{
return addressFactory.Create(connection, response.Address);
}
}
return null;
}
// <summary>
// |coreFile| should be a path to core file on the local machine.
// </summary>
public SbProcess LoadCore(string coreFile)
{
LoadCoreResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.LoadCore(new LoadCoreRequest
{
Target = grpcSbTarget,
CorePath = coreFile
});
}))
{
if (response.Process != null)
{
return processFactory.Create(connection, response.Process);
}
}
return null;
}
public SbModule AddModule(string path, string triple, string uuid)
{
AddModuleResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.AddModule(new AddModuleRequest
{
Target = grpcSbTarget,
Path = path,
Triple = triple,
Uuid = uuid,
});
}))
{
if (response.Module != null && response.Module.Id != 0)
{
return moduleFactory.Create(connection, response.Module);
}
}
return null;
}
public bool RemoveModule(SbModule module)
{
RemoveModuleResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.RemoveModule(new RemoveModuleRequest
{
Target = grpcSbTarget,
Module = new GrpcSbModule { Id = module.GetId() },
});
}))
{
return response.Result;
}
return false;
}
public SbError SetModuleLoadAddress(SbModule module, long sectionsOffset)
{
SetModuleLoadAddressResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.SetModuleLoadAddress(
new SetModuleLoadAddressRequest
{
Target = grpcSbTarget,
Module = new GrpcSbModule { Id = module.GetId() },
SectionsOffset = sectionsOffset,
});
}))
{
return errorFactory.Create(response.Error);
}
var grpcSbError = new GrpcSbError
{
Success = false,
Error = "Rpc error while calling SetModuleLoadAddress."
};
return errorFactory.Create(grpcSbError);
}
public List<InstructionInfo> ReadInstructionInfos(SbAddress address,
uint count, string flavor)
{
ReadInstructionInfosResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.ReadInstructionInfos(
new ReadInstructionInfosRequest
{
Target = grpcSbTarget,
Address = new GrpcSbAddress { Id = address.GetId() },
Count = count,
Flavor = flavor,
});
}))
{
var instructions = new List<InstructionInfo>();
foreach (var instruction in response.Instructions)
{
instructions.Add(new InstructionInfo(
instruction.Address,
instruction.Operands,
instruction.Comment,
instruction.Mnemonic,
instruction.SymbolName,
FrameInfoUtils.CreateLineEntryInfo(instruction.LineEntry)));
}
return instructions;
}
return new List<InstructionInfo>();
}
public EventType AddListener(SbListener listener, EventType eventMask)
{
var request = new AddListenerRequest
{
Target = grpcSbTarget,
Listener = new GrpcSbListener { Id = listener.GetId() },
EventMask = (uint)eventMask
};
AddListenerResponse response = null;
if (connection.InvokeRpc(() =>
{
response = client.AddListener(request);
}))
{
return (EventType)response.Result;
}
return 0;
}
}
}
| |
// 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using Azure;
using Management;
using Rest;
using Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// AppServiceCertificateOrdersOperations operations.
/// </summary>
public partial interface IAppServiceCertificateOrdersOperations
{
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificateOrder>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Validate information for a certificate order.
/// </summary>
/// <remarks>
/// Validate information for a certificate order.
/// </remarks>
/// <param name='appServiceCertificateOrder'>
/// Information for a certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> ValidatePurchaseInformationWithHttpMessagesAsync(AppServiceCertificateOrder appServiceCertificateOrder, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificateOrder>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificate>>> ListCertificatesWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Get the certificate associated with a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificate>> GetCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificate>> CreateOrUpdateCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, AppServiceCertificate keyVaultCertificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete the certificate associated with a certificate order.
/// </summary>
/// <remarks>
/// Delete the certificate associated with a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> DeleteCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get a certificate order.
/// </summary>
/// <remarks>
/// Get a certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificateOrder>> GetWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to to use for the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificateOrder>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, AppServiceCertificateOrder certificateDistinguishedName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Delete an existing certificate order.
/// </summary>
/// <remarks>
/// Delete an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> DeleteCertificateOrderWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Reissue an existing certificate order.
/// </summary>
/// <remarks>
/// Reissue an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='reissueCertificateOrderRequest'>
/// Parameters for the reissue.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> ReissueWithHttpMessagesAsync(string resourceGroupName, string name, ReissueCertificateOrderRequest reissueCertificateOrderRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Renew an existing certificate order.
/// </summary>
/// <remarks>
/// Renew an existing certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Certificate name
/// </param>
/// <param name='renewCertificateOrderRequest'>
/// Renew parameters
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> RenewWithHttpMessagesAsync(string resourceGroupName, string name, RenewCertificateOrderRequest renewCertificateOrderRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Resend certificate email.
/// </summary>
/// <remarks>
/// Resend certificate email.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Certificate order name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> ResendEmailWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Certificate order name
/// </param>
/// <param name='nameIdentifier'>
/// Email address
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> ResendRequestEmailsWithHttpMessagesAsync(string resourceGroupName, string name, NameIdentifier nameIdentifier, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve the list of certificate actions.
/// </summary>
/// <remarks>
/// Retrieve the list of certificate actions.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Certificate order name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<IList<CertificateOrderAction>>> RetrieveCertificateActionsWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Retrieve email history.
/// </summary>
/// <remarks>
/// Retrieve email history.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Certificate order name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<IList<CertificateEmail>>> RetrieveCertificateEmailHistoryWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Certificate order name
/// </param>
/// <param name='siteSealRequest'>
/// Site seal request
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<SiteSeal>> RetrieveSiteSealWithHttpMessagesAsync(string resourceGroupName, string name, SiteSealRequest siteSealRequest, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Verify domain ownership for this certificate order.
/// </summary>
/// <remarks>
/// Verify domain ownership for this certificate order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Certificate order name
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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> VerifyDomainOwnershipWithHttpMessagesAsync(string resourceGroupName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </summary>
/// <remarks>
/// Creates or updates a certificate and associates with key vault
/// secret.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='certificateOrderName'>
/// Name of the certificate order.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='keyVaultCertificate'>
/// Key vault certificate resource Id.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificate>> BeginCreateOrUpdateCertificateWithHttpMessagesAsync(string resourceGroupName, string certificateOrderName, string name, AppServiceCertificate keyVaultCertificate, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Create or update a certificate purchase order.
/// </summary>
/// <remarks>
/// Create or update a certificate purchase order.
/// </remarks>
/// <param name='resourceGroupName'>
/// Name of the resource group to which the resource belongs.
/// </param>
/// <param name='name'>
/// Name of the certificate.
/// </param>
/// <param name='certificateDistinguishedName'>
/// Distinguished name to to use for the certificate order.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificateOrder>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string name, AppServiceCertificateOrder certificateDistinguishedName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificate orders in a subscription.
/// </summary>
/// <remarks>
/// List all certificate orders in a subscription.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificateOrder>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Get certificate orders in a resource group.
/// </summary>
/// <remarks>
/// Get certificate orders in a resource group.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificateOrder>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// List all certificates associated with a certificate order.
/// </summary>
/// <remarks>
/// List all certificates associated with a certificate order.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// 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<AppServiceCertificate>>> ListCertificatesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
namespace DotSpatial.Data
{
/// <summary>
/// mw.png provides read-write support for a png format that also can provide overviews etc.
/// This cannot work with any possible png file, but rather provides at least one common
/// format that can be used natively for large files that is better at compression than
/// just storing the values directly.
/// http://www.w3.org/TR/2003/REC-PNG-20031110/#11PLTE.
/// </summary>
public class MwPng
{
#region Methods
/// <summary>
/// Many rows may be evaluated by this process, but the first value in the array should
/// be aligned with the left side of the image.
/// </summary>
/// <param name="refData">The original bytes to apply the PaethPredictor to.</param>
/// <param name="offset">The integer offset in the array where the filter should begin application. If this is 0, then
/// it assumes that there is no previous scan-line to work with.</param>
/// <param name="length">The number of bytes to filter, starting at the specified offset. This should be evenly divisible by the width.</param>
/// <param name="width">The integer width of a scan-line for grabbing the c and b bytes.</param>
/// <returns>The entire length of bytes starting with the specified offset.</returns>
/// <exception cref="PngInsuficientLengthException">Thrown if the offset and the length together lay after the refData.Length.</exception>
public static byte[] Filter(byte[] refData, int offset, int length, int width)
{
// the 'B' and 'C' values of the first row are considered to be 0.
// the 'A' value of the first column is considered to be 0.
if (refData.Length - offset < length)
{
throw new PngInsuficientLengthException(length, refData.Length, offset);
}
int numrows = length / width;
// The output also consists of a byte before each line that specifies the Paeth prediction filter is being used
byte[] result = new byte[numrows + length];
int source = offset;
int dest = 0;
for (int row = 0; row < numrows; row++)
{
result[dest] = 4;
dest++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : refData[source - 1];
byte b = (row == 0 || col == 0) ? (byte)0 : refData[source - width - 1];
byte c = (row == 0) ? (byte)0 : refData[source - width];
result[dest] = (byte)((refData[source] - PaethPredictor(a, b, c)) % 256);
source++;
dest++;
}
}
return result;
}
/// <summary>
/// Checks whether the signature is valid.
/// </summary>
/// <param name="signature">The signature.</param>
/// <returns>True, if the signatur is valid.</returns>
public static bool SignatureIsValid(byte[] signature)
{
byte[] test = { 137, 80, 78, 71, 13, 10, 26, 10 };
for (int i = 0; i < 8; i++)
{
if (signature[i] != test[i]) return false;
}
return true;
}
/// <summary>
/// Converts a value into Big-endian Uint format.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static byte[] ToBytesAsUInt32(long value)
{
uint temp = Convert.ToUInt32(value);
byte[] arr = BitConverter.GetBytes(temp);
if (BitConverter.IsLittleEndian) Array.Reverse(arr);
return arr;
}
/// <summary>
/// Reads a fileName into the specified bitmap.
/// </summary>
/// <param name="fileName">The file name.</param>
/// <returns>The created bitmap.</returns>
/// <exception cref="PngInvalidSignatureException">If the file signature doesn't match the png file signature.</exception>
public Bitmap Read(string fileName)
{
Stream f = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, 1000000);
byte[] signature = new byte[8];
f.Read(signature, 0, 8);
if (!SignatureIsValid(signature))
{
throw new PngInvalidSignatureException();
}
f.Close();
return new Bitmap(10, 10);
}
/// <summary>
/// Unfilters the data in order to reconstruct the original values.
/// </summary>
/// <param name="filterStream">The filtered but decompressed bytes.</param>
/// <param name="offset">the integer offset where reconstruction should begin.</param>
/// <param name="length">The integer length of bytes to deconstruct.</param>
/// <param name="width">The integer width of a scan-line in bytes (not counting any filter type bytes.</param>
/// <returns>The unfiltered data.</returns>
/// <exception cref="PngInsuficientLengthException">Thrown if the length and offset together lay behind the streams total length.</exception>
public byte[] UnFilter(byte[] filterStream, int offset, int length, int width)
{
// the 'B' and 'C' values of the first row are considered to be 0.
// the 'A' value of the first column is considered to be 0.
if (filterStream.Length - offset < length)
{
throw new PngInsuficientLengthException(length, filterStream.Length, offset);
}
int numrows = length / width;
// The output also consists of a byte before each line that specifies the Paeth prediction filter is being used
byte[] result = new byte[length - numrows];
int source = offset;
int dest = 0;
for (int row = 0; row < numrows; row++)
{
if (filterStream[source] == 0)
{
source++;
// No filtering
Array.Copy(filterStream, source, result, dest, width);
source += width;
dest += width;
}
else if (filterStream[source] == 1)
{
source++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : result[dest - 1];
result[dest] = (byte)((filterStream[dest] + a) % 256);
source++;
dest++;
}
}
else if (filterStream[source] == 2)
{
source++;
for (int col = 0; col < width; col++)
{
byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1];
result[dest] = (byte)((filterStream[dest] + b) % 256);
source++;
dest++;
}
}
else if (filterStream[source] == 3)
{
source++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : result[dest - 1];
byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1];
result[dest] = (byte)((filterStream[dest] + ((a + b) / 2)) % 256); // integer division automatically does "floor"
source++;
dest++;
}
}
else if (filterStream[source] == 4)
{
source++;
for (int col = 0; col < width; col++)
{
byte a = (col == 0) ? (byte)0 : result[dest - 1];
byte b = (row == 0 || col == 0) ? (byte)0 : result[dest - width - 1];
byte c = (row == 0) ? (byte)0 : result[dest - width];
result[dest] = (byte)((filterStream[dest] + PaethPredictor(a, b, c)) % 256);
source++;
dest++;
}
}
}
return result;
}
/// <summary>
/// For testing, see if we can write a png ourself that can be opened by .Net png.
/// </summary>
/// <param name="image">The image to write to png format.</param>
/// <param name="fileName">The string fileName.</param>
public void Write(Bitmap image, string fileName)
{
if (File.Exists(fileName)) File.Delete(fileName);
Stream f = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1000000);
WriteSignature(f);
PngHeader header = new PngHeader(image.Width, image.Height);
header.Write(f);
WriteSrgb(f);
byte[] refImage = GetBytesFromImage(image);
byte[] filtered = Filter(refImage, 0, refImage.Length, image.Width * 4);
byte[] compressed = Deflate.Compress(filtered);
WriteIDat(f, compressed);
WriteEnd(f);
f.Flush();
f.Close();
}
private static byte[] GetBytesFromImage(Bitmap image)
{
BitmapData bd = image.LockBits(new Rectangle(0, 0, image.Width, image.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb);
int len = image.Width * image.Height * 4;
byte[] refImage = new byte[len];
Marshal.Copy(bd.Scan0, refImage, 0, len);
image.UnlockBits(bd);
return refImage;
}
/// <summary>
/// B C - For the current pixel X, use the best fit from B, C or A to predict X.
/// A X.
/// </summary>
/// <param name="a">The a.</param>
/// <param name="b">The b.</param>
/// <param name="c">The c.</param>
/// <returns>The predicted value.</returns>
private static byte PaethPredictor(byte a, byte b, byte c)
{
byte pR;
int p = a + b - c;
int pa = Math.Abs(p - a);
int pb = Math.Abs(p - b);
int pc = Math.Abs(p - c);
if (pa <= pb && pa <= pc) pR = a;
else if (pb <= pc) pR = b;
else pR = c;
return pR;
}
private static void WriteEnd(Stream f)
{
f.Write(BitConverter.GetBytes(0), 0, 4);
byte[] vals = new byte[] { 73, 69, 78, 68 }; // IEND
f.Write(vals, 0, 4);
f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(vals)), 0, 4);
}
private static void WriteIDat(Stream f, byte[] data)
{
f.Write(ToBytesAsUInt32((uint)data.Length), 0, 4);
byte[] tag = { 73, 68, 65, 84 };
f.Write(tag, 0, 4); // IDAT
f.Write(data, 0, data.Length);
byte[] combined = new byte[data.Length + 4];
Array.Copy(tag, 0, combined, 0, 4);
Array.Copy(data, 0, combined, 4, data.Length);
f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(combined)), 0, 4);
}
private static void WriteSignature(Stream f)
{
f.Write(new byte[] { 137, 80, 78, 71, 13, 10, 26, 10 }, 0, 8);
}
private static void WriteSrgb(Stream f)
{
f.Write(ToBytesAsUInt32(1), 0, 4);
byte[] vals = { 115, 82, 71, 66, 0 }; // sRGB and the value of 0
f.Write(vals, 0, 5);
f.Write(ToBytesAsUInt32(Crc32.ComputeChecksum(vals)), 0, 4);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class TypeTests : CSharpTestBase
{
[Fact]
public void Bug18280()
{
string brackets = "[][][][][][][][][][][][][][][][][][][][]";
brackets += brackets; // 40
brackets += brackets; // 80
brackets += brackets; // 160
brackets += brackets; // 320
brackets += brackets; // 640
brackets += brackets; // 1280
brackets += brackets; // 2560
brackets += brackets; // 5120
brackets += brackets; // 10240
string code = "class C { int " + brackets + @" x; }";
var compilation = CreateCompilationWithMscorlib(code);
var c = compilation.GlobalNamespace.GetTypeMembers("C")[0];
var x = c.GetMembers("x").Single() as FieldSymbol;
var arr = x.Type;
arr.GetHashCode();
}
[Fact]
public void AlphaRenaming()
{
var code = @"
class A1 : A<int> {}
class A2 : A<int> {}
class A<T> {
class B<U> {
A<A<U>> X;
}
}
";
var compilation = CreateCompilationWithMscorlib(code);
var aint1 = compilation.GlobalNamespace.GetTypeMembers("A1")[0].BaseType; // A<int>
var aint2 = compilation.GlobalNamespace.GetTypeMembers("A2")[0].BaseType; // A<int>
var b1 = aint1.GetTypeMembers("B", 1).Single(); // A<int>.B<U>
var b2 = aint2.GetTypeMembers("B", 1).Single(); // A<int>.B<U>
Assert.NotSame(b1.TypeParameters[0], b2.TypeParameters[0]); // they've been alpha renamed independently
Assert.Equal(b1.TypeParameters[0], b2.TypeParameters[0]); // but happen to be the same type
var xtype1 = (b1.GetMembers("X")[0] as FieldSymbol).Type; // Types using them are the same too
var xtype2 = (b2.GetMembers("X")[0] as FieldSymbol).Type;
Assert.Equal(xtype1, xtype2);
}
[Fact]
public void Access1()
{
var text =
@"
class A {
}
struct S {
}
interface B {
}
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
var b = global.GetTypeMembers("B", 0).Single();
var s = global.GetTypeMembers("S").Single();
Assert.Equal(Accessibility.Internal, a.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, b.DeclaredAccessibility);
Assert.Equal(Accessibility.Internal, s.DeclaredAccessibility);
}
[Fact]
public void InheritedTypesCrossTrees()
{
var text = @"namespace MT {
public interface IFoo { void Foo(); }
public interface IFoo<T, R> { R Foo(T t); }
}
";
var text1 = @"namespace MT {
public interface IBar<T> : IFoo { void Bar(T t); }
}
";
var text2 = @"namespace NS {
using System;
using MT;
public class A<T> : IFoo<T, string>, IBar<string> {
void IFoo.Foo() { }
void IBar<string>.Bar(string s) { }
public string Foo(T t) { return null; }
}
public class B : A<int> {}
}
";
var text3 = @"namespace NS {
public class C : B {}
}
";
var comp = CreateCompilationWithMscorlib(new[] { text, text1, text2, text3 });
var global = comp.GlobalNamespace;
var ns = global.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("C", 0).SingleOrDefault() as NamedTypeSymbol;
Assert.Equal(0, type1.Interfaces.Length);
Assert.Equal(3, type1.AllInterfaces.Length);
var sorted = (from i in type1.AllInterfaces
orderby i.Name
select i).ToArray();
var i1 = sorted[0] as NamedTypeSymbol;
var i2 = sorted[1] as NamedTypeSymbol;
var i3 = sorted[2] as NamedTypeSymbol;
Assert.Equal("MT.IBar<System.String>", i1.ToTestDisplayString());
Assert.Equal(1, i1.Arity);
Assert.Equal("MT.IFoo<System.Int32, System.String>", i2.ToTestDisplayString());
Assert.Equal(2, i2.Arity);
Assert.Equal("MT.IFoo", i3.ToTestDisplayString());
Assert.Equal(0, i3.Arity);
Assert.Equal("B", type1.BaseType.Name);
// B
var type2 = type1.BaseType as NamedTypeSymbol;
Assert.Equal(3, type2.AllInterfaces.Length);
Assert.NotNull(type2.BaseType);
// A<int>
var type3 = type2.BaseType as NamedTypeSymbol;
Assert.Equal("NS.A<System.Int32>", type3.ToTestDisplayString());
Assert.Equal(2, type3.Interfaces.Length);
Assert.Equal(3, type3.AllInterfaces.Length);
var type33 = ns.GetTypeMembers("A", 1).SingleOrDefault() as NamedTypeSymbol;
Assert.Equal("NS.A<T>", type33.ToTestDisplayString());
Assert.Equal(2, type33.Interfaces.Length);
Assert.Equal(3, type33.AllInterfaces.Length);
}
[WorkItem(537752, "DevDiv")]
[Fact]
public void InheritedTypesCrossComps()
{
var text = @"namespace MT {
public interface IFoo { void Foo(); }
public interface IFoo<T, R> { R Foo(T t); }
public interface IEmpty { }
}
";
var text1 = @"namespace MT {
public interface IBar<T> : IFoo, IEmpty { void Bar(T t); }
}
";
var text2 = @"namespace NS {
using MT;
public class A<T> : IFoo<T, string>, IBar<T>, IFoo {
void IFoo.Foo() { }
public string Foo(T t) { return null; }
void IBar<T>.Bar(T t) { }
}
public class B : A<ulong> {}
}
";
var text3 = @"namespace NS {
public class C : B {}
}
";
var comp1 = CreateCompilationWithMscorlib(text);
var compRef1 = new CSharpCompilationReference(comp1);
var comp2 = CreateCompilationWithMscorlib(new string[] { text1, text2 }, assemblyName: "Test1",
references: new List<MetadataReference> { compRef1 });
var compRef2 = new CSharpCompilationReference(comp2);
var comp = CreateCompilationWithMscorlib(text3, assemblyName: "Test2",
references: new List<MetadataReference> { compRef2, compRef1 });
Assert.Equal(0, comp1.GetDiagnostics().Count());
Assert.Equal(0, comp2.GetDiagnostics().Count());
Assert.Equal(0, comp.GetDiagnostics().Count());
var global = comp.GlobalNamespace;
var ns = global.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("C", 0).SingleOrDefault() as NamedTypeSymbol;
Assert.Equal(0, type1.Interfaces.Length);
//
Assert.Equal(4, type1.AllInterfaces.Length);
var sorted = (from i in type1.AllInterfaces
orderby i.Name
select i).ToArray();
var i1 = sorted[0] as NamedTypeSymbol;
var i2 = sorted[1] as NamedTypeSymbol;
var i3 = sorted[2] as NamedTypeSymbol;
var i4 = sorted[3] as NamedTypeSymbol;
Assert.Equal("MT.IBar<System.UInt64>", i1.ToTestDisplayString());
Assert.Equal(1, i1.Arity);
Assert.Equal("MT.IEmpty", i2.ToTestDisplayString());
Assert.Equal(0, i2.Arity);
Assert.Equal("MT.IFoo<System.UInt64, System.String>", i3.ToTestDisplayString());
Assert.Equal(2, i3.Arity);
Assert.Equal("MT.IFoo", i4.ToTestDisplayString());
Assert.Equal(0, i4.Arity);
Assert.Equal("B", type1.BaseType.Name);
// B
var type2 = type1.BaseType as NamedTypeSymbol;
//
Assert.Equal(4, type2.AllInterfaces.Length);
Assert.NotNull(type2.BaseType);
// A<ulong>
var type3 = type2.BaseType as NamedTypeSymbol;
// T1?
Assert.Equal("NS.A<System.UInt64>", type3.ToTestDisplayString());
Assert.Equal(3, type3.Interfaces.Length);
Assert.Equal(4, type3.AllInterfaces.Length);
var type33 = ns.GetTypeMembers("A", 1).SingleOrDefault() as NamedTypeSymbol;
Assert.Equal("NS.A<T>", type33.ToTestDisplayString());
Assert.Equal(3, type33.Interfaces.Length);
Assert.Equal(4, type33.AllInterfaces.Length);
}
[WorkItem(537746, "DevDiv")]
[Fact]
public void NestedTypes()
{
var text = @"namespace NS
using System;
public class Test
{
private void M() {}
internal class NestedClass {
internal protected interface INestedFoo {}
}
struct NestedStruct {}
}
public class Test<T>
{
T M() { return default(T); }
public struct NestedS<V, V1> {
class NestedC<R> {}
}
interface INestedFoo<T1, T2, T3> {}
}
}
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.GlobalNamespace;
var ns = global.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("Test", 0).SingleOrDefault() as NamedTypeSymbol;
Assert.Equal(2, type1.GetTypeMembers().Length);
var type2 = type1.GetTypeMembers("NestedClass").Single() as NamedTypeSymbol;
var type3 = type1.GetTypeMembers("NestedStruct").SingleOrDefault() as NamedTypeSymbol;
Assert.Equal(type1, type2.ContainingSymbol);
Assert.Equal(Accessibility.Internal, type2.DeclaredAccessibility);
Assert.Equal(TypeKind.Struct, type3.TypeKind);
// Bug
Assert.Equal(Accessibility.Private, type3.DeclaredAccessibility);
var type4 = type2.GetTypeMembers().First() as NamedTypeSymbol;
Assert.Equal(type2, type4.ContainingSymbol);
Assert.Equal(Accessibility.ProtectedOrInternal, type4.DeclaredAccessibility);
Assert.Equal(TypeKind.Interface, type4.TypeKind);
// Generic
type1 = ns.GetTypeMembers("Test", 1).SingleOrDefault() as NamedTypeSymbol;
Assert.Equal(2, type1.GetTypeMembers().Length);
type2 = type1.GetTypeMembers("NestedS", 2).Single() as NamedTypeSymbol;
type3 = type1.GetTypeMembers("INestedFoo", 3).SingleOrDefault() as NamedTypeSymbol;
Assert.Equal(type1, type2.ContainingSymbol);
Assert.Equal(Accessibility.Public, type2.DeclaredAccessibility);
Assert.Equal(TypeKind.Interface, type3.TypeKind);
// Bug
Assert.Equal(Accessibility.Private, type3.DeclaredAccessibility);
type4 = type2.GetTypeMembers().First() as NamedTypeSymbol;
Assert.Equal(type2, type4.ContainingSymbol);
// Bug
Assert.Equal(Accessibility.Private, type4.DeclaredAccessibility);
Assert.Equal(TypeKind.Class, type4.TypeKind);
}
[Fact]
public void PartialTypeCrossTrees()
{
var text = @"
namespace MT {
using System.Collections.Generic;
public partial interface IFoo<T> { void Foo(); }
}
";
var text1 = @"
namespace MT {
using System.Collections.Generic;
public partial interface IFoo<T> { T Foo(T t); }
}
namespace NS {
using System;
using MT;
public partial class A<T> : IFoo<T>
{
void IFoo<T>.Foo() { }
}
}
";
var text2 = @"
namespace NS {
using MT;
public partial class A<T> : IFoo<T>
{
public T Foo(T t) { return default(T); }
}
}
";
var comp = CreateCompilationWithMscorlib(new[] { text, text1, text2 });
var global = comp.GlobalNamespace;
var ns = global.GetMembers("NS").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("A", 1).SingleOrDefault() as NamedTypeSymbol;
// 2 Methods + Ctor
Assert.Equal(3, type1.GetMembers().Length);
Assert.Equal(1, type1.Interfaces.Length);
Assert.Equal(2, type1.Locations.Length);
var i1 = type1.Interfaces[0] as NamedTypeSymbol;
Assert.Equal("MT.IFoo<T>", i1.ToTestDisplayString());
Assert.Equal(2, i1.GetMembers().Length);
Assert.Equal(2, i1.Locations.Length);
}
[WorkItem(537752, "DevDiv")]
[Fact]
public void TypeCrossComps()
{
#region "Interface Impl"
var text = @"
public interface IFoo {
void M0();
}
";
var text1 = @"
public class Foo : IFoo {
public void M0() {}
}
";
var comp1 = CreateCompilationWithMscorlib(text);
var compRef1 = new CSharpCompilationReference(comp1);
var comp = CreateCompilationWithMscorlib(text1, references: new List<MetadataReference> { compRef1 }, assemblyName: "Comp2");
Assert.Equal(0, comp.GetDiagnostics().Count());
#endregion
#region "Interface Inherit"
text = @"
public interface IFoo {
void M0();
}
";
text1 = @"
public interface IBar : IFoo {
void M1();
}
";
comp1 = CreateCompilationWithMscorlib(text);
compRef1 = new CSharpCompilationReference(comp1);
comp = CreateCompilationWithMscorlib(text1, references: new List<MetadataReference> { compRef1 }, assemblyName: "Comp2");
Assert.Equal(0, comp.GetDiagnostics().Count());
#endregion
#region "Class Inherit"
text = @"
public class A {
void M0() {}
}
";
text1 = @"
public class B : A {
void M1() {}
}
";
comp1 = CreateCompilationWithMscorlib(text);
compRef1 = new CSharpCompilationReference(comp1);
comp = CreateCompilationWithMscorlib(text1, references: new List<MetadataReference> { compRef1 }, assemblyName: "Comp2");
Assert.Equal(0, comp.GetDiagnostics().Count());
#endregion
#region "Partial"
text = @"
public partial interface IBar {
void M0();
}
public partial class A { }
";
text1 = @"
public partial interface IBar {
void M1();
}
public partial class A { }
";
comp1 = CreateCompilationWithMscorlib(text);
compRef1 = new CSharpCompilationReference(comp1);
comp = CreateCompilationWithMscorlib(text1, references: new List<MetadataReference> { compRef1 }, assemblyName: "Comp2");
Assert.Equal(0, comp.GetDiagnostics().Count());
#endregion
}
[Fact, WorkItem(537233, "DevDiv"), WorkItem(537313, "DevDiv")]
public void ArrayTypes()
{
var text =
@"public class Test
{
static int[,] intAryField;
internal ulong[][,] ulongAryField;
public string[,][] MethodWithArray(
ref Test[, ,] refArray,
out object[][][] outArray,
params byte[] varArray)
{
outArray = null; return null;
}
}";
var comp = CreateCompilationWithMscorlib(text);
var classTest = comp.GlobalNamespace.GetTypeMembers("Test", 0).Single();
var field1 = classTest.GetMembers("intAryField").Single();
Assert.Equal(classTest, field1.ContainingSymbol);
Assert.Equal(SymbolKind.Field, field1.Kind);
Assert.True(field1.IsDefinition);
Assert.True(field1.IsStatic);
var elemType1 = (field1 as FieldSymbol).Type;
Assert.Equal(TypeKind.Array, elemType1.TypeKind);
Assert.Equal("System.Int32[,]", elemType1.ToTestDisplayString());
// ArrayType public API
Assert.False(elemType1.IsStatic);
Assert.False(elemType1.IsAbstract);
Assert.False(elemType1.IsSealed);
Assert.Equal(Accessibility.NotApplicable, elemType1.DeclaredAccessibility);
field1 = classTest.GetMembers("ulongAryField").Single();
Assert.Equal(classTest, field1.ContainingSymbol);
Assert.Equal(SymbolKind.Field, field1.Kind);
Assert.True(field1.IsDefinition);
var elemType2 = (field1 as FieldSymbol).Type;
Assert.Equal(TypeKind.Array, elemType2.TypeKind);
// bug 2034
Assert.Equal("System.UInt64[][,]", elemType2.ToTestDisplayString());
Assert.Equal("Array", elemType2.BaseType.Name);
var method = classTest.GetMembers("MethodWithArray").Single() as MethodSymbol;
Assert.Equal(classTest, method.ContainingSymbol);
Assert.Equal(SymbolKind.Method, method.Kind);
Assert.True(method.IsDefinition);
var retType = (method as MethodSymbol).ReturnType;
Assert.Equal(TypeKind.Array, retType.TypeKind);
// ArrayType public API
Assert.Equal(0, retType.GetAttributes().Length); // Enumerable.Empty<SymbolAttribute>()
Assert.Equal(0, retType.GetMembers().Length); // Enumerable.Empty<Symbol>()
Assert.Equal(0, retType.GetMembers(string.Empty).Length);
Assert.Equal(0, retType.GetTypeMembers().Length); // Enumerable.Empty<NamedTypeSymbol>()
Assert.Equal(0, retType.GetTypeMembers(string.Empty).Length);
Assert.Equal(0, retType.GetTypeMembers(string.Empty, 0).Length);
// bug 2034
Assert.Equal("System.String[,][]", retType.ToTestDisplayString());
var paramList = (method as MethodSymbol).Parameters;
var p1 = method.Parameters[0];
var p2 = method.Parameters[1];
var p3 = method.Parameters[2];
Assert.Equal(RefKind.Ref, p1.RefKind);
Assert.Equal("ref Test[,,] refArray", p1.ToTestDisplayString());
Assert.Equal(RefKind.Out, p2.RefKind);
Assert.Equal("out System.Object[][][] outArray", p2.ToTestDisplayString());
Assert.Equal(RefKind.None, p3.RefKind);
Assert.Equal(TypeKind.Array, p3.Type.TypeKind);
Assert.Equal("params System.Byte[] varArray", p3.ToTestDisplayString());
}
// Interfaces impl-ed by System.Array
// .Net 2/3.0 (7) IList&[T] -> ICollection&[T] ->IEnumerable&[T]; ICloneable;
// .Net 4.0 (9) IList&[T] -> ICollection&[T] ->IEnumerable&[T]; ICloneable; IStructuralComparable; IStructuralEquatable
// Array T[] impl IList[T] only
[Fact, WorkItem(537300, "DevDiv"), WorkItem(527247, "DevDiv")]
public void ArrayTypeInterfaces()
{
var text = @"
public class A {
static byte[][] AryField;
static byte[,] AryField2;
}
";
var compilation = CreateCompilationWithMscorlib(text);
int[] ary = new int[2];
var globalNS = compilation.SourceModule.GlobalNamespace;
var classTest = globalNS.GetTypeMembers("A").Single() as NamedTypeSymbol;
var sym1 = (classTest.GetMembers("AryField").First() as FieldSymbol).Type;
Assert.Equal(SymbolKind.ArrayType, sym1.Kind);
//
Assert.Equal(1, sym1.Interfaces.Length);
Assert.Equal("IList", sym1.Interfaces.First().Name);
Assert.Equal(9, sym1.AllInterfaces.Length);
// ? Don't seem sort right
var sorted = sym1.AllInterfaces.OrderBy(i => i.Name).ToArray();
var i1 = sorted[0] as NamedTypeSymbol;
var i2 = sorted[1] as NamedTypeSymbol;
var i3 = sorted[2] as NamedTypeSymbol;
var i4 = sorted[3] as NamedTypeSymbol;
var i5 = sorted[4] as NamedTypeSymbol;
var i6 = sorted[5] as NamedTypeSymbol;
var i7 = sorted[6] as NamedTypeSymbol;
var i8 = sorted[7] as NamedTypeSymbol;
var i9 = sorted[8] as NamedTypeSymbol;
Assert.Equal("System.ICloneable", i1.ToTestDisplayString());
Assert.Equal("System.Collections.ICollection", i2.ToTestDisplayString());
Assert.Equal("System.Collections.Generic.ICollection<System.Byte[]>", i3.ToTestDisplayString());
Assert.Equal("System.Collections.Generic.IEnumerable<System.Byte[]>", i4.ToTestDisplayString());
Assert.Equal("System.Collections.IEnumerable", i5.ToTestDisplayString());
Assert.Equal("System.Collections.IList", i6.ToTestDisplayString());
Assert.Equal("System.Collections.Generic.IList<System.Byte[]>", i7.ToTestDisplayString());
Assert.Equal("System.Collections.IStructuralComparable", i8.ToTestDisplayString());
Assert.Equal("System.Collections.IStructuralEquatable", i9.ToTestDisplayString());
var sym2 = (classTest.GetMembers("AryField2").First() as FieldSymbol).Type;
Assert.Equal(SymbolKind.ArrayType, sym2.Kind);
Assert.Equal(0, sym2.Interfaces.Length);
}
[Fact]
public void ArrayTypeGetHashCode()
{
var text = @"public class A {
public uint[] AryField1;
static string[][] AryField2;
private sbyte[,,] AryField3;
A(){}
";
var compilation = CreateCompilationWithMscorlib(text);
var globalNS = compilation.SourceModule.GlobalNamespace;
var classTest = globalNS.GetTypeMembers("A").Single() as NamedTypeSymbol;
var sym1 = (classTest.GetMembers().First() as FieldSymbol).Type;
Assert.Equal(SymbolKind.ArrayType, sym1.Kind);
var v1 = sym1.GetHashCode();
var v2 = sym1.GetHashCode();
Assert.Equal(v1, v2);
var sym2 = (classTest.GetMembers("AryField2").First() as FieldSymbol).Type;
Assert.Equal(SymbolKind.ArrayType, sym2.Kind);
v1 = sym2.GetHashCode();
v2 = sym2.GetHashCode();
Assert.Equal(v1, v2);
var sym3 = (classTest.GetMembers("AryField3").First() as FieldSymbol).Type;
Assert.Equal(SymbolKind.ArrayType, sym3.Kind);
v1 = sym3.GetHashCode();
v2 = sym3.GetHashCode();
Assert.Equal(v1, v2);
}
[Fact, WorkItem(527114, "DevDiv")]
public void DynamicType()
{
var text =
@"class A
{
object field1;
dynamic field2;
}";
var global = CreateCompilationWithMscorlib(text).GlobalNamespace;
var a = global.GetTypeMembers("A", 0).Single();
foreach (var m in a.GetMembers())
{
if (m.Name == "field1")
{
var f1 = (m as FieldSymbol).Type;
Assert.False(f1 is ErrorTypeSymbol, f1.GetType().ToString() + " : " + f1.ToTestDisplayString());
}
else if (m.Name == "field2")
{
Assert.Equal(SymbolKind.Field, m.Kind);
// dynamic is NOT implemented
// var f2 = (m as FieldSymbol).Type;
// Assert.False(f2 is ErrorTypeSymbol); // failed
}
}
var obj = a.GetMembers("field1").Single();
Assert.Equal(a, obj.ContainingSymbol);
Assert.Equal(SymbolKind.Field, obj.Kind);
Assert.True(obj.IsDefinition);
var objType = (obj as FieldSymbol).Type;
Assert.False(objType is ErrorTypeSymbol, objType.GetType().ToString() + " : " + objType.ToTestDisplayString());
Assert.NotEqual(SymbolKind.ErrorType, objType.Kind);
var dyn = a.GetMembers("field2").Single();
Assert.Equal(a, dyn.ContainingSymbol);
Assert.Equal(SymbolKind.Field, dyn.Kind);
Assert.True(dyn.IsDefinition);
var dynType = (obj as FieldSymbol).Type;
Assert.False(dynType is ErrorTypeSymbol, dynType.GetType().ToString() + " : " + dynType.ToTestDisplayString()); // this is ok
Assert.NotEqual(SymbolKind.ErrorType, dynType.Kind);
}
[WorkItem(537187, "DevDiv")]
[Fact]
public void EnumFields()
{
var text =
@"public enum MyEnum
{
One,
Two = 2,
Three,
}
";
var comp = CreateCompilationWithMscorlib(text);
var v = comp.GlobalNamespace.GetTypeMembers("MyEnum", 0).Single();
Assert.NotEqual(null, v);
Assert.Equal(Accessibility.Public, v.DeclaredAccessibility);
var fields = v.GetMembers().OfType<FieldSymbol>().ToList();
Assert.Equal(3, fields.Count);
CheckField(fields[0], "One", isStatic: true);
CheckField(fields[1], "Two", isStatic: true);
CheckField(fields[2], "Three", isStatic: true);
}
private void CheckField(Symbol symbol, string name, bool isStatic)
{
Assert.Equal(SymbolKind.Field, symbol.Kind);
Assert.Equal(name, symbol.Name);
Assert.Equal(isStatic, symbol.IsStatic);
}
[WorkItem(542479, "DevDiv")]
[WorkItem(538320, "DevDiv")]
[Fact] // TODO: Dev10 does not report ERR_SameFullNameAggAgg here - source wins.
public void SourceAndMetadata_SpecialType()
{
var text = @"
using System;
namespace System
{
public struct Void
{
static void Main()
{
System.Void.Equals(1, 1);
}
}
}
";
var compilation = CreateCompilationWithMscorlib(text);
compilation.VerifyDiagnostics(
// (10,13): warning CS0436: The type 'System.Void' in '' conflicts with the imported type 'void' in 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// System.Void.Equals(1, 1);
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "System.Void").WithArguments("", "System.Void", "mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "void"),
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
}
[WorkItem(542479, "DevDiv")]
[WorkItem(538320, "DevDiv")]
[Fact] // TODO: Dev10 does not report ERR_SameFullNameAggAgg here - source wins.
public void SourceAndMetadata_NonSpecialType()
{
var refSource = @"
namespace N
{
public class C {}
}";
var csharp = @"
using System;
namespace N
{
public struct C
{
static void Main()
{
N.C.Equals(1, 1);
}
}
}
";
var refAsm = CreateCompilationWithMscorlib(refSource, assemblyName: "RefAsm").ToMetadataReference();
var compilation = CreateCompilationWithMscorlib(csharp, references: new[] { refAsm });
compilation.VerifyDiagnostics(
// (10,13): warning CS0436: The type 'N.C' in '' conflicts with the imported type 'N.C' in 'RefAsm, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. Using the type defined in ''.
// N.C.Equals(1, 1);
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "N.C").WithArguments("", "N.C", "RefAsm, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "N.C"),
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
}
[WorkItem(542479, "DevDiv")]
[Fact]
public void DuplicateType()
{
string referenceText = @"
namespace N
{
public class C { }
}
";
var compilation1 = CreateCompilationWithMscorlib(referenceText, assemblyName: "A");
compilation1.VerifyDiagnostics();
var compilation2 = CreateCompilationWithMscorlib(referenceText, assemblyName: "B");
compilation2.VerifyDiagnostics();
var testText = @"
namespace M
{
public struct Test
{
static void Main()
{
N.C.ToString();
}
}
}";
var compilation3 = CreateCompilationWithMscorlib(testText, new[] { new CSharpCompilationReference(compilation1), new CSharpCompilationReference(compilation2) });
compilation3.VerifyDiagnostics(
// (8,13): error CS0433: The type 'N.C' exists in both 'A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' and 'B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
// N.C.ToString();
Diagnostic(ErrorCode.ERR_SameFullNameAggAgg, "N.C").WithArguments("A, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", "N.C", "B, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null"));
}
[Fact]
public void SimpleGeneric()
{
var text =
@"namespace NS
{
public interface IFoo<T> {}
internal class A<V, U> {}
public struct S<X, Y, Z> {}
}";
var comp = CreateCompilationWithMscorlib(text);
var namespaceNS = comp.GlobalNamespace.GetMembers("NS").First() as NamespaceOrTypeSymbol;
Assert.Equal(3, namespaceNS.GetMembers().Length);
var ifoo = namespaceNS.GetTypeMembers("IFoo").First();
Assert.Equal(namespaceNS, ifoo.ContainingSymbol);
Assert.Equal(SymbolKind.NamedType, ifoo.Kind);
Assert.Equal(TypeKind.Interface, ifoo.TypeKind);
Assert.Equal(Accessibility.Public, ifoo.DeclaredAccessibility);
Assert.Equal(1, ifoo.TypeParameters.Length);
Assert.Equal("T", ifoo.TypeParameters[0].Name);
Assert.Equal(1, ifoo.TypeArguments.Length);
// Bug#932083 - Not impl
// Assert.False(ifoo.TypeParameters[0].IsReferenceType);
// Assert.False(ifoo.TypeParameters[0].IsValueType);
var classA = namespaceNS.GetTypeMembers("A").First();
Assert.Equal(namespaceNS, classA.ContainingSymbol);
Assert.Equal(SymbolKind.NamedType, classA.Kind);
Assert.Equal(TypeKind.Class, classA.TypeKind);
Assert.Equal(Accessibility.Internal, classA.DeclaredAccessibility);
Assert.Equal(2, classA.TypeParameters.Length);
Assert.Equal("V", classA.TypeParameters[0].Name);
Assert.Equal("U", classA.TypeParameters[1].Name);
// same as type parameter
Assert.Equal(2, classA.TypeArguments.Length);
var structS = namespaceNS.GetTypeMembers("S").First();
Assert.Equal(namespaceNS, structS.ContainingSymbol);
Assert.Equal(SymbolKind.NamedType, structS.Kind);
Assert.Equal(TypeKind.Struct, structS.TypeKind);
Assert.Equal(Accessibility.Public, structS.DeclaredAccessibility);
Assert.Equal(3, structS.TypeParameters.Length);
Assert.Equal("X", structS.TypeParameters[0].Name);
Assert.Equal("Y", structS.TypeParameters[1].Name);
Assert.Equal("Z", structS.TypeParameters[2].Name);
Assert.Equal(3, structS.TypeArguments.Length);
}
[WorkItem(537199, "DevDiv")]
[Fact]
public void UseTypeInNetModule()
{
var module1Ref = ModuleMetadata.CreateFromImage(TestResources.SymbolsTests.netModule.netModule1).GetReference(display: "netModule1.netmodule");
var text = @"class Test
{
Class1 a = null;
}";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var comp = CreateCompilationWithMscorlib(text, references: new[] { module1Ref });
var globalNS = comp.SourceModule.GlobalNamespace;
var classTest = globalNS.GetTypeMembers("Test").First();
var varA = classTest.GetMembers("a").First() as FieldSymbol;
Assert.Equal(SymbolKind.Field, varA.Kind);
Assert.Equal(TypeKind.Class, varA.Type.TypeKind);
Assert.Equal(SymbolKind.NamedType, varA.Type.Kind);
}
[WorkItem(537344, "DevDiv")]
[Fact]
public void ClassNameWithPrecedingAtChar()
{
var text =
@"using System;
static class @main
{
public static void @Main() {}
}
";
var comp = CreateCompilation(text);
var typeSym = comp.Assembly.GlobalNamespace.GetTypeMembers().First();
Assert.Equal("main", typeSym.ToTestDisplayString());
var memSym = typeSym.GetMembers("Main").First();
Assert.Equal("void main.Main()", memSym.ToTestDisplayString());
}
[Fact]
public void ReturnsVoidWithoutCorlib()
{
// ensure a return type of "void" remains so even when corlib is unavailable.
string code = @"
class Test
{
void Main()
{
}
}";
var comp = CreateCompilation(code);
NamedTypeSymbol testTypeSymbol = comp.Assembly.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
MethodSymbol methodSymbol = testTypeSymbol.GetMembers("Main").Single() as MethodSymbol;
Assert.Equal("void Test.Main()", methodSymbol.ToTestDisplayString());
}
[WorkItem(537437, "DevDiv")]
[Fact]
public void ClassWithMultipleConstr()
{
var text =
@"public class MyClass
{
public MyClass()
{
}
public MyClass(int DummyInt)
{
}
}
";
var comp = CreateCompilationWithMscorlib(text);
var typeSym = comp.Assembly.GlobalNamespace.GetTypeMembers("MyClass").First();
var actual = string.Join(", ", typeSym.GetMembers().Select(symbol => symbol.ToTestDisplayString()).OrderBy(name => name));
Assert.Equal("MyClass..ctor(), MyClass..ctor(System.Int32 DummyInt)", actual);
}
[WorkItem(537446, "DevDiv")]
[Fact]
public void BaseTypeNotDefinedInSrc()
{
string code = @"
public class MyClass : T1
{
}";
var comp = CreateCompilation(code);
NamedTypeSymbol testTypeSymbol = comp.Assembly.GlobalNamespace.GetTypeMembers("MyClass").Single() as NamedTypeSymbol;
Assert.Equal("T1", testTypeSymbol.BaseType.ToTestDisplayString());
}
[WorkItem(537447, "DevDiv")]
[Fact]
public void IllegalTypeArgumentInBaseType()
{
string code = @"
public class GC1<T> {}
public class X : GC1<BOGUS> {}
";
var comp = CreateCompilation(code);
NamedTypeSymbol testTypeSymbol = comp.Assembly.GlobalNamespace.GetTypeMembers("X").Single() as NamedTypeSymbol;
Assert.Equal("GC1<BOGUS>", testTypeSymbol.BaseType.ToTestDisplayString());
}
[WorkItem(537449, "DevDiv")]
[Fact]
public void MethodInDerivedGenericClassWithParamOfIllegalGenericType()
{
var text =
@"public class BaseT<T> : GenericClass {}
public class SubGenericClass<T> : BaseT<T>
{
public void Meth3(GC1<T> t)
{
}
public void Meth4(System.NonexistentType t)
{
}
}
";
var comp = CreateCompilationWithMscorlib(text);
var typeSym = comp.Assembly.GlobalNamespace.GetTypeMembers("SubGenericClass").First();
var actualSymbols = typeSym.GetMembers();
var actual = string.Join(", ", actualSymbols.Select(symbol => symbol.ToTestDisplayString()).OrderBy(name => name));
Assert.Equal("SubGenericClass<T>..ctor(), void SubGenericClass<T>.Meth3(GC1<T> t), void SubGenericClass<T>.Meth4(System.NonexistentType t)", actual);
}
[WorkItem(537449, "DevDiv")]
[Fact]
public void TestAllInterfaces()
{
var text =
@"
interface I1 {}
interface I2 : I1 {}
interface I3 : I1, I2 {}
interface I4 : I2, I3 {}
interface I5 : I3, I4 {}
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.GlobalNamespace;
var interfaces = global.GetTypeMembers("I5", 0).Single().AllInterfaces;
Assert.Equal(4, interfaces.Length);
Assert.Equal(global.GetTypeMembers("I4", 0).Single(), interfaces[0]);
Assert.Equal(global.GetTypeMembers("I3", 0).Single(), interfaces[1]);
Assert.Equal(global.GetTypeMembers("I2", 0).Single(), interfaces[2]);
Assert.Equal(global.GetTypeMembers("I1", 0).Single(), interfaces[3]);
}
[WorkItem(2750, "DevDiv_Projects/Roslyn")]
[Fact]
public void NamespaceSameNameAsMetadataClass()
{
var text = @"
using System;
namespace Convert
{
class Test
{
protected int M() { return 0; }
}
}
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.GlobalNamespace;
var ns = global.GetMembers("Convert").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var mems = type1.GetMembers();
}
[WorkItem(537685, "DevDiv")]
[Fact]
public void NamespaceMemberArity()
{
var text = @"
namespace NS1.NS2
{
internal class A<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11> {}
internal proteced class B<T1,T2,T3,T4,T5,T6,T7,T8,T9,T10, T11, T12> {}
}
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.GlobalNamespace;
var ns1 = global.GetMembers("NS1").Single() as NamespaceSymbol;
var ns2 = ns1.GetMembers("NS2").Single() as NamespaceSymbol;
var mems = ns2.GetMembers();
var x = mems.Length;
}
[WorkItem(3178, "DevDiv_Projects/Roslyn")]
[Fact]
public void NamespaceSameNameAsMetadataNamespace()
{
var text = @"
using System;
using System.Collections.Generic;
namespace Collections {
class Test<T> {
List<T> itemList = null;
}
}
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.GlobalNamespace;
var ns = global.GetMembers("Collections").Single() as NamespaceSymbol;
var type1 = ns.GetTypeMembers("Test", 1).Single() as NamedTypeSymbol;
var mems = type1.GetMembers();
}
[WorkItem(537957, "DevDiv")]
[Fact]
public void EmptyNameErrorSymbolErr()
{
var text = @"
namespace NS
{
class A { }
class B : A[] {}
}
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.GlobalNamespace;
var ns1 = global.GetMembers("NS").Single() as NamespaceSymbol;
var syma = ns1.GetMembers("A").Single() as NamedTypeSymbol;
var bt = (ns1.GetMembers("B").FirstOrDefault() as NamedTypeSymbol).BaseType;
Assert.Equal("Object", bt.Name);
}
[WorkItem(538210, "DevDiv")]
[Fact]
public void NestedTypeAccessibility01()
{
var text = @"
using System;
class A
{
public class B : A { }
}
";
var tree = Parse(text);
var comp = CreateCompilationWithMscorlib(tree);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
}
[WorkItem(538242, "DevDiv")]
[Fact]
public void PartialClassWithBaseType()
{
var text = @"
class C1 { }
partial class C2 : C1 {}
partial class C2 : C1 {}
";
var tree = Parse(text);
var comp = CreateCompilationWithMscorlib(tree);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count());
}
[WorkItem(537873, "DevDiv")]
[Fact]
public void InaccessibleTypesSkipped()
{
var text = @"
class B
{
public class A
{
public class X { }
}
}
class C : B
{
class A { } /* private */
}
class D : C
{
A.X x;
}";
var tree = Parse(text);
var comp = CreateCompilationWithMscorlib(tree);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count(diag => !ErrorFacts.IsWarning((ErrorCode)diag.Code)));
var global = comp.GlobalNamespace;
var d = global.GetMembers("D").Single() as NamedTypeSymbol;
var x = d.GetMembers("x").Single() as FieldSymbol;
Assert.Equal("B.A.X", x.Type.ToTestDisplayString());
}
[WorkItem(537970, "DevDiv")]
[Fact]
public void ImportedVersusSource()
{
var text = @"
namespace System
{
public class String { }
public class MyString : String { }
}";
var tree = Parse(text);
var comp = CreateCompilationWithMscorlib(tree);
Assert.Equal(0, comp.GetDeclarationDiagnostics().Count(e => e.Severity >= DiagnosticSeverity.Error));
var global = comp.GlobalNamespace;
var system = global.GetMembers("System").Single() as NamespaceSymbol;
var mystring = system.GetMembers("MyString").Single() as NamedTypeSymbol;
var sourceString = mystring.BaseType;
Assert.Equal(0,
sourceString.GetMembers()
.Count(m => !(m is MethodSymbol) || (m as MethodSymbol).MethodKind != MethodKind.Constructor));
}
[Fact, WorkItem(538012, "DevDiv"), WorkItem(538580, "DevDiv")]
public void ErrorTypeSymbolWithArity()
{
var text = @"
namespace N
{
public interface IFoo<T, V, U> {}
public interface IBar<T> {}
public class A : NotExist<int, int>
{
public class BB {}
public class B : BB, IFoo<string, byte>
{
}
}
public class C : IBar<char, string>
{
// NotExist is binding error, Not error symbol
public class D : IFoo<char, ulong, NotExist>
{
}
}
}
";
var comp = CreateCompilationWithMscorlib(text);
Assert.Equal(4, comp.GetDiagnostics().Count());
var global = comp.SourceModule.GlobalNamespace;
var ns = global.GetMember<NamespaceSymbol>("N");
var typeA = ns.GetMember<NamedTypeSymbol>("A");
var typeAb = typeA.BaseType;
Assert.Equal(SymbolKind.ErrorType, typeAb.Kind);
Assert.Equal(2, typeAb.Arity);
var typeB = typeA.GetMember<NamedTypeSymbol>("B");
Assert.Equal("BB", typeB.BaseType.Name);
var typeBi = typeB.Interfaces.Single();
Assert.Equal("IFoo", typeBi.Name);
Assert.Equal(SymbolKind.ErrorType, typeBi.Kind);
Assert.Equal(2, typeBi.Arity); //matches arity in source, not arity of desired symbol
var typeC = ns.GetMember<NamedTypeSymbol>("C");
Assert.Equal(SpecialType.System_Object, typeC.BaseType.SpecialType);
var typeCi = typeC.Interfaces.Single();
Assert.Equal("IBar", typeCi.Name);
Assert.Equal(SymbolKind.ErrorType, typeCi.Kind);
Assert.Equal(2, typeCi.Arity); //matches arity in source, not arity of desired symbol
var typeD = typeC.GetMember<NamedTypeSymbol>("D");
var typeDi = typeD.Interfaces.Single();
Assert.Equal("IFoo", typeDi.Name);
Assert.Equal(3, typeDi.TypeParameters.Length);
Assert.Equal(SymbolKind.ErrorType, typeDi.TypeArguments[2].Kind);
}
[Fact]
public void ErrorWithoutInterfaceGuess()
{
var text = @"
class Base<T> { }
interface Interface1<T> { }
interface Interface2<T> { }
//all one on part
partial class Derived0 : Base<int, int>, Interface1<int, int> { }
partial class Derived0 { }
//all one on part, order reversed
partial class Derived1 : Interface1<int, int>, Base<int, int> { }
partial class Derived1 { }
//interface on first part, base type on second
partial class Derived2 : Interface1<int, int> { }
partial class Derived2 : Base<int, int> { }
//base type on first part, interface on second
partial class Derived3 : Base<int, int> { }
partial class Derived3 : Interface1<int, int> { }
//interfaces on both parts
partial class Derived4 : Interface1<int, int> { }
partial class Derived4 : Interface2<int, int> { }
//interfaces on both parts, base type on first
partial class Derived5 : Base<int, int>, Interface1<int, int> { }
partial class Derived5 : Interface2<int, int> { }
//interfaces on both parts, base type on second
partial class Derived6 : Interface2<int, int> { }
partial class Derived6 : Base<int, int>, Interface1<int, int> { }
";
var comp = CreateCompilationWithMscorlib(text);
var global = comp.SourceModule.GlobalNamespace;
var baseType = global.GetMember<NamedTypeSymbol>("Base");
var interface1 = global.GetMember<NamedTypeSymbol>("Interface1");
var interface2 = global.GetMember<NamedTypeSymbol>("Interface2");
Assert.Equal(TypeKind.Class, baseType.TypeKind);
Assert.Equal(TypeKind.Interface, interface1.TypeKind);
Assert.Equal(TypeKind.Interface, interface2.TypeKind);
//we could do this with a linq query, but then we couldn't exclude specific types
var derivedTypes = new[]
{
global.GetMember<NamedTypeSymbol>("Derived0"),
global.GetMember<NamedTypeSymbol>("Derived1"),
global.GetMember<NamedTypeSymbol>("Derived2"),
global.GetMember<NamedTypeSymbol>("Derived3"),
global.GetMember<NamedTypeSymbol>("Derived4"),
global.GetMember<NamedTypeSymbol>("Derived5"),
global.GetMember<NamedTypeSymbol>("Derived6"),
};
foreach (var derived in derivedTypes)
{
if (derived.BaseType.SpecialType != SpecialType.System_Object)
{
Assert.Equal(TypeKind.Error, derived.BaseType.TypeKind);
}
foreach (var i in derived.Interfaces)
{
Assert.Equal(TypeKind.Error, i.TypeKind);
}
}
Assert.Same(baseType, ExtractErrorGuess(derivedTypes[0].BaseType));
Assert.Same(interface1, ExtractErrorGuess(derivedTypes[0].Interfaces.Single()));
//everything after the first interface is an interface
Assert.Equal(SpecialType.System_Object, derivedTypes[1].BaseType.SpecialType);
Assert.Same(interface1, ExtractErrorGuess(derivedTypes[1].Interfaces[0]));
Assert.Same(baseType, ExtractErrorGuess(derivedTypes[1].Interfaces[1]));
Assert.Same(baseType, ExtractErrorGuess(derivedTypes[2].BaseType));
Assert.Same(interface1, ExtractErrorGuess(derivedTypes[2].Interfaces.Single()));
Assert.Same(baseType, ExtractErrorGuess(derivedTypes[3].BaseType));
Assert.Same(interface1, ExtractErrorGuess(derivedTypes[3].Interfaces.Single()));
Assert.Equal(SpecialType.System_Object, derivedTypes[4].BaseType.SpecialType);
Assert.Same(interface1, ExtractErrorGuess(derivedTypes[4].Interfaces[0]));
Assert.Same(interface2, ExtractErrorGuess(derivedTypes[4].Interfaces[1]));
Assert.Same(baseType, ExtractErrorGuess(derivedTypes[5].BaseType));
Assert.Same(interface1, ExtractErrorGuess(derivedTypes[5].Interfaces[0]));
Assert.Same(interface2, ExtractErrorGuess(derivedTypes[5].Interfaces[1]));
Assert.Same(baseType, ExtractErrorGuess(derivedTypes[6].BaseType));
Assert.Same(interface1, ExtractErrorGuess(derivedTypes[6].Interfaces[1]));
Assert.Same(interface2, ExtractErrorGuess(derivedTypes[6].Interfaces[0]));
}
private static TypeSymbol ExtractErrorGuess(NamedTypeSymbol typeSymbol)
{
Assert.Equal(TypeKind.Error, typeSymbol.TypeKind);
return typeSymbol.GetNonErrorGuess();
}
[WorkItem(2195, "DevDiv_Projects/Roslyn")]
[Fact]
public void CircularNestedInterfaceDeclaration()
{
var text = @"
class Bar : Bar.IFoo
{
public interface IFoo { Foo GetFoo(); }
public class Foo { }
public Foo GetFoo() { return null; }
}";
var comp = CreateCompilationWithMscorlib(text);
Assert.Empty(comp.GetDiagnostics());
var bar = comp.GetTypeByMetadataName("Bar");
var iFooGetFoo = comp.GetTypeByMetadataName("Bar+IFoo").GetMembers("GetFoo").Single();
MethodSymbol getFoo = (MethodSymbol)bar.FindImplementationForInterfaceMember(iFooGetFoo);
Assert.Equal("Bar.GetFoo()", getFoo.ToString());
}
[WorkItem(3684, "DevDiv_Projects/Roslyn")]
[Fact]
public void ExplicitlyImplementGenericInterface()
{
var text = @"
public interface I<Q>
{
void Foo();
}
public class Test1<Q> : I<Q>
{
void I<Q>.Foo() {}
}";
var comp = CreateCompilationWithMscorlib(text);
Assert.Empty(comp.GetDiagnostics());
}
[Fact]
public void MetadataNameOfGenericTypes()
{
var compilation = CreateCompilationWithMscorlib(@"
class Gen1<T,U,V>
{}
class NonGen
{}
");
var globalNS = compilation.GlobalNamespace;
var gen1Class = ((NamedTypeSymbol)globalNS.GetMembers("Gen1").First());
Assert.Equal("Gen1", gen1Class.Name);
Assert.Equal("Gen1`3", gen1Class.MetadataName);
var nonGenClass = ((NamedTypeSymbol)globalNS.GetMembers("NonGen").First());
Assert.Equal("NonGen", nonGenClass.Name);
Assert.Equal("NonGen", nonGenClass.MetadataName);
var system = ((NamespaceSymbol)globalNS.GetMembers("System").First());
var equatable = ((NamedTypeSymbol)system.GetMembers("IEquatable").First());
Assert.Equal("IEquatable", equatable.Name);
Assert.Equal("IEquatable`1", equatable.MetadataName);
}
[WorkItem(545154, "DevDiv")]
[ClrOnlyFact]
public void MultiDimArray()
{
var r = MetadataReference.CreateFromImage(TestResources.SymbolsTests.Methods.CSMethods.AsImmutableOrNull());
var source = @"
class Program
{
static void Main()
{
MultiDimArrays.Foo(null);
}
}
";
CompileAndVerify(source, new[] { r });
}
[Fact, WorkItem(530171, "DevDiv")]
public void ErrorTypeTest01()
{
var comp = CreateCompilationWithMscorlib(@"public void TopLevelMethod() {}");
var errSymbol = comp.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
Assert.NotNull(errSymbol);
Assert.Equal("<invalid-global-code>", errSymbol.Name);
Assert.False(errSymbol.IsErrorType(), "ErrorType");
Assert.True(errSymbol.IsImplicitClass, "ImplicitClass");
}
#region "Nullable"
[Fact, WorkItem(537195, "DevDiv")]
public void SimpleNullable()
{
var text =
@"namespace NS
{
public class A
{
int? x = null;
}
}";
var comp = CreateCompilationWithMscorlib(text);
var namespaceNS = comp.GlobalNamespace.GetMembers("NS").First() as NamespaceOrTypeSymbol;
var classA = namespaceNS.GetTypeMembers("A").First();
var varX = classA.GetMembers("x").First() as FieldSymbol;
Assert.Equal(SymbolKind.Field, varX.Kind);
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), varX.Type.OriginalDefinition);
}
[Fact]
public void BuiltInTypeNullableTest01()
{
var text = @"
public class NullableTest
{
// As Field Type
static sbyte? field01 = null;
protected byte? field02 = (byte)(field01 ?? 1);
// As Property Type
public char? Prop01 { get; private set; }
internal short? this[ushort? p1, uint? p2 = null] { set { } }
private static int? Method01(ref long? p1, out ulong? p2) { p2 = null; return null; }
public decimal? Method02(double? p1 = null, params float?[] ary) { return null; }
}
";
var comp = CreateCompilationWithMscorlib(text);
var topType = comp.SourceModule.GlobalNamespace.GetTypeMembers("NullableTest").FirstOrDefault();
// ------------------------------
var mem = topType.GetMembers("field01").Single();
var memType = (mem as FieldSymbol).Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
Assert.True(memType.CanBeAssignedNull());
var underType = memType.GetNullableUnderlyingType();
Assert.True(underType.IsNonNullableValueType());
Assert.Same(comp.GetSpecialType(SpecialType.System_SByte), underType);
// ------------------------------
mem = topType.GetMembers("field02").Single();
memType = (mem as FieldSymbol).Type;
Assert.True(memType.IsNullableType());
Assert.False(memType.CanBeConst());
underType = memType.StrippedType();
Assert.Same(comp.GetSpecialType(SpecialType.System_Byte), underType);
Assert.Same(underType, memType.GetNullableUnderlyingType());
// ------------------------------
mem = topType.GetMembers("Prop01").Single();
memType = (mem as PropertySymbol).Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
Assert.True(memType.CanBeAssignedNull());
underType = memType.StrippedType();
Assert.Same(comp.GetSpecialType(SpecialType.System_Char), underType);
Assert.Same(underType, memType.GetNullableUnderlyingType());
// ------------------------------
mem = topType.GetMembers(WellKnownMemberNames.Indexer).Single();
memType = (mem as PropertySymbol).Type;
Assert.True(memType.CanBeAssignedNull());
Assert.False(memType.CanBeConst());
underType = memType.GetNullableUnderlyingType();
Assert.True(underType.IsNonNullableValueType());
Assert.Same(comp.GetSpecialType(SpecialType.System_Int16), underType);
var paras = mem.GetParameters();
Assert.Equal(2, paras.Length);
memType = paras[0].Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_UInt16), memType.GetNullableUnderlyingType());
memType = paras[1].Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_UInt32), memType.GetNullableUnderlyingType());
// ------------------------------
mem = topType.GetMembers("Method01").Single();
memType = (mem as MethodSymbol).ReturnType;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
Assert.True(memType.CanBeAssignedNull());
underType = memType.StrippedType();
Assert.Same(comp.GetSpecialType(SpecialType.System_Int32), underType);
Assert.Same(underType, memType.GetNullableUnderlyingType());
paras = mem.GetParameters();
Assert.Equal(RefKind.Ref, paras[0].RefKind);
Assert.Equal(RefKind.Out, paras[1].RefKind);
memType = paras[0].Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_Int64), memType.GetNullableUnderlyingType());
memType = paras[1].Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_UInt64), memType.GetNullableUnderlyingType());
// ------------------------------
mem = topType.GetMembers("Method02").Single();
memType = (mem as MethodSymbol).ReturnType;
Assert.True(memType.IsNullableType());
underType = memType.GetNullableUnderlyingType();
Assert.True(underType.IsNonNullableValueType());
Assert.Same(comp.GetSpecialType(SpecialType.System_Decimal), underType);
Assert.Equal("decimal?", memType.ToDisplayString());
paras = mem.GetParameters();
Assert.True(paras[0].IsOptional);
Assert.True(paras[1].IsParams);
memType = paras[0].Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_Double), memType.GetNullableUnderlyingType());
memType = paras[1].Type;
Assert.True(memType.IsArray());
Assert.Same(comp.GetSpecialType(SpecialType.System_Single), (memType as ArrayTypeSymbol).ElementType.GetNullableUnderlyingType());
}
[Fact]
public void EnumStructNullableTest01()
{
var text = @"
public enum E { Zero, One, Two }
public struct S
{
public struct Nested { }
public delegate S? Dele(S? p1, E? p2 = E.Zero);
event Dele efield;
public static implicit operator Nested?(S? p)
{
return null;
}
public static E? operator +(S? p1, Nested? p)
{
return null;
}
}
";
var comp = CreateCompilationWithMscorlib(text);
var topType = comp.SourceModule.GlobalNamespace.GetTypeMembers("S").FirstOrDefault();
var nestedType = topType.GetTypeMembers("Nested").Single();
var enumType = comp.SourceModule.GlobalNamespace.GetTypeMembers("E").Single();
// ------------------------------
var mem = topType.GetMembers("efield").Single();
var deleType = (mem as EventSymbol).Type;
Assert.True(deleType.IsDelegateType());
var memType = deleType.DelegateInvokeMethod().ReturnType;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
var paras = deleType.DelegateParameters();
Assert.False(paras[0].IsOptional);
Assert.True(paras[1].IsOptional);
memType = paras[0].Type;
Assert.Same(topType, memType.GetNullableUnderlyingType());
memType = paras[1].Type;
Assert.Same(enumType, memType.GetNullableUnderlyingType());
Assert.Equal("E?", memType.ToDisplayString());
// ------------------------------
mem = topType.GetMembers(WellKnownMemberNames.ImplicitConversionName).Single();
memType = (mem as MethodSymbol).ReturnType;
Assert.True(memType.IsNullableType());
Assert.False(memType.CanBeConst());
var underType = memType.GetNullableUnderlyingType();
Assert.True(underType.IsNonNullableValueType());
Assert.Same(nestedType, underType);
paras = (mem as MethodSymbol).GetParameters();
Assert.Same(topType, paras[0].Type.GetNullableUnderlyingType());
// ------------------------------
mem = topType.GetMembers(WellKnownMemberNames.AdditionOperatorName).Single();
memType = (mem as MethodSymbol).ReturnType;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
Assert.True(memType.CanBeAssignedNull());
paras = mem.GetParameters();
memType = paras[0].Type;
Assert.Same(topType, memType.GetNullableUnderlyingType());
memType = paras[1].Type;
Assert.Same(nestedType, memType.GetNullableUnderlyingType());
}
[Fact]
public void LocalNullableTest01()
{
var text = @"
using System;
using System.Collections;
class A
{
static void M(DictionaryEntry? p = null)
{
System.IO.FileAccess? local01 = null;
Action<char?, PlatformID?> local02 = delegate(char? p1, PlatformID? p2) { ; };
Func<decimal?> local03 = () => 0.123m;
var local04 = new { p0 = local01, p1 = new { p1 = local02, local03 }, p };
// NYI - PlatformID?[] { PlatformID.MacOSX, null, 0 }
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var comp = CreateCompilationWithMscorlib(tree);
var model = comp.GetSemanticModel(tree);
var mnode = (MethodDeclarationSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.MethodDeclaration);
var localvars = model.AnalyzeDataFlow(mnode.Body).VariablesDeclared;
var locals = localvars.OrderBy(s => s.Name).Select(s => s).ToArray();
// 4 locals + 2 lambda params
Assert.Equal(6, locals.Length);
// local04
var anonymousType = (locals[3] as LocalSymbol).Type;
Assert.True(anonymousType.IsAnonymousType);
// --------------------
// local01
var memType = anonymousType.GetMember<PropertySymbol>("p0").Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
Assert.Same((locals[0] as LocalSymbol).Type, memType);
// --------------------
var nestedType = anonymousType.GetMember<PropertySymbol>("p1").Type;
Assert.True(nestedType.IsAnonymousType);
// local02
memType = nestedType.GetMember<PropertySymbol>("p1").Type;
Assert.True(memType.IsDelegateType());
Assert.Same((locals[1] as LocalSymbol).Type, memType);
//
var paras = memType.DelegateInvokeMethod().Parameters;
memType = paras[0].Type;
Assert.True(memType.IsNullableType());
Assert.False(memType.CanBeConst());
memType = paras[1].Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
Assert.True(memType.GetNullableUnderlyingType().IsEnumType());
Assert.Equal("System.PlatformID?", memType.ToDisplayString());
// local03
memType = nestedType.GetMember<PropertySymbol>("local03").Type;
Assert.Same((locals[2] as LocalSymbol).Type, memType);
Assert.True(memType.IsDelegateType());
// return type
memType = memType.DelegateInvokeMethod().ReturnType;
Assert.True(memType.IsNullableType());
Assert.True(memType.CanBeAssignedNull());
// --------------------
// method parameter symbol
var compType = (model.GetDeclaredSymbol(mnode) as MethodSymbol).Parameters[0].Type;
memType = anonymousType.GetMember<PropertySymbol>("p").Type;
Assert.Same(compType, memType);
Assert.True(memType.IsNullableType());
Assert.Equal("System.Collections.DictionaryEntry?", memType.ToDisplayString());
}
[Fact]
public void TypeParameterNullableTest01()
{
var text = @"
using System;
using System.Collections.Generic;
namespace NS
{
interface IFoo<T, R> where T : struct where R: struct
{
R? M<V>(ref T? p1, V? p2) where V: struct;
}
struct SFoo<T> : IFoo<T, PlatformID> where T : struct
{
PlatformID? IFoo<T, PlatformID>.M<V>(ref T? p1, V? p2) { return null; }
}
class CFoo
{
static void Main()
{
IFoo<float, PlatformID> obj = new SFoo<float>();
float? f = null;
var ret = /*<bind0>*/obj/*</bind0>*/.M<decimal>(ref /*<bind1>*/f/*</bind1>*/, /*<bind2>*/null/*</bind2>*/);
}
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(text);
var comp = CreateCompilationWithMscorlib(tree);
var model = comp.GetSemanticModel(tree);
var node1 = (LocalDeclarationStatementSyntax)tree.FindNodeOrTokenByKind(SyntaxKind.LocalDeclarationStatement, 3);
var loc = node1.Declaration.Variables.First();
var sym = model.GetDeclaredSymbol(node1.Declaration.Variables.First()) as LocalSymbol;
// --------------------
// R?
var memType = sym.Type;
Assert.Same(comp.GetSpecialType(SpecialType.System_Nullable_T), memType.OriginalDefinition);
Assert.Equal("System.PlatformID?", memType.ToDisplayString());
var nodes = GetBindingNodes<SyntaxNode>(comp).ToList();
var tinfo = model.GetTypeInfo(nodes[0] as IdentifierNameSyntax);
// obj: IFoo<float, PlatformID>
Assert.NotNull(tinfo.Type);
Assert.True(((TypeSymbol)tinfo.Type).IsInterfaceType());
Assert.Equal("NS.IFoo<float, System.PlatformID>", tinfo.Type.ToDisplayString());
// f: T? -> float?
tinfo = model.GetTypeInfo(nodes[1] as IdentifierNameSyntax);
Assert.True(((TypeSymbol)tinfo.Type).IsNullableType());
Assert.Equal("float?", tinfo.Type.ToDisplayString());
// decimal?
tinfo = model.GetTypeInfo(nodes[2] as LiteralExpressionSyntax);
Assert.True(((TypeSymbol)tinfo.ConvertedType).IsNullableType());
Assert.Same(comp.GetSpecialType(SpecialType.System_Decimal), ((TypeSymbol)tinfo.ConvertedType).GetNullableUnderlyingType());
Assert.Equal("decimal?", tinfo.ConvertedType.ToDisplayString());
}
#endregion
[Fact]
public void DynamicVersusObject()
{
var code = @"
using System;
class Foo {
dynamic X;
object Y;
Func<dynamic> Z;
Func<object> W;
}
";
var compilation = CreateCompilationWithMscorlib(code);
var Foo = compilation.GlobalNamespace.GetTypeMembers("Foo")[0];
var Dynamic = (Foo.GetMembers("X")[0] as FieldSymbol).Type;
var Object = (Foo.GetMembers("Y")[0] as FieldSymbol).Type;
var Func_Dynamic = (Foo.GetMembers("Z")[0] as FieldSymbol).Type;
var Func_Object = (Foo.GetMembers("W")[0] as FieldSymbol).Type;
var comparator = TypeSymbol.EqualsIgnoringDynamicComparer;
Assert.NotEqual(Object, Dynamic);
Assert.Equal(comparator.GetHashCode(Dynamic), comparator.GetHashCode(Object));
Assert.True(comparator.Equals(Dynamic, Object));
Assert.True(comparator.Equals(Object, Dynamic));
Assert.NotEqual(Func_Object, Func_Dynamic);
Assert.Equal(comparator.GetHashCode(Func_Dynamic), comparator.GetHashCode(Func_Object));
Assert.True(comparator.Equals(Func_Dynamic, Func_Object));
Assert.True(comparator.Equals(Func_Object, Func_Dynamic));
}
[Fact]
public void UnboundGenericTypeEquality()
{
var code = @"
class C<T>
{
}
";
var compilation = CreateCompilationWithMscorlib(code);
var originalDefinition = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
var unboundGeneric1 = originalDefinition.AsUnboundGenericType();
var unboundGeneric2 = originalDefinition.AsUnboundGenericType();
Assert.Equal(unboundGeneric1, unboundGeneric2);
}
[Fact]
public void SymbolInfoForUnboundGenericTypeObjectCreation()
{
var code = @"
class C<T>
{
static void Main()
{
var c = new C<>();
}
}
";
var compilation = CreateCompilationWithMscorlib(code);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var syntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ObjectCreationExpressionSyntax>().Single();
var info = model.GetSymbolInfo(syntax);
var symbol = info.Symbol;
var originalDefinition = compilation.GlobalNamespace.GetMember<NamedTypeSymbol>("C");
Assert.Equal(originalDefinition.InstanceConstructors.Single(), symbol.OriginalDefinition);
Assert.False(symbol.ContainingType.IsUnboundGenericType);
Assert.IsType<UnboundArgumentErrorTypeSymbol>(symbol.ContainingType.TypeArguments.Single());
}
}
}
| |
// Copyright 2019 Esri
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using ArcGIS.Core.Data;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Editing;
using ArcGIS.Desktop.Editing.Attributes;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Framework.Controls;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Desktop.Mapping.Events;
namespace DivideLines
{
class DivideLinesViewModel : EmbeddableControl
{
public DivideLinesViewModel(System.Xml.Linq.XElement options, bool canChangeOptions) : base(options, canChangeOptions) { }
#region EmbeddableControl interface
private bool _designMode;
public bool DesignMode
{
get { return _designMode; }
private set { SetProperty(ref _designMode, value, () => DesignMode); }
}
public override bool CanCommit { get { return true; } }
public override Task CommitAsync() { return base.CommitAsync(); }
public override void Dispose() { base.Dispose(); }
protected override void OnOptionsChanged()
{
base.OnOptionsChanged();
DesignMode = !String.IsNullOrEmpty(GetOption("designMode"));
}
private string GetOption(string name)
{
if (Options == null)
return "";
else if (Options.Element(name) != null)
return Options.Element(name).Value.ToString();
else if (Options.Attribute(name) != null)
return Options.Attribute(name).Value.ToString();
else
return "";
}
#endregion
public override async Task OpenAsync()
{
await base.OpenAsync();
if (DesignMode) return;
// Make sure tool is active (if not already).
await FrameworkApplication.SetCurrentToolAsync("esri_sample_divideLinesTool");
_okRelay = new RelayCommand(() => DivideLinesAsync(IsNumberOfParts, Value), CanDivideLines);
NotifyPropertyChanged(() => OKCommand);
ArcGIS.Desktop.Mapping.Events.MapSelectionChangedEvent.Subscribe(OnSelectionChanged);
await QueuedTask.Run(() => _cachedValue = CheckSelection(MapView.Active.Map.GetSelection()));
}
public override Task CloseAsync()
{
ArcGIS.Desktop.Mapping.Events.MapSelectionChangedEvent.Unsubscribe(OnSelectionChanged);
return base.CloseAsync();
}
#region Bindable Properties
private RelayCommand _okRelay;
public ICommand OKCommand { get { return _okRelay; } }
private static bool _isNumberOfParts = true;
public bool IsNumberOfParts
{
get { return _isNumberOfParts; }
set
{
if (SetProperty(ref _isNumberOfParts, value, () => IsNumberOfParts))
NotifyPropertyChanged(() => IsDistance);
}
}
public bool IsDistance
{
get { return !_isNumberOfParts; }
set { IsNumberOfParts = !value; }
}
private static double _value = 2;
public double Value
{
get { return _value; }
set { SetProperty(ref _value, value, () => Value); }
}
#endregion
#region Implementation
private void OnSelectionChanged(MapSelectionChangedEventArgs obj)
{
if (obj.Map != MapView.Active.Map) return;
_cachedValue = false;
_cachedValue = CheckSelection(obj.Selection);
}
private static bool CheckSelection(Dictionary<MapMember, List<long>> sel)
{
//Enable only if we have one selected polyline feature that is editable.
if (sel == null || sel.Values.Sum(List => List.Count) != 1) return false;
var member = sel.Keys.FirstOrDefault();
var oids = sel[member];
if (member is IDisplayTable)
{
var dt = member as IDisplayTable;
var canEdit = dt.CanEditData();
if (!canEdit) return false;
var flayer = member as FeatureLayer;
if (flayer == null) return false;
if (flayer.ShapeType != ArcGIS.Core.CIM.esriGeometryType.esriGeometryPolyline) return false;
return true;
}
return false;
}
private bool _cachedValue = false;
private bool CanDivideLines()
{
return _cachedValue;
}
/// <summary>
/// Divide the first selected feature into equal parts or by map unit distance.
/// </summary>
/// <param name="numberOfParts">Number of parts to create.</param>
/// <param name="value">Value for number or parts or distance.</param>
/// <returns></returns>
private static Task DivideLinesAsync(bool numberOfParts, double value)
{
//Run on MCT
return QueuedTask.Run(() =>
{
//get selected feature
var selectedFeatures = MapView.Active.Map.GetSelection();
//get the layer of the selected feature
var featLayer = selectedFeatures.Keys.First() as FeatureLayer;
var oid = selectedFeatures.Values.First().First();
var feature = featLayer.Inspect(oid);
//get geometry and length
var origPolyLine = feature.Shape as Polyline;
var origLength = GeometryEngine.Instance.Length(origPolyLine);
string xml = origPolyLine.ToXML();
//List of mappoint geometries for the split
var splitPoints = new List<MapPoint>();
var enteredValue = (numberOfParts) ? origLength / value : value;
var splitAtDistance = 0 + enteredValue;
while (splitAtDistance < origLength)
{
//create a mapPoint at splitDistance and add to splitpoint list
MapPoint pt = null;
try
{
pt = GeometryEngine.Instance.MovePointAlongLine(origPolyLine, splitAtDistance, false, 0, SegmentExtension.NoExtension);
}
catch (GeometryObjectException)
{
// line is an arc?
}
if (pt != null)
splitPoints.Add(pt);
splitAtDistance += enteredValue;
}
if (splitPoints.Count == 0)
{
ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Divide lines was unable to process your selected line. Please select another.", "Divide Lines");
return;
}
//create and execute the edit operation
var op = new EditOperation()
{
Name = "Divide Lines",
SelectModifiedFeatures = false,
SelectNewFeatures = false
};
op.Split(featLayer, oid, splitPoints);
op.Execute();
//clear selection
featLayer.ClearSelection();
});
}
#endregion
}
}
| |
// -- FILE ------------------------------------------------------------------
// name : QuartersTest.cs
// project : Itenso Time Period
// created : Jani Giannoudis - 2011.02.18
// language : C# 4.0
// environment: .NET 2.0
// copyright : (c) 2011-2012 by Itenso GmbH, Switzerland
// --------------------------------------------------------------------------
using System;
using Itenso.TimePeriod;
using Xunit;
namespace Itenso.TimePeriodTests
{
// ------------------------------------------------------------------------
public sealed class QuartersTest : TestUnitBase
{
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void YearBaseMonthTest()
{
DateTime moment = new DateTime( 2009, 2, 15 );
int year = TimeTool.GetYearOf( YearMonth.April, moment.Year, moment.Month );
Quarters quarters = new Quarters( moment, YearQuarter.First, 3, TimeCalendar.New( YearMonth.April ) );
Assert.Equal(YearMonth.April, quarters.YearBaseMonth);
Assert.Equal( quarters.Start, new DateTime( year, (int)YearMonth.April, 1 ) );
} // YearBaseMonthTest
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void SingleQuartersTest()
{
const int startYear = 2004;
const YearQuarter startQuarter = YearQuarter.Second;
Quarters quarters = new Quarters( startYear, startQuarter, 1 );
Assert.Equal(YearMonth.January, quarters.YearBaseMonth);
Assert.Equal(1, quarters.QuarterCount);
Assert.Equal( quarters.StartQuarter, startQuarter );
Assert.Equal( quarters.StartYear, startYear );
Assert.Equal( quarters.EndYear, startYear );
Assert.Equal(YearQuarter.Second, quarters.EndQuarter);
Assert.Equal(1, quarters.GetQuarters().Count);
Assert.True( quarters.GetQuarters()[ 0 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Second ) ) );
} // SingleQuartersTest
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void FirstCalendarQuartersTest()
{
const int startYear = 2004;
const YearQuarter startQuarter = YearQuarter.First;
const int quarterCount = 5;
Quarters quarters = new Quarters( startYear, startQuarter, quarterCount );
Assert.Equal(YearMonth.January, quarters.YearBaseMonth);
Assert.Equal( quarters.QuarterCount, quarterCount );
Assert.Equal( quarters.StartQuarter, startQuarter );
Assert.Equal( quarters.StartYear, startYear );
Assert.Equal(2005, quarters.EndYear);
Assert.Equal(YearQuarter.First, quarters.EndQuarter);
Assert.Equal( quarters.GetQuarters().Count, quarterCount );
Assert.True( quarters.GetQuarters()[ 0 ].IsSamePeriod( new Quarter( 2004, YearQuarter.First ) ) );
Assert.True( quarters.GetQuarters()[ 1 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Second ) ) );
Assert.True( quarters.GetQuarters()[ 2 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Third ) ) );
Assert.True( quarters.GetQuarters()[ 3 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Fourth ) ) );
Assert.True( quarters.GetQuarters()[ 4 ].IsSamePeriod( new Quarter( 2005, YearQuarter.First ) ) );
} // FirstCalendarQuartersTest
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void SecondCalendarQuartersTest()
{
const int startYear = 2004;
const YearQuarter startQuarter = YearQuarter.Second;
const int quarterCount = 5;
Quarters quarters = new Quarters( startYear, startQuarter, quarterCount );
Assert.Equal(YearMonth.January, quarters.YearBaseMonth);
Assert.Equal( quarters.QuarterCount, quarterCount );
Assert.Equal( quarters.StartQuarter, startQuarter );
Assert.Equal( quarters.StartYear, startYear );
Assert.Equal(2005, quarters.EndYear);
Assert.Equal(YearQuarter.Second, quarters.EndQuarter);
Assert.Equal( quarters.GetQuarters().Count, quarterCount );
Assert.True( quarters.GetQuarters()[ 0 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Second ) ) );
Assert.True( quarters.GetQuarters()[ 1 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Third ) ) );
Assert.True( quarters.GetQuarters()[ 2 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Fourth ) ) );
Assert.True( quarters.GetQuarters()[ 3 ].IsSamePeriod( new Quarter( 2005, YearQuarter.First ) ) );
Assert.True( quarters.GetQuarters()[ 4 ].IsSamePeriod( new Quarter( 2005, YearQuarter.Second ) ) );
} // SecondCalendarQuartersTest
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void FirstCustomCalendarQuartersTest()
{
TimeCalendar calendar = TimeCalendar.New( YearMonth.October );
const int startYear = 2004;
const YearQuarter startQuarter = YearQuarter.First;
const int quarterCount = 5;
Quarters quarters = new Quarters( startYear, startQuarter, quarterCount, calendar );
Assert.Equal(YearMonth.October, quarters.YearBaseMonth);
Assert.Equal( quarters.QuarterCount, quarterCount );
Assert.Equal( quarters.StartQuarter, startQuarter );
Assert.Equal( quarters.StartYear, startYear );
Assert.Equal(2005, quarters.EndYear);
Assert.Equal(YearQuarter.First, quarters.EndQuarter);
Assert.Equal( quarters.GetQuarters().Count, quarterCount );
Assert.True( quarters.GetQuarters()[ 0 ].IsSamePeriod( new Quarter( 2004, YearQuarter.First, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 1 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Second, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 2 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Third, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 3 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Fourth, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 4 ].IsSamePeriod( new Quarter( 2005, YearQuarter.First, calendar ) ) );
} // FirstCustomCalendarQuartersTest
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void SecondCustomCalendarQuartersTest()
{
TimeCalendar calendar = TimeCalendar.New( YearMonth.October );
const int startYear = 2004;
const YearQuarter startQuarter = YearQuarter.Second;
const int quarterCount = 5;
Quarters quarters = new Quarters( startYear, startQuarter, quarterCount, calendar );
Assert.Equal(YearMonth.October, quarters.YearBaseMonth);
Assert.Equal( quarters.QuarterCount, quarterCount );
Assert.Equal( quarters.StartQuarter, startQuarter );
Assert.Equal( quarters.StartYear, startYear );
Assert.Equal(2005, quarters.EndYear);
Assert.Equal(YearQuarter.Second, quarters.EndQuarter);
Assert.Equal( quarters.GetQuarters().Count, quarterCount );
Assert.True( quarters.GetQuarters()[ 0 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Second, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 1 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Third, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 2 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Fourth, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 3 ].IsSamePeriod( new Quarter( 2005, YearQuarter.First, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 4 ].IsSamePeriod( new Quarter( 2005, YearQuarter.Second, calendar ) ) );
} // SecondCustomCalendarQuartersTest
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void ThirdCustomCalendarQuartersTest()
{
TimeCalendar calendar = TimeCalendar.New( YearMonth.October );
const int startYear = 2004;
const YearQuarter startQuarter = YearQuarter.Third;
const int quarterCount = 5;
Quarters quarters = new Quarters( startYear, startQuarter, quarterCount, calendar );
Assert.Equal(YearMonth.October, quarters.YearBaseMonth);
Assert.Equal( quarters.QuarterCount, quarterCount );
Assert.Equal( quarters.StartQuarter, startQuarter );
Assert.Equal( quarters.StartYear, startYear );
Assert.Equal(2005, quarters.EndYear);
Assert.Equal(YearQuarter.Third, quarters.EndQuarter);
Assert.Equal( quarters.GetQuarters().Count, quarterCount );
Assert.True( quarters.GetQuarters()[ 0 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Third, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 1 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Fourth, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 2 ].IsSamePeriod( new Quarter( 2005, YearQuarter.First, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 3 ].IsSamePeriod( new Quarter( 2005, YearQuarter.Second, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 4 ].IsSamePeriod( new Quarter( 2005, YearQuarter.Third, calendar ) ) );
} // ThirdCustomCalendarQuartersTest
// ----------------------------------------------------------------------
[Trait("Category", "Quarters")]
[Fact]
public void FourthCustomCalendarQuartersTest()
{
TimeCalendar calendar = TimeCalendar.New( YearMonth.October );
const int startYear = 2004;
const YearQuarter startQuarter = YearQuarter.Fourth;
const int quarterCount = 5;
Quarters quarters = new Quarters( startYear, startQuarter, quarterCount, calendar );
Assert.Equal(YearMonth.October, quarters.YearBaseMonth);
Assert.Equal( quarters.QuarterCount, quarterCount );
Assert.Equal( quarters.StartQuarter, startQuarter );
Assert.Equal( quarters.StartYear, startYear );
Assert.Equal(2005, quarters.EndYear);
Assert.Equal(YearQuarter.Fourth, quarters.EndQuarter);
Assert.Equal( quarters.GetQuarters().Count, quarterCount );
Assert.True( quarters.GetQuarters()[ 0 ].IsSamePeriod( new Quarter( 2004, YearQuarter.Fourth, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 1 ].IsSamePeriod( new Quarter( 2005, YearQuarter.First, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 2 ].IsSamePeriod( new Quarter( 2005, YearQuarter.Second, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 3 ].IsSamePeriod( new Quarter( 2005, YearQuarter.Third, calendar ) ) );
Assert.True( quarters.GetQuarters()[ 4 ].IsSamePeriod( new Quarter( 2005, YearQuarter.Fourth, calendar ) ) );
} // FourthCustomCalendarQuartersTest
// ----------------------------------------------------------------------
private ITimeCalendar GetFiscalYearCalendar( FiscalYearAlignment yearAlignment )
{
return new TimeCalendar(
new TimeCalendarConfig
{
YearType = YearType.FiscalYear,
YearBaseMonth = YearMonth.September,
FiscalFirstDayOfYear = DayOfWeek.Sunday,
FiscalYearAlignment = yearAlignment,
FiscalQuarterGrouping = FiscalQuarterGrouping.FourFourFiveWeeks
} );
} // GetFiscalYearCalendar
// ----------------------------------------------------------------------
// http://en.wikipedia.org/wiki/4-4-5_Calendar
[Trait("Category", "Quarters")]
[Fact]
public void FiscalYearGetMonthsTest()
{
const int quarterCount = 8;
Quarters halfyears = new Quarters( 2006, YearQuarter.First, quarterCount, GetFiscalYearCalendar( FiscalYearAlignment.LastDay ) );
ITimePeriodCollection months = halfyears.GetMonths();
Assert.NotNull(months);
Assert.Equal( months.Count, TimeSpec.MonthsPerQuarter * quarterCount );
Assert.Equal( months[ 0 ].Start, new DateTime( 2006, 8, 27 ) );
for ( int i = 0; i < months.Count; i++ )
{
Month month = (Month)months[ i ];
// last month of a leap year (6 weeks)
// http://en.wikipedia.org/wiki/4-4-5_Calendar
if ( ( month.YearMonth == YearMonth.August ) && ( month.Year == 2008 || month.Year == 2013 || month.Year == 2019 ) )
{
Assert.Equal( month.Duration.Subtract( TimeCalendar.DefaultEndOffset ).Days, TimeSpec.FiscalDaysPerLeapMonth );
}
else if ( ( i + 1 ) % 3 == 0 ) // first and second month of quarter (4 weeks)
{
Assert.Equal( month.Duration.Subtract( TimeCalendar.DefaultEndOffset ).Days, TimeSpec.FiscalDaysPerLongMonth );
}
else // third month of quarter (5 weeks)
{
Assert.Equal( month.Duration.Subtract( TimeCalendar.DefaultEndOffset ).Days, TimeSpec.FiscalDaysPerShortMonth );
}
}
Assert.Equal( months[ ( TimeSpec.MonthsPerQuarter * quarterCount ) - 1 ].End, halfyears.End );
} // FiscalYearGetMonthsTest
} // class QuartersTest
} // namespace Itenso.TimePeriodTests
// -- EOF -------------------------------------------------------------------
| |
// Copyright 2017 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The controller is not available for versions of Unity without the
// GVR native integration.
using UnityEngine;
using UnityEngine.EventSystems;
/// Implementation of GvrBasePointer for a laser pointer visual.
/// This script should be attached to the controller object.
/// The laser visual is important to help users locate their cursor
/// when its not directly in their field of view.
public class GvrLaserPointerImpl : GvrBasePointer {
/// Small offset to prevent z-fighting of the reticle (meters).
private const float Z_OFFSET_EPSILON = 0.1f;
/// Final size of the reticle in meters when it is 1 meter from the camera.
/// The reticle will be scaled based on the size of the mesh so that it's size
/// matches this size.
private const float RETICLE_SIZE_METERS = 0.1f;
/// The percentage of the reticle mesh that shows the reticle.
/// The rest of the reticle mesh is transparent.
private const float RETICLE_VISUAL_RATIO = 0.1f;
public Camera MainCamera { private get; set; }
public Color LaserColor { private get; set; }
public LineRenderer LaserLineRenderer { get; set; }
public float MaxLaserDistance { private get; set; }
public float MaxReticleDistance { private get; set; }
private GameObject reticle;
public GameObject Reticle {
get {
return reticle;
}
set {
reticle = value;
reticleMeshSizeMeters = 1.0f;
reticleMeshSizeRatio = 1.0f;
if (reticle != null) {
MeshFilter meshFilter = reticle.GetComponent<MeshFilter>();
if (meshFilter != null && meshFilter.mesh != null) {
reticleMeshSizeMeters = meshFilter.mesh.bounds.size.x;
if (reticleMeshSizeMeters != 0.0f) {
reticleMeshSizeRatio = 1.0f / reticleMeshSizeMeters;
}
}
}
}
}
// Properties exposed for testing purposes.
public Vector3 PointerIntersection { get; private set; }
public bool IsPointerIntersecting { get; private set; }
public Ray PointerIntersectionRay { get; private set; }
// The size of the reticle's mesh in meters.
private float reticleMeshSizeMeters;
// The ratio of the reticleMeshSizeMeters to 1 meter.
// If reticleMeshSizeMeters is 10, then reticleMeshSizeRatio is 0.1.
private float reticleMeshSizeRatio;
private Vector3 lineEndPoint = Vector3.zero;
public override Vector3 LineEndPoint { get { return lineEndPoint; } }
public override float MaxPointerDistance {
get {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
return MaxReticleDistance;
#else
return 0;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
}
public GvrLaserPointerImpl() {
MaxLaserDistance = 0.75f;
MaxReticleDistance = 2.5f;
}
#if !(UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR))
public override void OnStart() {
// Don't call base.Start() so that this pointer isn't activated when
// the editor doesn't have UNITY_HAS_GOOGLE_VR.
}
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
public override void OnInputModuleEnabled() {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
if (LaserLineRenderer != null) {
LaserLineRenderer.enabled = true;
}
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
public override void OnInputModuleDisabled() {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
if (LaserLineRenderer != null) {
LaserLineRenderer.enabled = false;
}
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
public override void OnPointerEnter(RaycastResult rayastResult, Ray ray,
bool isInteractive) {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
PointerIntersection = rayastResult.worldPosition;
PointerIntersectionRay = ray;
IsPointerIntersecting = true;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
public override void OnPointerHover(RaycastResult rayastResult, Ray ray,
bool isInteractive) {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
PointerIntersection = rayastResult.worldPosition;
PointerIntersectionRay = ray;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
public override void OnPointerExit(GameObject previousObject) {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
PointerIntersection = Vector3.zero;
PointerIntersectionRay = new Ray();
IsPointerIntersecting = false;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
public override void OnPointerClickDown() {
// User has performed a click on the target. In a derived class, you could
// handle visual feedback such as laser or cursor color changes here.
}
public override void OnPointerClickUp() {
// User has released a click from the target. In a derived class, you could
// handle visual feedback such as laser or cursor color changes here.
}
public override void GetPointerRadius(out float enterRadius, out float exitRadius) {
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
if (Reticle != null) {
float reticleScale = Reticle.transform.localScale.x;
// Fixed size for enter radius to avoid flickering.
// This will cause some slight variability based on the distance of the object
// from the camera, and is optimized for the average case.
enterRadius = RETICLE_SIZE_METERS * 0.5f * RETICLE_VISUAL_RATIO;
// Dynamic size for exit radius.
// Always correct because we know the intersection point of the object and can
// therefore use the correct radius based on the object's distance from the camera.
exitRadius = reticleScale * reticleMeshSizeMeters * RETICLE_VISUAL_RATIO;
} else {
enterRadius = 0.0f;
exitRadius = 0.0f;
}
#else
enterRadius = 0.0f;
exitRadius = 0.0f;
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
#if UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
public void OnUpdate() {
// Set the reticle's position and scale
if (Reticle != null) {
if (IsPointerIntersecting) {
Vector3 difference = PointerIntersection - PointerIntersectionRay.origin;
Vector3 clampedDifference = Vector3.ClampMagnitude(difference, MaxReticleDistance);
Vector3 clampedPosition = PointerIntersectionRay.origin + clampedDifference;
Reticle.transform.position = clampedPosition;
} else {
Reticle.transform.localPosition = new Vector3(0, 0, MaxReticleDistance);
}
float reticleDistanceFromCamera =
(Reticle.transform.position - MainCamera.transform.position).magnitude;
float scale = RETICLE_SIZE_METERS * reticleMeshSizeRatio * reticleDistanceFromCamera;
Reticle.transform.localScale = new Vector3(scale, scale, scale);
}
if (LaserLineRenderer == null) {
Debug.LogWarning("Line renderer is null, returning");
return;
}
// Set the line renderer positions.
if (IsPointerIntersecting) {
Vector3 laserDiff = PointerIntersection - base.PointerTransform.position;
float intersectionDistance = laserDiff.magnitude;
Vector3 direction = laserDiff.normalized;
float laserDistance = intersectionDistance > MaxLaserDistance ? MaxLaserDistance : intersectionDistance;
lineEndPoint = base.PointerTransform.position + (direction * laserDistance);
} else {
lineEndPoint = base.PointerTransform.position + (base.PointerTransform.forward * MaxLaserDistance);
}
LaserLineRenderer.SetPosition(0,base.PointerTransform.position);
LaserLineRenderer.SetPosition(1,lineEndPoint);
// Adjust transparency
float alpha = GvrArmModel.Instance.preferredAlpha;
#if UNITY_5_6_OR_NEWER
LaserLineRenderer.startColor = Color.Lerp(Color.clear, LaserColor, alpha);
LaserLineRenderer.endColor = Color.clear;
#else
LaserLineRenderer.SetColors(Color.Lerp(Color.clear, LaserColor, alpha), Color.clear);
#endif // UNITY_5_6_OR_NEWER
}
#endif // UNITY_HAS_GOOGLEVR && (UNITY_ANDROID || UNITY_EDITOR)
}
| |
//-----------------------------------------------------------------------
// <copyright file="FlowDelaySpec.cs" company="Akka.NET Project">
// Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Akka.Actor;
using Akka.Streams.Dsl;
using Akka.Streams.TestKit;
using Akka.Streams.TestKit.Tests;
using Akka.Streams.Tests.Actor;
using Akka.TestKit;
using Akka.Util.Internal;
using FluentAssertions;
using Xunit;
using Xunit.Abstractions;
// ReSharper disable InvokeAsExtensionMethod
namespace Akka.Streams.Tests.Dsl
{
public class FlowDelaySpec : AkkaSpec
{
private ActorMaterializer Materializer { get; }
public FlowDelaySpec(ITestOutputHelper helper) : base(helper)
{
Materializer = ActorMaterializer.Create(Sys);
}
[Fact]
public void A_Delay_must_deliver_elements_with_some_time_shift()
{
var task =
Source.From(Enumerable.Range(1, 10))
.Delay(TimeSpan.FromSeconds(1))
.Grouped(100)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromMilliseconds(1200)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(1, 10));
}
[Fact]
public void A_Delay_must_add_delay_to_initialDelay_if_exists_upstream()
{
var probe = Source.From(Enumerable.Range(1, 10))
.InitialDelay(TimeSpan.FromSeconds(1))
.Delay(TimeSpan.FromSeconds(1))
.RunWith(this.SinkProbe<int>(), Materializer);
probe.Request(10);
probe.ExpectNoMsg(TimeSpan.FromMilliseconds(1800));
probe.ExpectNext(1, TimeSpan.FromMilliseconds(300));
probe.ExpectNextN(Enumerable.Range(2, 9));
probe.ExpectComplete();
}
[Fact]
public void A_Delay_must_deliver_element_after_time_passed_from_actual_receiving_element()
{
var probe = Source.From(Enumerable.Range(1, 3))
.Delay(TimeSpan.FromMilliseconds(300))
.RunWith(this.SinkProbe<int>(), Materializer);
probe.Request(2)
.ExpectNoMsg(TimeSpan.FromMilliseconds(200)) //delay
.ExpectNext(1, TimeSpan.FromMilliseconds(200)) //delayed element
.ExpectNext(2, TimeSpan.FromMilliseconds(100)) //buffered element
.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
probe.Request(1)
.ExpectNext(3) //buffered element
.ExpectComplete();
}
[Fact]
public void A_Delay_must_deliver_elements_with_delay_for_slow_stream()
{
this.AssertAllStagesStopped(() =>
{
var c = this.CreateManualSubscriberProbe<int>();
var p = this.CreateManualPublisherProbe<int>();
Source.FromPublisher(p)
.Delay(TimeSpan.FromMilliseconds(300))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var cSub = c.ExpectSubscription();
var pSub = p.ExpectSubscription();
cSub.Request(100);
pSub.SendNext(1);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
c.ExpectNext(1);
pSub.SendNext(2);
c.ExpectNoMsg(TimeSpan.FromMilliseconds(200));
c.ExpectNext(2);
pSub.SendComplete();
c.ExpectComplete();
}, Materializer);
}
[Fact]
public void A_Delay_must_drop_tail_for_internal_buffer_if_it_is_full_in_DropTail_mode()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 20))
.Delay(TimeSpan.FromSeconds(1), DelayOverflowStrategy.DropTail)
.WithAttributes(Attributes.CreateInputBuffer(16, 16))
.Grouped(100)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromMilliseconds(1200)).Should().BeTrue();
var expected = Enumerable.Range(1, 15).ToList();
expected.Add(20);
task.Result.ShouldAllBeEquivalentTo(expected);
}, Materializer);
}
[Fact]
public void A_Delay_must_drop_head_for_internal_buffer_if_it_is_full_in_DropHead_mode()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 20))
.Delay(TimeSpan.FromSeconds(1), DelayOverflowStrategy.DropHead)
.WithAttributes(Attributes.CreateInputBuffer(16, 16))
.Grouped(100)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromMilliseconds(1200)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(5, 16));
}, Materializer);
}
[Fact]
public void A_Delay_must_clear_all_for_internal_buffer_if_it_is_full_in_DropBuffer_mode()
{
this.AssertAllStagesStopped(() =>
{
var task = Source.From(Enumerable.Range(1, 20))
.Delay(TimeSpan.FromSeconds(1), DelayOverflowStrategy.DropBuffer)
.WithAttributes(Attributes.CreateInputBuffer(16, 16))
.Grouped(100)
.RunWith(Sink.First<IEnumerable<int>>(), Materializer);
task.Wait(TimeSpan.FromMilliseconds(1200)).Should().BeTrue();
task.Result.ShouldAllBeEquivalentTo(Enumerable.Range(17, 4));
}, Materializer);
}
[Fact]
public void A_Delay_must_pass_elements_with_delay_through_normally_in_backpressured_mode()
{
this.AssertAllStagesStopped(() =>
{
Source.From(Enumerable.Range(1, 3))
.Delay(TimeSpan.FromMilliseconds(300), DelayOverflowStrategy.Backpressure)
.WithAttributes(Attributes.CreateInputBuffer(1,1))
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(5)
.ExpectNoMsg(TimeSpan.FromMilliseconds(200))
.ExpectNext(1, TimeSpan.FromMilliseconds(200))
.ExpectNoMsg(TimeSpan.FromMilliseconds(200))
.ExpectNext(2, TimeSpan.FromMilliseconds(200))
.ExpectNoMsg(TimeSpan.FromMilliseconds(200))
.ExpectNext(3, TimeSpan.FromMilliseconds(200));
}, Materializer);
}
[Fact]
public void A_Delay_must_fail_on_overflow_in_Fail_mode()
{
this.AssertAllStagesStopped(() =>
{
var actualError = Source.From(Enumerable.Range(1, 20))
.Delay(TimeSpan.FromMilliseconds(300), DelayOverflowStrategy.Fail)
.WithAttributes(Attributes.CreateInputBuffer(16, 16))
.RunWith(this.SinkProbe<int>(), Materializer)
.Request(100)
.ExpectError();
actualError.Should().BeOfType<BufferOverflowException>();
actualError.Message.Should().Be("Buffer overflow for Delay combinator (max capacity was: 16)!");
}, Materializer);
}
[Fact]
public void A_Delay_must_emit_early_when_buffer_is_full_and_in_EmitEarly_mode()
{
this.AssertAllStagesStopped(() =>
{
var c = this.CreateManualSubscriberProbe<int>();
var p = this.CreateManualPublisherProbe<int>();
Source.FromPublisher(p)
.Delay(TimeSpan.FromSeconds(10), DelayOverflowStrategy.EmitEarly)
.WithAttributes(Attributes.CreateInputBuffer(16, 16))
.To(Sink.FromSubscriber(c))
.Run(Materializer);
var cSub = c.ExpectSubscription();
var pSub = p.ExpectSubscription();
cSub.Request(20);
Enumerable.Range(1, 16).ForEach(i => pSub.SendNext(i));
c.ExpectNoMsg(TimeSpan.FromMilliseconds(300));
pSub.SendNext(17);
c.ExpectNext(1, TimeSpan.FromMilliseconds(100));
// fail will terminate despite of non empty internal buffer
pSub.SendError(new Exception());
}, Materializer);
}
[Fact]
public void A_Delay_must_properly_delay_according_to_buffer_size()
{
// With a buffer size of 1, delays add up
var task = Source.From(Enumerable.Range(1, 5))
.Delay(TimeSpan.FromMilliseconds(500), DelayOverflowStrategy.Backpressure)
.WithAttributes(Attributes.CreateInputBuffer(1, 1))
.RunWith(Sink.Ignore<int>(), Materializer);
task.Wait(TimeSpan.FromSeconds(2)).ShouldBeFalse();
task.Wait(TimeSpan.FromSeconds(1)).ShouldBeTrue();
// With a buffer large enough to hold all arriving elements, delays don't add up
task = Source.From(Enumerable.Range(1, 100))
.Delay(TimeSpan.FromSeconds(1), DelayOverflowStrategy.Backpressure)
.WithAttributes(Attributes.CreateInputBuffer(100, 100))
.RunWith(Sink.Ignore<int>(), Materializer);
task.Wait(TimeSpan.FromSeconds(2)).ShouldBeTrue();
// Delays that are already present are preserved when buffer is large enough
task = Source.Tick(TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), NotUsed.Instance)
.Take(10)
.Delay(TimeSpan.FromSeconds(1), DelayOverflowStrategy.Backpressure)
.WithAttributes(Attributes.CreateInputBuffer(10, 10))
.RunWith(Sink.Ignore<NotUsed>(), Materializer);
task.Wait(TimeSpan.FromMilliseconds(900)).ShouldBeFalse();
task.Wait(TimeSpan.FromSeconds(1)).ShouldBeTrue();
}
}
}
| |
//
// AddinTile.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Mono.Unix;
using Mono.Addins;
using Hyena.Widgets;
namespace Banshee.Addins.Gui
{
public class AddinTile : Table
{
private Addin addin;
private Button activate_button;
private Button details_button;
private Box button_box;
private Label title;
private WrapLabel description;
private WrapLabel authors;
private bool last;
public bool Last {
get { return last; }
set { last = value; }
}
public event EventHandler ActiveChanged;
public AddinTile (Addin addin) : base (3, 3, false)
{
this.addin = addin;
BuildTile ();
}
private void BuildTile ()
{
BorderWidth = 5;
RowSpacing = 1;
ColumnSpacing = 5;
Image image = new Image ();
image.IconName = "package-x-generic";
image.IconSize = (int)IconSize.Dnd;
image.Yalign = 0.0f;
image.Show ();
Attach (image, 0, 1, 0, 3, AttachOptions.Shrink, AttachOptions.Fill | AttachOptions.Expand, 0, 0);
title = new Label ();
SetLabelStyle (title);
title.Show ();
title.Xalign = 0.0f;
title.Markup = String.Format ("<b>{0}</b>", GLib.Markup.EscapeText (addin.Name));
Attach (title, 1, 3, 0, 1,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 0);
description = new WrapLabel ();
SetLabelStyle (description);
description.Show ();
description.Text = addin.Description.Description;
description.Wrap = false;
Attach (description, 1, 3, 1, 2,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 0);
authors = new WrapLabel ();
SetLabelStyle (authors);
authors.Markup = String.Format (
"<small><b>{0}</b> <i>{1}</i></small>",
Catalog.GetString ("Authors:"),
GLib.Markup.EscapeText (addin.Description.Author)
);
Attach (authors, 1, 2, 2, 3,
AttachOptions.Expand | AttachOptions.Fill,
AttachOptions.Expand | AttachOptions.Fill, 0, 4);
button_box = new VBox ();
HBox box = new HBox ();
box.Spacing = 3;
button_box.PackEnd (box, false, false, 0);
Pango.FontDescription font = PangoContext.FontDescription.Copy ();
font.Size = (int)(font.Size * Pango.Scale.Small);
Label label = new Label ("Details");
label.ModifyFont (font);
details_button = new Button ();
details_button.Add (label);
details_button.Clicked += OnDetailsClicked;
box.PackStart (details_button, false, false, 0);
label = new Label ();
label.ModifyFont (font);
activate_button = new Button ();
activate_button.Add (label);
activate_button.Clicked += OnActivateClicked;
box.PackStart (activate_button, false, false, 0);
Attach (button_box, 2, 3, 2, 3, AttachOptions.Shrink, AttachOptions.Expand | AttachOptions.Fill, 0, 0);
Show ();
UpdateState ();
}
private void SetLabelStyle (Widget label)
{
bool changing_styles = false;
label.StyleSet += delegate {
if (changing_styles) {
return;
}
changing_styles = true;
label.ModifyBg (StateType.Normal, label.Style.Base (StateType.Normal));
label.ModifyBg (StateType.Active, label.Style.Base (StateType.Active));
label.ModifyBg (StateType.Prelight, label.Style.Base (StateType.Prelight));
label.ModifyBg (StateType.Selected, label.Style.Base (StateType.Selected));
label.ModifyBg (StateType.Insensitive, label.Style.Base (StateType.Insensitive));
label.ModifyFg (StateType.Normal, label.Style.Text (StateType.Normal));
label.ModifyFg (StateType.Active, label.Style.Text (StateType.Active));
label.ModifyFg (StateType.Prelight, label.Style.Text (StateType.Prelight));
label.ModifyFg (StateType.Selected, label.Style.Text (StateType.Selected));
label.ModifyFg (StateType.Insensitive, label.Style.Text (StateType.Insensitive));
changing_styles = false;
};
}
protected override void OnRealized ()
{
WidgetFlags |= WidgetFlags.NoWindow;
GdkWindow = Parent.GdkWindow;
base.OnRealized ();
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (State == StateType.Selected) {
Gtk.Style.PaintFlatBox (Style, evnt.Window, State, ShadowType.None, evnt.Area,
this, "cell_odd", Allocation.X, Allocation.Y,
Allocation.Width, Allocation.Height - (last ? 0 : 1));
}
if (!last) {
Gtk.Style.PaintHline (Style, evnt.Window, StateType.Normal, evnt.Area, this, null,
Allocation.X, Allocation.Right, Allocation.Bottom - 1);
}
return base.OnExposeEvent (evnt);
}
private void OnActivateClicked (object o, EventArgs args)
{
addin.Enabled = !addin.Enabled;
ActiveChanged (this, EventArgs.Empty);
}
private void OnDetailsClicked (object o, EventArgs args)
{
AddinDetailsDialog dialog = new AddinDetailsDialog (addin, Toplevel as Window);
dialog.Run ();
dialog.Destroy ();
}
public void UpdateState ()
{
bool enabled = addin.Enabled;
bool sensitive = enabled || (!enabled && State == StateType.Selected);
title.Sensitive = sensitive;
description.Sensitive = sensitive;
description.Wrap = State == StateType.Selected;
authors.Visible = State == StateType.Selected;
((Label)activate_button.Child).Text = enabled
? Catalog.GetString ("Disable")
: Catalog.GetString ("Enable");
}
public void Select (bool select)
{
State = select ? StateType.Selected : StateType.Normal;
if (select) {
button_box.ShowAll ();
} else {
button_box.Hide ();
}
button_box.State = StateType.Normal;
UpdateState ();
QueueResize ();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.Globalization;
namespace System.Data.OleDb
{
public sealed class OleDbCommandBuilder : DbCommandBuilder
{
public OleDbCommandBuilder() : base()
{
GC.SuppressFinalize(this);
}
public OleDbCommandBuilder(OleDbDataAdapter adapter) : this()
{
DataAdapter = adapter;
}
[DefaultValue(null)]
new public OleDbDataAdapter DataAdapter
{
get
{
return (base.DataAdapter as OleDbDataAdapter);
}
set
{
base.DataAdapter = value;
}
}
private void OleDbRowUpdatingHandler(object sender, OleDbRowUpdatingEventArgs ruevent)
{
RowUpdatingHandler(ruevent);
}
new public OleDbCommand GetInsertCommand()
{
return (OleDbCommand)base.GetInsertCommand();
}
new public OleDbCommand GetInsertCommand(bool useColumnsForParameterNames)
{
return (OleDbCommand)base.GetInsertCommand(useColumnsForParameterNames);
}
new public OleDbCommand GetUpdateCommand()
{
return (OleDbCommand)base.GetUpdateCommand();
}
new public OleDbCommand GetUpdateCommand(bool useColumnsForParameterNames)
{
return (OleDbCommand)base.GetUpdateCommand(useColumnsForParameterNames);
}
new public OleDbCommand GetDeleteCommand()
{
return (OleDbCommand)base.GetDeleteCommand();
}
new public OleDbCommand GetDeleteCommand(bool useColumnsForParameterNames)
{
return (OleDbCommand)base.GetDeleteCommand(useColumnsForParameterNames);
}
override protected string GetParameterName(int parameterOrdinal)
{
return "p" + parameterOrdinal.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
override protected string GetParameterName(string parameterName)
{
return parameterName;
}
override protected string GetParameterPlaceholder(int parameterOrdinal)
{
return "?";
}
override protected void ApplyParameterInfo(DbParameter parameter, DataRow datarow, StatementType statementType, bool whereClause)
{
OleDbParameter p = (OleDbParameter)parameter;
object valueType = datarow[SchemaTableColumn.ProviderType];
p.OleDbType = (OleDbType)valueType;
object bvalue = datarow[SchemaTableColumn.NumericPrecision];
if (DBNull.Value != bvalue)
{
byte bval = (byte)(short)bvalue;
p.PrecisionInternal = ((0xff != bval) ? bval : (byte)0);
}
bvalue = datarow[SchemaTableColumn.NumericScale];
if (DBNull.Value != bvalue)
{
byte bval = (byte)(short)bvalue;
p.ScaleInternal = ((0xff != bval) ? bval : (byte)0);
}
}
static public void DeriveParameters(OleDbCommand command)
{
if (null == command)
{
throw ADP.ArgumentNull("command");
}
switch (command.CommandType)
{
case System.Data.CommandType.Text:
throw ADP.DeriveParametersNotSupported(command);
case System.Data.CommandType.StoredProcedure:
break;
case System.Data.CommandType.TableDirect:
// CommandType.TableDirect - do nothing, parameters are not supported
throw ADP.DeriveParametersNotSupported(command);
default:
throw ADP.InvalidCommandType(command.CommandType);
}
if (ADP.IsEmpty(command.CommandText))
{
throw ADP.CommandTextRequired(ADP.DeriveParameters);
}
OleDbConnection connection = command.Connection;
if (null == connection)
{
throw ADP.ConnectionRequired(ADP.DeriveParameters);
}
ConnectionState state = connection.State;
if (ConnectionState.Open != state)
{
throw ADP.OpenConnectionRequired(ADP.DeriveParameters, state);
}
OleDbParameter[] list = DeriveParametersFromStoredProcedure(connection, command);
OleDbParameterCollection parameters = command.Parameters;
parameters.Clear();
for (int i = 0; i < list.Length; ++i)
{
parameters.Add(list[i]);
}
}
// known difference: when getting the parameters for a sproc, the
// return value gets marked as a return value but for a sql stmt
// the return value gets marked as an output parameter.
static private OleDbParameter[] DeriveParametersFromStoredProcedure(OleDbConnection connection, OleDbCommand command)
{
OleDbParameter[] plist = new OleDbParameter[0];
if (connection.SupportSchemaRowset(OleDbSchemaGuid.Procedure_Parameters))
{
string quotePrefix, quoteSuffix;
connection.GetLiteralQuotes(ADP.DeriveParameters, out quotePrefix, out quoteSuffix);
Object[] parsed = MultipartIdentifier.ParseMultipartIdentifier(command.CommandText, quotePrefix, quoteSuffix, '.', 4, true, SR.OLEDB_OLEDBCommandText, false);
if (null == parsed[3])
{
throw ADP.NoStoredProcedureExists(command.CommandText);
}
Object[] restrictions = new object[4];
object value;
// Parse returns an enforced 4 part array
// 0) Server - ignored but removal would be a run-time breaking change from V1.0
// 1) Catalog
// 2) Schema
// 3) ProcedureName
// Restrictions array which is passed to OleDb API expects:
// 0) Catalog
// 1) Schema
// 2) ProcedureName
// 3) ParameterName (leave null)
// Copy from Parse format to OleDb API format
Array.Copy(parsed, 1, restrictions, 0, 3);
//if (cmdConnection.IsServer_msdaora) {
// restrictions[1] = Convert.ToString(cmdConnection.UserId).ToUpper();
//}
DataTable table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedure_Parameters, restrictions);
if (null != table)
{
DataColumnCollection columns = table.Columns;
DataColumn parameterName = null;
DataColumn parameterDirection = null;
DataColumn dataType = null;
DataColumn maxLen = null;
DataColumn numericPrecision = null;
DataColumn numericScale = null;
DataColumn backendtype = null;
int index = columns.IndexOf(ODB.PARAMETER_NAME);
if (-1 != index)
parameterName = columns[index];
index = columns.IndexOf(ODB.PARAMETER_TYPE);
if (-1 != index)
parameterDirection = columns[index];
index = columns.IndexOf(ODB.DATA_TYPE);
if (-1 != index)
dataType = columns[index];
index = columns.IndexOf(ODB.CHARACTER_MAXIMUM_LENGTH);
if (-1 != index)
maxLen = columns[index];
index = columns.IndexOf(ODB.NUMERIC_PRECISION);
if (-1 != index)
numericPrecision = columns[index];
index = columns.IndexOf(ODB.NUMERIC_SCALE);
if (-1 != index)
numericScale = columns[index];
index = columns.IndexOf(ODB.TYPE_NAME);
if (-1 != index)
backendtype = columns[index];
DataRow[] dataRows = table.Select(null, ODB.ORDINAL_POSITION_ASC, DataViewRowState.CurrentRows);
plist = new OleDbParameter[dataRows.Length];
for (index = 0; index < dataRows.Length; ++index)
{
DataRow dataRow = dataRows[index];
OleDbParameter parameter = new OleDbParameter();
if ((null != parameterName) && !dataRow.IsNull(parameterName, DataRowVersion.Default))
{
// $CONSIDER - not trimming the @ from the beginning but to left the designer do that
parameter.ParameterName = Convert.ToString(dataRow[parameterName, DataRowVersion.Default], CultureInfo.InvariantCulture).TrimStart(new char[] { '@', ' ', ':' });
}
if ((null != parameterDirection) && !dataRow.IsNull(parameterDirection, DataRowVersion.Default))
{
short direction = Convert.ToInt16(dataRow[parameterDirection, DataRowVersion.Default], CultureInfo.InvariantCulture);
parameter.Direction = ConvertToParameterDirection(direction);
}
if ((null != dataType) && !dataRow.IsNull(dataType, DataRowVersion.Default))
{
// need to ping FromDBType, otherwise WChar->WChar when the user really wants VarWChar
short wType = Convert.ToInt16(dataRow[dataType, DataRowVersion.Default], CultureInfo.InvariantCulture);
parameter.OleDbType = NativeDBType.FromDBType(wType, false, false).enumOleDbType;
}
if ((null != maxLen) && !dataRow.IsNull(maxLen, DataRowVersion.Default))
{
parameter.Size = Convert.ToInt32(dataRow[maxLen, DataRowVersion.Default], CultureInfo.InvariantCulture);
}
switch (parameter.OleDbType)
{
case OleDbType.Decimal:
case OleDbType.Numeric:
case OleDbType.VarNumeric:
if ((null != numericPrecision) && !dataRow.IsNull(numericPrecision, DataRowVersion.Default))
{
// @devnote: unguarded cast from Int16 to Byte
parameter.PrecisionInternal = (Byte)Convert.ToInt16(dataRow[numericPrecision], CultureInfo.InvariantCulture);
}
if ((null != numericScale) && !dataRow.IsNull(numericScale, DataRowVersion.Default))
{
// @devnote: unguarded cast from Int16 to Byte
parameter.ScaleInternal = (Byte)Convert.ToInt16(dataRow[numericScale], CultureInfo.InvariantCulture);
}
break;
case OleDbType.VarBinary:
case OleDbType.VarChar:
case OleDbType.VarWChar:
value = dataRow[backendtype, DataRowVersion.Default];
if (value is string)
{
string backendtypename = ((string)value).ToLower(CultureInfo.InvariantCulture);
switch (backendtypename)
{
case "binary":
parameter.OleDbType = OleDbType.Binary;
break;
//case "varbinary":
// parameter.OleDbType = OleDbType.VarBinary;
// break;
case "image":
parameter.OleDbType = OleDbType.LongVarBinary;
break;
case "char":
parameter.OleDbType = OleDbType.Char;
break;
//case "varchar":
//case "varchar2":
// parameter.OleDbType = OleDbType.VarChar;
// break;
case "text":
parameter.OleDbType = OleDbType.LongVarChar;
break;
case "nchar":
parameter.OleDbType = OleDbType.WChar;
break;
//case "nvarchar":
// parameter.OleDbType = OleDbType.VarWChar;
case "ntext":
parameter.OleDbType = OleDbType.LongVarWChar;
break;
}
}
break;
}
//if (AdapterSwitches.OleDbSql.TraceVerbose) {
// ADP.Trace_Parameter("StoredProcedure", parameter);
//}
plist[index] = parameter;
}
}
if ((0 == plist.Length) && connection.SupportSchemaRowset(OleDbSchemaGuid.Procedures))
{
restrictions = new Object[4] { null, null, command.CommandText, null };
table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions);
if (0 == table.Rows.Count)
{
throw ADP.NoStoredProcedureExists(command.CommandText);
}
}
}
else if (connection.SupportSchemaRowset(OleDbSchemaGuid.Procedures))
{
Object[] restrictions = new Object[4] { null, null, command.CommandText, null };
DataTable table = connection.GetSchemaRowset(OleDbSchemaGuid.Procedures, restrictions);
if (0 == table.Rows.Count)
{
throw ADP.NoStoredProcedureExists(command.CommandText);
}
// we don't ever expect a procedure with 0 parameters, they should have at least a return value
throw ODB.NoProviderSupportForSProcResetParameters(connection.Provider);
}
else
{
throw ODB.NoProviderSupportForSProcResetParameters(connection.Provider);
}
return plist;
}
static private ParameterDirection ConvertToParameterDirection(int value)
{
switch (value)
{
case ODB.DBPARAMTYPE_INPUT:
return System.Data.ParameterDirection.Input;
case ODB.DBPARAMTYPE_INPUTOUTPUT:
return System.Data.ParameterDirection.InputOutput;
case ODB.DBPARAMTYPE_OUTPUT:
return System.Data.ParameterDirection.Output;
case ODB.DBPARAMTYPE_RETURNVALUE:
return System.Data.ParameterDirection.ReturnValue;
default:
return System.Data.ParameterDirection.Input;
}
}
public override string QuoteIdentifier(string unquotedIdentifier)
{
return QuoteIdentifier(unquotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */);
}
public string QuoteIdentifier(string unquotedIdentifier, OleDbConnection connection)
{
ADP.CheckArgumentNull(unquotedIdentifier, "unquotedIdentifier");
// if the user has specificed a prefix use the user specified prefix and suffix
// otherwise get them from the provider
string quotePrefix = QuotePrefix;
string quoteSuffix = QuoteSuffix;
if (ADP.IsEmpty(quotePrefix) == true)
{
if (connection == null)
{
// Use the adapter's connection if QuoteIdentifier was called from
// DbCommandBuilder instance (which does not have an overload that gets connection object)
connection = DataAdapter?.SelectCommand?.Connection;
if (connection == null)
{
throw ADP.QuotePrefixNotSet(ADP.QuoteIdentifier);
}
}
connection.GetLiteralQuotes(ADP.QuoteIdentifier, out quotePrefix, out quoteSuffix);
// if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec
// IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.)
if (quoteSuffix == null)
{
quoteSuffix = quotePrefix;
}
}
return ADP.BuildQuotedString(quotePrefix, quoteSuffix, unquotedIdentifier);
}
override protected void SetRowUpdatingHandler(DbDataAdapter adapter)
{
Debug.Assert(adapter is OleDbDataAdapter, "!OleDbDataAdapter");
if (adapter == base.DataAdapter)
{ // removal case
((OleDbDataAdapter)adapter).RowUpdating -= OleDbRowUpdatingHandler;
}
else
{ // adding case
((OleDbDataAdapter)adapter).RowUpdating += OleDbRowUpdatingHandler;
}
}
public override string UnquoteIdentifier(string quotedIdentifier)
{
return UnquoteIdentifier(quotedIdentifier, null /* use DataAdapter.SelectCommand.Connection if available */);
}
public string UnquoteIdentifier(string quotedIdentifier, OleDbConnection connection)
{
ADP.CheckArgumentNull(quotedIdentifier, "quotedIdentifier");
// if the user has specificed a prefix use the user specified prefix and suffix
// otherwise get them from the provider
string quotePrefix = QuotePrefix;
string quoteSuffix = QuoteSuffix;
if (ADP.IsEmpty(quotePrefix) == true)
{
if (connection == null)
{
// Use the adapter's connection if UnquoteIdentifier was called from
// DbCommandBuilder instance (which does not have an overload that gets connection object)
connection = DataAdapter?.SelectCommand?.Connection;
if (connection == null)
{
throw ADP.QuotePrefixNotSet(ADP.UnquoteIdentifier);
}
}
connection.GetLiteralQuotes(ADP.UnquoteIdentifier, out quotePrefix, out quoteSuffix);
// if the quote suffix is null assume that it is the same as the prefix (See OLEDB spec
// IDBInfo::GetLiteralInfo DBLITERAL_QUOTE_SUFFIX.)
if (quoteSuffix == null)
{
quoteSuffix = quotePrefix;
}
}
String unquotedIdentifier;
// ignoring the return value because it is acceptable for the quotedString to not be quoted in this
// context.
ADP.RemoveStringQuotes(quotePrefix, quoteSuffix, quotedIdentifier, out unquotedIdentifier);
return unquotedIdentifier;
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="FormatterLocator.cs" company="Sirenix IVS">
// Copyright (c) 2018 Sirenix IVS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-----------------------------------------------------------------------
namespace Stratus.OdinSerializer
{
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using Utilities;
/// <summary>
/// Utility class for locating and caching formatters for all non-primitive types.
/// </summary>
#if UNITY_EDITOR
[UnityEditor.InitializeOnLoad]
#endif
public static class FormatterLocator
{
private static readonly object LOCK = new object();
private static readonly Dictionary<Type, IFormatter> FormatterInstances = new Dictionary<Type, IFormatter>(FastTypeComparer.Instance);
private static readonly DoubleLookupDictionary<Type, ISerializationPolicy, IFormatter> TypeFormatterMap = new DoubleLookupDictionary<Type, ISerializationPolicy, IFormatter>(FastTypeComparer.Instance, ReferenceEqualityComparer<ISerializationPolicy>.Default);
private struct FormatterInfo
{
public Type FormatterType;
public Type TargetType;
public bool AskIfCanFormatTypes;
public int Priority;
}
private struct FormatterLocatorInfo
{
public IFormatterLocator LocatorInstance;
public int Priority;
}
private static readonly List<FormatterLocatorInfo> FormatterLocators = new List<FormatterLocatorInfo>();
private static readonly List<FormatterInfo> FormatterInfos = new List<FormatterInfo>();
#if UNITY_EDITOR
/// <summary>
/// Editor-only event that fires whenever an emittable formatter has been located.
/// This event is used by the AOT formatter pre-emitter to locate types that need to have formatters pre-emitted.
/// </summary>
public static event Action<Type> OnLocatedEmittableFormatterForType;
/// <summary>
/// Editor-only event that fires whenever a formatter has been located.
/// </summary>
public static event Action<IFormatter> OnLocatedFormatter;
#endif
static FormatterLocator()
{
foreach (var ass in AppDomain.CurrentDomain.GetAssemblies())
{
try
{
var name = ass.GetName().Name;
if (name.StartsWith("System.") || name.StartsWith("UnityEngine") || name.StartsWith("UnityEditor") || name == "mscorlib")
{
// Filter out various core .NET libraries and Unity engine assemblies
continue;
}
else if (ass.GetName().Name == FormatterEmitter.PRE_EMITTED_ASSEMBLY_NAME || ass.IsDefined(typeof(EmittedAssemblyAttribute), true))
{
// Only include pre-emitted formatters if we are on an AOT platform.
// Pre-emitted formatters will not work in newer .NET runtimes due to
// lacking private member access privileges, but when compiled via
// IL2CPP they work fine.
#if UNITY_EDITOR
continue;
#else
if (EmitUtilities.CanEmit)
{
// Never include pre-emitted formatters if we can emit on the current platform
continue;
}
#endif
}
foreach (var attrUncast in ass.SafeGetCustomAttributes(typeof(RegisterFormatterAttribute), true))
{
var attr = (RegisterFormatterAttribute)attrUncast;
if (!attr.FormatterType.IsClass
|| attr.FormatterType.IsAbstract
|| attr.FormatterType.GetConstructor(Type.EmptyTypes) == null
|| !attr.FormatterType.ImplementsOpenGenericInterface(typeof(IFormatter<>)))
{
continue;
}
FormatterInfos.Add(new FormatterInfo()
{
FormatterType = attr.FormatterType,
TargetType = attr.FormatterType.GetArgumentsOfInheritedOpenGenericInterface(typeof(IFormatter<>))[0],
AskIfCanFormatTypes = typeof(IAskIfCanFormatTypes).IsAssignableFrom(attr.FormatterType),
Priority = attr.Priority
});
}
foreach (var attrUncast in ass.SafeGetCustomAttributes(typeof(RegisterFormatterLocatorAttribute), true))
{
var attr = (RegisterFormatterLocatorAttribute)attrUncast;
if (!attr.FormatterLocatorType.IsClass
|| attr.FormatterLocatorType.IsAbstract
|| attr.FormatterLocatorType.GetConstructor(Type.EmptyTypes) == null
|| !typeof(IFormatterLocator).IsAssignableFrom(attr.FormatterLocatorType))
{
continue;
}
try
{
FormatterLocators.Add(new FormatterLocatorInfo()
{
LocatorInstance = (IFormatterLocator)Activator.CreateInstance(attr.FormatterLocatorType),
Priority = attr.Priority
});
}
catch (Exception ex)
{
Debug.LogException(new Exception("Exception was thrown while instantiating FormatterLocator of type " + attr.FormatterLocatorType.FullName + ".", ex));
}
}
}
catch (TypeLoadException)
{
if (ass.GetName().Name == "OdinSerializer")
{
Debug.LogError("A TypeLoadException occurred when FormatterLocator tried to load types from assembly '" + ass.FullName + "'. No serialization formatters in this assembly will be found. Serialization will be utterly broken.");
}
}
catch (ReflectionTypeLoadException)
{
if (ass.GetName().Name == "OdinSerializer")
{
Debug.LogError("A ReflectionTypeLoadException occurred when FormatterLocator tried to load types from assembly '" + ass.FullName + "'. No serialization formatters in this assembly will be found. Serialization will be utterly broken.");
}
}
catch (MissingMemberException)
{
if (ass.GetName().Name == "OdinSerializer")
{
Debug.LogError("A ReflectionTypeLoadException occurred when FormatterLocator tried to load types from assembly '" + ass.FullName + "'. No serialization formatters in this assembly will be found. Serialization will be utterly broken.");
}
}
}
// Order formatters and formatter locators by priority and then by name, to ensure consistency regardless of the order of loaded types, which is important for cross-platform cases.
FormatterInfos.Sort((a, b) =>
{
int compare = -a.Priority.CompareTo(b.Priority);
if (compare == 0)
{
compare = a.FormatterType.Name.CompareTo(b.FormatterType.Name);
}
return compare;
});
FormatterLocators.Sort((a, b) =>
{
int compare = -a.Priority.CompareTo(b.Priority);
if (compare == 0)
{
compare = a.LocatorInstance.GetType().Name.CompareTo(b.LocatorInstance.GetType().Name);
}
return compare;
});
}
/// <summary>
/// This event is invoked before everything else when a formatter is being resolved for a given type. If any invoked delegate returns a valid formatter, that formatter is used and the resolve process stops there.
/// <para />
/// This can be used to hook into and extend the serialization system's formatter resolution logic.
/// </summary>
[Obsolete("Use the new IFormatterLocator interface instead, and register your custom locator with the RegisterFormatterLocator assembly attribute.", true)]
public static event Func<Type, IFormatter> FormatterResolve
{
add { throw new NotSupportedException(); }
remove { throw new NotSupportedException(); }
}
/// <summary>
/// Gets a formatter for the type <see cref="T" />.
/// </summary>
/// <typeparam name="T">The type to get a formatter for.</typeparam>
/// <param name="policy">The serialization policy to use if a formatter has to be emitted. If null, <see cref="SerializationPolicies.Strict"/> is used.</param>
/// <returns>
/// A formatter for the type <see cref="T" />.
/// </returns>
public static IFormatter<T> GetFormatter<T>(ISerializationPolicy policy)
{
return (IFormatter<T>)GetFormatter(typeof(T), policy);
}
/// <summary>
/// Gets a formatter for a given type.
/// </summary>
/// <param name="type">The type to get a formatter for.</param>
/// <param name="policy">The serialization policy to use if a formatter has to be emitted. If null, <see cref="SerializationPolicies.Strict"/> is used.</param>
/// <returns>
/// A formatter for the given type.
/// </returns>
/// <exception cref="System.ArgumentNullException">The type argument is null.</exception>
public static IFormatter GetFormatter(Type type, ISerializationPolicy policy)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (policy == null)
{
policy = SerializationPolicies.Strict;
}
IFormatter result;
lock (LOCK)
{
if (TypeFormatterMap.TryGetInnerValue(type, policy, out result) == false)
{
// System.ExecutionEngineException is marked obsolete in .NET 4.6.
// That's all very good for .NET, but Unity still uses it, and that means we use it as well!
#pragma warning disable 618
try
{
result = CreateFormatter(type, policy);
}
catch (TargetInvocationException ex)
{
if (ex.GetBaseException() is ExecutionEngineException)
{
LogAOTError(type, ex.GetBaseException() as ExecutionEngineException);
}
else
{
throw ex;
}
}
catch (TypeInitializationException ex)
{
if (ex.GetBaseException() is ExecutionEngineException)
{
LogAOTError(type, ex.GetBaseException() as ExecutionEngineException);
}
else
{
throw ex;
}
}
catch (ExecutionEngineException ex)
{
LogAOTError(type, ex);
}
TypeFormatterMap.AddInner(type, policy, result);
#pragma warning restore 618
}
}
#if UNITY_EDITOR
if (OnLocatedFormatter != null)
{
OnLocatedFormatter(result);
}
if (OnLocatedEmittableFormatterForType != null && result.GetType().IsGenericType)
{
#if CAN_EMIT
if (result.GetType().GetGenericTypeDefinition() == typeof(FormatterEmitter.RuntimeEmittedFormatter<>))
{
OnLocatedEmittableFormatterForType(type);
}
else
#endif
if (result.GetType().GetGenericTypeDefinition() == typeof(ReflectionFormatter<>))
{
OnLocatedEmittableFormatterForType(type);
}
}
#endif
return result;
}
private static void LogAOTError(Type type, Exception ex)
{
var types = new List<string>(GetAllPossibleMissingAOTTypes(type)).ToArray();
Debug.LogError("Creating a serialization formatter for the type '" + type.GetNiceFullName() + "' failed due to missing AOT support. \n\n" +
" Please use Odin's AOT generation feature to generate an AOT dll before building, and MAKE SURE that all of the following " +
"types were automatically added to the supported types list after a scan (if they were not, please REPORT AN ISSUE with the details of which exact types the scan is missing " +
"and ADD THEM MANUALLY): \n\n" + string.Join("\n", types) + "\n\nIF ALL THE TYPES ARE IN THE SUPPORT LIST AND YOU STILL GET THIS ERROR, PLEASE REPORT AN ISSUE." +
"The exception contained the following message: \n" + ex.Message);
throw new SerializationAbortException("AOT formatter support was missing for type '" + type.GetNiceFullName() + "'.");
}
private static IEnumerable<string> GetAllPossibleMissingAOTTypes(Type type)
{
yield return type.GetNiceFullName() + " (name string: '" + TwoWaySerializationBinder.Default.BindToName(type) + "')";
if (!type.IsGenericType) yield break;
foreach (var arg in type.GetGenericArguments())
{
yield return arg.GetNiceFullName() + " (name string: '" + TwoWaySerializationBinder.Default.BindToName(arg) + "')";
if (arg.IsGenericType)
{
foreach (var subArg in GetAllPossibleMissingAOTTypes(arg))
{
yield return subArg;
}
}
}
}
internal static List<IFormatter> GetAllCompatiblePredefinedFormatters(Type type, ISerializationPolicy policy)
{
if (FormatterUtilities.IsPrimitiveType(type))
{
throw new ArgumentException("Cannot create formatters for a primitive type like " + type.Name);
}
List<IFormatter> formatters = new List<IFormatter>();
// First call formatter locators before checking for registered formatters
for (int i = 0; i < FormatterLocators.Count; i++)
{
try
{
IFormatter result;
if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.BeforeRegisteredFormatters, policy, out result))
{
formatters.Add(result);
}
}
catch (TargetInvocationException ex)
{
throw ex;
}
catch (TypeInitializationException ex)
{
throw ex;
}
#pragma warning disable CS0618 // Type or member is obsolete
catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
{
throw ex;
}
catch (Exception ex)
{
Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
}
}
// Then check for valid registered formatters
for (int i = 0; i < FormatterInfos.Count; i++)
{
var info = FormatterInfos[i];
Type formatterType = null;
if (type == info.TargetType)
{
formatterType = info.FormatterType;
}
else if (info.FormatterType.IsGenericType && info.TargetType.IsGenericParameter)
{
Type[] inferredArgs;
if (info.FormatterType.TryInferGenericParameters(out inferredArgs, type))
{
formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(inferredArgs);
}
}
else if (type.IsGenericType && info.FormatterType.IsGenericType && info.TargetType.IsGenericType && type.GetGenericTypeDefinition() == info.TargetType.GetGenericTypeDefinition())
{
Type[] args = type.GetGenericArguments();
if (info.FormatterType.AreGenericConstraintsSatisfiedBy(args))
{
formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(args);
}
}
if (formatterType != null)
{
var instance = GetFormatterInstance(formatterType);
if (instance == null) continue;
if (info.AskIfCanFormatTypes && !((IAskIfCanFormatTypes)instance).CanFormatType(type))
{
continue;
}
formatters.Add(instance);
}
}
// Then call formatter locators after checking for registered formatters
for (int i = 0; i < FormatterLocators.Count; i++)
{
try
{
IFormatter result;
if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.AfterRegisteredFormatters, policy, out result))
{
formatters.Add(result);
}
}
catch (TargetInvocationException ex)
{
throw ex;
}
catch (TypeInitializationException ex)
{
throw ex;
}
#pragma warning disable CS0618 // Type or member is obsolete
catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
{
throw ex;
}
catch (Exception ex)
{
Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
}
}
formatters.Add((IFormatter)Activator.CreateInstance(typeof(ReflectionFormatter<>).MakeGenericType(type)));
return formatters;
}
private static IFormatter CreateFormatter(Type type, ISerializationPolicy policy)
{
if (FormatterUtilities.IsPrimitiveType(type))
{
throw new ArgumentException("Cannot create formatters for a primitive type like " + type.Name);
}
// First call formatter locators before checking for registered formatters
for (int i = 0; i < FormatterLocators.Count; i++)
{
try
{
IFormatter result;
if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.BeforeRegisteredFormatters, policy, out result))
{
return result;
}
}
catch (TargetInvocationException ex)
{
throw ex;
}
catch (TypeInitializationException ex)
{
throw ex;
}
#pragma warning disable CS0618 // Type or member is obsolete
catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
{
throw ex;
}
catch (Exception ex)
{
Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
}
}
// Then check for valid registered formatters
for (int i = 0; i < FormatterInfos.Count; i++)
{
var info = FormatterInfos[i];
Type formatterType = null;
if (type == info.TargetType)
{
formatterType = info.FormatterType;
}
else if (info.FormatterType.IsGenericType && info.TargetType.IsGenericParameter)
{
Type[] inferredArgs;
if (info.FormatterType.TryInferGenericParameters(out inferredArgs, type))
{
formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(inferredArgs);
}
}
else if (type.IsGenericType && info.FormatterType.IsGenericType && info.TargetType.IsGenericType && type.GetGenericTypeDefinition() == info.TargetType.GetGenericTypeDefinition())
{
Type[] args = type.GetGenericArguments();
if (info.FormatterType.AreGenericConstraintsSatisfiedBy(args))
{
formatterType = info.FormatterType.GetGenericTypeDefinition().MakeGenericType(args);
}
}
if (formatterType != null)
{
var instance = GetFormatterInstance(formatterType);
if (instance == null) continue;
if (info.AskIfCanFormatTypes && !((IAskIfCanFormatTypes)instance).CanFormatType(type))
{
continue;
}
return instance;
}
}
// Then call formatter locators after checking for registered formatters
for (int i = 0; i < FormatterLocators.Count; i++)
{
try
{
IFormatter result;
if (FormatterLocators[i].LocatorInstance.TryGetFormatter(type, FormatterLocationStep.AfterRegisteredFormatters, policy, out result))
{
return result;
}
}
catch (TargetInvocationException ex)
{
throw ex;
}
catch (TypeInitializationException ex)
{
throw ex;
}
#pragma warning disable CS0618 // Type or member is obsolete
catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
{
throw ex;
}
catch (Exception ex)
{
Debug.LogException(new Exception("Exception was thrown while calling FormatterLocator " + FormatterLocators[i].GetType().FullName + ".", ex));
}
}
// If we can, emit a formatter to handle serialization of this object
{
if (EmitUtilities.CanEmit)
{
var result = FormatterEmitter.GetEmittedFormatter(type, policy);
if (result != null) return result;
}
}
if (EmitUtilities.CanEmit)
{
Debug.LogWarning("Fallback to reflection for type " + type.Name + " when emit is possible on this platform.");
}
// Finally, we fall back to a reflection-based formatter if nothing else has been found
return (IFormatter)Activator.CreateInstance(typeof(ReflectionFormatter<>).MakeGenericType(type));
}
private static IFormatter GetFormatterInstance(Type type)
{
IFormatter formatter;
if (!FormatterInstances.TryGetValue(type, out formatter))
{
try
{
formatter = (IFormatter)Activator.CreateInstance(type);
FormatterInstances.Add(type, formatter);
}
catch (TargetInvocationException ex)
{
throw ex;
}
catch (TypeInitializationException ex)
{
throw ex;
}
#pragma warning disable CS0618 // Type or member is obsolete
catch (ExecutionEngineException ex)
#pragma warning restore CS0618 // Type or member is obsolete
{
throw ex;
}
catch (Exception ex)
{
Debug.LogException(new Exception("Exception was thrown while instantiating formatter '" + type.GetNiceFullName() + "'.", ex));
}
}
return formatter;
}
}
}
| |
// Amplify Shader Editor - Visual Shader Editing Tool
// Copyright (c) Amplify Creations, Lda <info@amplify.pt>
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.Collections.Generic;
using System.Reflection;
namespace AmplifyShaderEditor
{
public class ShortcutKeyData
{
public bool IsPressed;
public System.Type NodeType;
public string Name;
public ShortcutKeyData( System.Type type, string name )
{
NodeType = type;
Name = name;
IsPressed = false;
}
}
public class GraphContextMenu
{
private List<ContextMenuItem> m_items;
private List<ContextMenuItem> m_itemFunctions;
private Dictionary<System.Type, NodeAttributes> m_itemsDict;
private Dictionary<System.Type, NodeAttributes> m_deprecatedItemsDict;
private Dictionary<System.Type, System.Type> m_castTypes;
private Dictionary<KeyCode, ShortcutKeyData> m_shortcutTypes;
private KeyCode m_lastKeyPressed;
private ParentGraph m_currentGraph;
private bool m_correctlyLoaded = false;
public GraphContextMenu( ParentGraph currentGraph )
{
m_currentGraph = currentGraph;
m_correctlyLoaded = RefreshNodes( currentGraph );
}
public bool RefreshNodes( ParentGraph currentGraph )
{
if ( m_items != null )
{
m_items.Clear();
m_items = null;
}
if ( m_itemFunctions != null )
{
m_itemFunctions.Clear();
m_itemFunctions = null;
}
m_items = new List<ContextMenuItem>();
m_itemFunctions = new List<ContextMenuItem>();
if ( m_itemsDict != null )
m_itemsDict.Clear();
m_itemsDict = new Dictionary<System.Type, NodeAttributes>();
if ( m_deprecatedItemsDict != null )
m_deprecatedItemsDict.Clear();
m_deprecatedItemsDict = new Dictionary<System.Type, NodeAttributes>();
if ( m_castTypes != null )
m_castTypes.Clear();
m_castTypes = new Dictionary<System.Type, System.Type>();
if ( m_shortcutTypes != null )
m_shortcutTypes.Clear();
m_shortcutTypes = new Dictionary<KeyCode, ShortcutKeyData>();
m_lastKeyPressed = KeyCode.None;
// Fetch all available nodes by their attributes
try
{
IEnumerable<System.Type> availableTypes = AppDomain.CurrentDomain.GetAssemblies().ToList().SelectMany( type => type.GetTypes() );
foreach ( System.Type type in availableTypes )
{
foreach ( NodeAttributes attribute in Attribute.GetCustomAttributes( type ).OfType<NodeAttributes>() )
{
if ( attribute.Available && !attribute.Deprecated )
{
//if ( !UIUtils.CurrentWindow.IsShaderFunctionWindow && attribute.AvailableInFunctionsOnly )
// continue;
if ( !UIUtils.HasColorCategory( attribute.Category ) )
{
if ( !String.IsNullOrEmpty( attribute.CustomCategoryColor ) )
{
try
{
Color color = new Color();
ColorUtility.TryParseHtmlString( attribute.CustomCategoryColor, out color );
UIUtils.AddColorCategory( attribute.Category, color );
}
catch ( Exception e )
{
Debug.LogException( e );
UIUtils.AddColorCategory( attribute.Category, Constants.DefaultCategoryColor );
}
}
else
{
UIUtils.AddColorCategory( attribute.Category, Constants.DefaultCategoryColor );
}
}
if ( attribute.CastType != null && attribute.CastType.Length > 0 && type != null )
{
for ( int i = 0; i < attribute.CastType.Length; i++ )
{
m_castTypes.Add( attribute.CastType[ i ], type );
}
}
if ( attribute.ShortcutKey != KeyCode.None && type != null )
m_shortcutTypes.Add( attribute.ShortcutKey, new ShortcutKeyData( type, attribute.Name ) );
ContextMenuItem newItem = new ContextMenuItem( attribute, type, attribute.Name, attribute.Category, attribute.Description, null, attribute.ShortcutKey );
if ( UIUtils.GetNodeAvailabilityInBitArray( attribute.NodeAvailabilityFlags, NodeAvailability.SurfaceShader ) )
m_items.Add( newItem );
else if ( UIUtils.GetNodeAvailabilityInBitArray( attribute.NodeAvailabilityFlags, currentGraph.ParentWindow.CurrentNodeAvailability ) )
m_items.Add( newItem );
m_itemsDict.Add( type, attribute );
m_itemFunctions.Add( newItem );
}
else
{
m_deprecatedItemsDict.Add( type, attribute );
}
}
}
}
catch ( ReflectionTypeLoadException exception )
{
Debug.LogException( exception );
return false;
}
string[] guids = AssetDatabase.FindAssets( "t:AmplifyShaderFunction" );
List<AmplifyShaderFunction> allFunctions = new List<AmplifyShaderFunction>();
for ( int i = 0; i < guids.Length; i++ )
{
allFunctions.Add( AssetDatabase.LoadAssetAtPath<AmplifyShaderFunction>( AssetDatabase.GUIDToAssetPath( guids[ i ] ) ) );
}
int functionCount = allFunctions.Count;
if ( functionCount > 0 )
{
m_castTypes.Add( typeof( AmplifyShaderFunction ), typeof( FunctionNode ) );
}
for ( int i = 0; i < functionCount; i++ )
{
NodeAttributes attribute = new NodeAttributes( allFunctions[ i ].FunctionName, "Functions", allFunctions[ i ].Description, KeyCode.None, true, 0, int.MaxValue, typeof( AmplifyShaderFunction ) );
System.Type type = typeof( FunctionNode );
ContextMenuItem newItem = new ContextMenuItem( attribute, type, attribute.Name, attribute.Category, attribute.Description, allFunctions[ i ], attribute.ShortcutKey );
m_items.Add( newItem );
m_itemFunctions.Add( newItem );
}
//Sort out the final list by name
m_items.Sort( ( x, y ) => x.Category.CompareTo( y.Category ) );
m_itemFunctions.Sort( ( x, y ) => x.Category.CompareTo( y.Category ) );
return true;
}
public void Destroy()
{
for ( int i = 0; i < m_items.Count; i++ )
{
m_items[ i ].Destroy();
}
for ( int i = 0; i < m_itemFunctions.Count; i++ )
{
if ( m_itemFunctions[ i ] != null )
m_itemFunctions[ i ].Destroy();
}
m_items.Clear();
m_items = null;
m_itemFunctions.Clear();
m_itemFunctions = null;
m_itemsDict.Clear();
m_itemsDict = null;
m_deprecatedItemsDict.Clear();
m_deprecatedItemsDict = null;
m_castTypes.Clear();
m_castTypes = null;
m_shortcutTypes.Clear();
m_shortcutTypes = null;
}
public NodeAttributes GetNodeAttributesForType( System.Type type )
{
if ( type == null )
{
Debug.LogError( "Invalid type detected" );
return null;
}
if ( m_itemsDict.ContainsKey( type ) )
return m_itemsDict[ type ];
return null;
}
public NodeAttributes GetDeprecatedNodeAttributesForType( System.Type type )
{
if ( m_deprecatedItemsDict.ContainsKey( type ) )
return m_deprecatedItemsDict[ type ];
return null;
}
public void UpdateKeyPress( KeyCode key )
{
if ( key == KeyCode.None )
return;
m_lastKeyPressed = key;
if ( m_shortcutTypes.ContainsKey( key ) )
{
m_shortcutTypes[ key ].IsPressed = true;
}
}
public void UpdateKeyReleased( KeyCode key )
{
if ( key == KeyCode.None )
return;
if ( m_shortcutTypes.ContainsKey( key ) )
{
m_shortcutTypes[ key ].IsPressed = false;
}
}
public ParentNode CreateNodeFromCastType( System.Type type )
{
if ( m_castTypes.ContainsKey( type ) )
{
ParentNode newNode = ( ParentNode ) ScriptableObject.CreateInstance( m_castTypes[ type ] );
return newNode;
}
return null;
}
public ParentNode CreateNodeFromShortcutKey()
{
if ( m_lastKeyPressed == KeyCode.None )
return null;
if ( m_shortcutTypes.ContainsKey( m_lastKeyPressed ) && m_shortcutTypes[ m_lastKeyPressed ].IsPressed )
{
ParentNode newNode = ( ParentNode ) ScriptableObject.CreateInstance( m_shortcutTypes[ m_lastKeyPressed ].NodeType );
return newNode;
}
return null;
}
public bool CheckShortcutKey()
{
if ( m_lastKeyPressed == KeyCode.None )
return false;
if ( m_shortcutTypes.ContainsKey( m_lastKeyPressed ) && m_shortcutTypes[ m_lastKeyPressed ].IsPressed )
{
return true;
}
return false;
}
public List<ContextMenuItem> MenuItems
{
get
{
if ( m_currentGraph.ParentWindow.IsShaderFunctionWindow )
return m_itemFunctions;
else
return m_items;
}
}
public List<ContextMenuItem> ItemFunctions { get { return m_itemFunctions; } }
public KeyCode LastKeyPressed
{
get { return m_lastKeyPressed; }
}
public Dictionary<KeyCode, ShortcutKeyData> NodeShortcuts { get { return m_shortcutTypes; } }
public bool CorrectlyLoaded { get { return m_correctlyLoaded; } }
}
}
| |
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using NJsonSchema.Generation;
using Xunit;
namespace NJsonSchema.Tests.Generation
{
public class EnumGenerationTests
{
public class Foo
{
public Bar Bar { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public Bar Bar2 { get; set; }
}
/// <summary>
/// Foo bar.
/// </summary>
public enum Bar
{
A = 0,
B = 5,
C = 6,
}
[Fact]
public async Task When_property_is_integer_enum_then_schema_has_enum()
{
//// Arrange
//// Act
var schema = JsonSchema.FromType<Foo>(new JsonSchemaGeneratorSettings
{
DefaultEnumHandling = EnumHandling.Integer,
GenerateEnumMappingDescription = true
});
var data = schema.ToJson();
//// Assert
Assert.Equal(JsonObjectType.Integer, schema.Properties["Bar"].ActualTypeSchema.Type);
Assert.Equal(3, schema.Properties["Bar"].ActualTypeSchema.Enumeration.Count);
Assert.Equal(0, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(0));
Assert.Equal(5, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(1));
Assert.Equal(6, schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(2));
Assert.Contains("Foo bar.", schema.Properties["Bar"].ActualTypeSchema.Description); // option is enabled
Assert.Contains("5 = B", schema.Properties["Bar"].ActualTypeSchema.Description); // option is enabled
}
[Fact]
public async Task When_string_and_integer_enum_used_then_two_refs_are_generated()
{
//// Arrange
//// Act
var schema = JsonSchema.FromType<Foo>(new JsonSchemaGeneratorSettings
{
DefaultEnumHandling = EnumHandling.Integer
});
var data = schema.ToJson();
//// Assert
Assert.NotNull(schema.Properties["Bar"].ActualTypeSchema);
Assert.NotNull(schema.Properties["Bar2"].ActualTypeSchema); // must not be a reference but second enum declaration
Assert.NotEqual(schema.Properties["Bar"].ActualTypeSchema, schema.Properties["Bar2"].ActualTypeSchema);
Assert.DoesNotContain("5 = B", schema.Properties["Bar"].ActualTypeSchema.Description); // option is not enabled
}
[Fact]
public async Task When_property_is_string_enum_then_schema_has_enum()
{
//// Arrange
//// Act
var schema = JsonSchema.FromType<Foo>(new JsonSchemaGeneratorSettings
{
DefaultEnumHandling = EnumHandling.String,
GenerateEnumMappingDescription = true
});
var data = schema.ToJson();
//// Assert
Assert.Equal(JsonObjectType.String, schema.Properties["Bar"].ActualTypeSchema.Type);
Assert.Equal(3, schema.Properties["Bar"].ActualTypeSchema.Enumeration.Count);
Assert.Equal("A", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(0));
Assert.Equal("B", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(1));
Assert.Equal("C", schema.Properties["Bar"].ActualTypeSchema.Enumeration.ElementAt(2));
Assert.DoesNotContain("=", schema.Properties["Bar"].ActualTypeSchema.Description); // string enums do not have mapping in description
}
[Fact]
public async Task When_enum_is_generated_then_names_are_set()
{
//// Arrange
//// Act
var schema = JsonSchema.FromType<Foo>(new JsonSchemaGeneratorSettings
{
DefaultEnumHandling = EnumHandling.Integer
});
//// Assert
Assert.Equal(3, schema.Properties["Bar"].ActualTypeSchema.EnumerationNames.Count);
Assert.Equal("A", schema.Properties["Bar"].ActualTypeSchema.EnumerationNames.ElementAt(0));
Assert.Equal("B", schema.Properties["Bar"].ActualTypeSchema.EnumerationNames.ElementAt(1));
Assert.Equal("C", schema.Properties["Bar"].ActualTypeSchema.EnumerationNames.ElementAt(2));
}
public class EnumProperty
{
[DefaultValue(Bar.C)]
public Bar Bar { get; set; }
}
[Fact]
public async Task When_enum_property_is_generated_then_enum_is_referenced()
{
//// Arrange
//// Act
var schema = JsonSchema.FromType<EnumProperty>(new JsonSchemaGeneratorSettings
{
SchemaType = SchemaType.Swagger2,
DefaultEnumHandling = EnumHandling.Integer
});
var json = schema.ToJson();
//// Assert
Assert.Equal(Bar.C, schema.Properties["Bar"].Default);
Assert.True(schema.Properties["Bar"].HasReference);
}
public class EnumPropertyWithDefaultClass
{
[DefaultValue(MyEnumeration.C)]
public MyEnumeration MyEnumeration { get; set; }
}
[JsonConverter(typeof(StringEnumConverter))]
public enum MyEnumeration
{
A,
B,
C
}
[Fact]
public async Task When_string_enum_property_has_default_then_default_is_converted_to_string()
{
//// Arrange
var schema = JsonSchema.FromType<EnumPropertyWithDefaultClass>(new JsonSchemaGeneratorSettings());
//// Act
var json = schema.ToJson();
//// Assert
Assert.Equal("C", schema.Properties["MyEnumeration"].Default);
}
public class Party
{
public MyEnumeration? EnumValue { get; set; }
public bool ShouldSerializeEnumValue()
{
return EnumValue.HasValue;
}
}
[Fact]
public async Task When_enum_property_has_should_serialize_then_no_npe()
{
//// Arrange
var schema = JsonSchema.FromType<Party>(new JsonSchemaGeneratorSettings());
//// Act
var json = schema.ToJson();
//// Assert
Assert.True(schema.Properties.ContainsKey("EnumValue"));
Assert.NotNull(json);
}
public class RequiredEnumProperty
{
[Required]
public Bar Bar { get; set; }
public Bar Bar2 { get; set; }
}
[Fact]
public async Task When_enum_property_is_required_then_MinLength_is_not_set()
{
//// Arrange
//// Act
var schema = JsonSchema.FromType<RequiredEnumProperty>(new JsonSchemaGeneratorSettings
{
SchemaType = SchemaType.OpenApi3,
DefaultEnumHandling = EnumHandling.String
});
var json = schema.ToJson();
//// Assert
Assert.True(schema.RequiredProperties.Contains("Bar"));
Assert.True(schema.Properties["Bar"].OneOf.Count == 0);
Assert.True(schema.Properties["Bar"].Reference != null);
}
}
}
| |
// <copyright file="ResidualStopCriterionTest.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
//
// Copyright (c) 2009-2014 Math.NET
//
// 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.
// </copyright>
using System;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Solvers;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex.Solvers.StopCriterion
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Residual stop criterion tests.
/// </summary>
[TestFixture, Category("LASolver")]
public sealed class ResidualStopCriterionTest
{
/// <summary>
/// Create with negative maximum throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void CreateWithNegativeMaximumThrowsArgumentOutOfRangeException()
{
Assert.That(() => new ResidualStopCriterion<Complex>(-0.1), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Create with illegal minimum iterations throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void CreateWithIllegalMinimumIterationsThrowsArgumentOutOfRangeException()
{
Assert.That(() => new ResidualStopCriterion<Complex>(-1), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Can create.
/// </summary>
[Test]
public void Create()
{
var criterion = new ResidualStopCriterion<Complex>(1e-8, 50);
Assert.AreEqual(1e-8, criterion.Maximum, "Incorrect maximum");
Assert.AreEqual(50, criterion.MinimumIterationsBelowMaximum, "Incorrect iteration count");
}
/// <summary>
/// Determine status with illegal iteration number throws <c>ArgumentOutOfRangeException</c>.
/// </summary>
[Test]
public void DetermineStatusWithIllegalIterationNumberThrowsArgumentOutOfRangeException()
{
var criterion = new ResidualStopCriterion<Complex>(1e-8, 50);
Assert.That(() => criterion.DetermineStatus(
-1,
Vector<Complex>.Build.Dense(3, 4),
Vector<Complex>.Build.Dense(3, 5),
Vector<Complex>.Build.Dense(3, 6)), Throws.TypeOf<ArgumentOutOfRangeException>());
}
/// <summary>
/// Determine status with non-matching solution vector throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void DetermineStatusWithNonMatchingSolutionVectorThrowsArgumentException()
{
var criterion = new ResidualStopCriterion<Complex>(1e-8, 50);
Assert.That(() => criterion.DetermineStatus(
1,
Vector<Complex>.Build.Dense(4, 4),
Vector<Complex>.Build.Dense(3, 4),
Vector<Complex>.Build.Dense(3, 4)), Throws.ArgumentException);
}
/// <summary>
/// Determine status with non-matching source vector throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void DetermineStatusWithNonMatchingSourceVectorThrowsArgumentException()
{
var criterion = new ResidualStopCriterion<Complex>(1e-8, 50);
Assert.That(() => criterion.DetermineStatus(
1,
Vector<Complex>.Build.Dense(3, 4),
Vector<Complex>.Build.Dense(4, 4),
Vector<Complex>.Build.Dense(3, 4)), Throws.ArgumentException);
}
/// <summary>
/// Determine status with non-matching residual vector throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void DetermineStatusWithNonMatchingResidualVectorThrowsArgumentException()
{
var criterion = new ResidualStopCriterion<Complex>(1e-8, 50);
Assert.That(() => criterion.DetermineStatus(
1,
Vector<Complex>.Build.Dense(3, 4),
Vector<Complex>.Build.Dense(3, 4),
Vector<Complex>.Build.Dense(4, 4)), Throws.ArgumentException);
}
/// <summary>
/// Can determine status with source NaN.
/// </summary>
[Test]
public void DetermineStatusWithSourceNaN()
{
var criterion = new ResidualStopCriterion<Complex>(1e-3, 10);
var solution = new DenseVector(new[] { new Complex(1.0, 1), new Complex(1.0, 1), new Complex(2.0, 1) });
var source = new DenseVector(new[] { new Complex(1.0, 1), new Complex(1.0, 1), new Complex(double.NaN, 1) });
var residual = new DenseVector(new[] { new Complex(1000.0, 1), new Complex(1000.0, 1), new Complex(2001.0, 1) });
var status = criterion.DetermineStatus(5, solution, source, residual);
Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged");
}
/// <summary>
/// Can determine status with residual NaN.
/// </summary>
[Test]
public void DetermineStatusWithResidualNaN()
{
var criterion = new ResidualStopCriterion<Complex>(1e-3, 10);
var solution = new DenseVector(new[] { new Complex(1.0, 1), new Complex(1.0, 1), new Complex(2.0, 1) });
var source = new DenseVector(new[] { new Complex(1.0, 1), new Complex(1.0, 1), new Complex(2.0, 1) });
var residual = new DenseVector(new[] { new Complex(1000.0, 1), new Complex(double.NaN, 1), new Complex(2001.0, 1) });
var status = criterion.DetermineStatus(5, solution, source, residual);
Assert.AreEqual(IterationStatus.Diverged, status, "Should be diverged");
}
/// <summary>
/// Can determine status with convergence at first iteration.
/// </summary>
/// <remarks>Bugfix: The unit tests for the BiCgStab solver run with a super simple matrix equation
/// which converges at the first iteration. The default settings for the
/// residual stop criterion should be able to handle this.
/// </remarks>
[Test]
public void DetermineStatusWithConvergenceAtFirstIteration()
{
var criterion = new ResidualStopCriterion<Complex>(1e-12);
var solution = new DenseVector(new[] { Complex.One, Complex.One, Complex.One });
var source = new DenseVector(new[] { Complex.One, Complex.One, Complex.One });
var residual = new DenseVector(new[] { Complex.Zero, Complex.Zero, Complex.Zero });
var status = criterion.DetermineStatus(0, solution, source, residual);
Assert.AreEqual(IterationStatus.Converged, status, "Should be done");
}
/// <summary>
/// Can determine status.
/// </summary>
[Test]
public void DetermineStatus()
{
var criterion = new ResidualStopCriterion<Complex>(1e-3, 10);
// the solution vector isn't actually being used so ...
var solution = new DenseVector(new[] { new Complex(double.NaN, double.NaN), new Complex(double.NaN, double.NaN), new Complex(double.NaN, double.NaN) });
// Set the source values
var source = new DenseVector(new[] { new Complex(1.000, 1), new Complex(1.000, 1), new Complex(2.001, 1) });
// Set the residual values
var residual = new DenseVector(new[] { new Complex(0.001, 0), new Complex(0.001, 0), new Complex(0.002, 0) });
var status = criterion.DetermineStatus(5, solution, source, residual);
Assert.AreEqual(IterationStatus.Continue, status, "Should still be running");
var status2 = criterion.DetermineStatus(16, solution, source, residual);
Assert.AreEqual(IterationStatus.Converged, status2, "Should be done");
}
/// <summary>
/// Can reset calculation state.
/// </summary>
[Test]
public void ResetCalculationState()
{
var criterion = new ResidualStopCriterion<Complex>(1e-3, 10);
var solution = new DenseVector(new[] { new Complex(0.001, 1), new Complex(0.001, 1), new Complex(0.002, 1) });
var source = new DenseVector(new[] { new Complex(0.001, 1), new Complex(0.001, 1), new Complex(0.002, 1) });
var residual = new DenseVector(new[] { new Complex(1.000, 0), new Complex(1.000, 0), new Complex(2.001, 0) });
var status = criterion.DetermineStatus(5, solution, source, residual);
Assert.AreEqual(IterationStatus.Continue, status, "Should be running");
criterion.Reset();
Assert.AreEqual(IterationStatus.Continue, criterion.Status, "Should not have started");
}
/// <summary>
/// Can clone stop criterion.
/// </summary>
[Test]
public void Clone()
{
var criterion = new ResidualStopCriterion<Complex>(1e-3, 10);
var clone = criterion.Clone();
Assert.IsInstanceOf(typeof (ResidualStopCriterion<Complex>), clone, "Wrong criterion type");
var clonedCriterion = clone as ResidualStopCriterion<Complex>;
Assert.IsNotNull(clonedCriterion);
// ReSharper disable PossibleNullReferenceException
Assert.AreEqual(criterion.Maximum, clonedCriterion.Maximum, "Clone failed");
Assert.AreEqual(criterion.MinimumIterationsBelowMaximum, clonedCriterion.MinimumIterationsBelowMaximum, "Clone failed");
// ReSharper restore PossibleNullReferenceException
}
}
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Data.Entity.Migrations;
namespace WebApp.Migrations
{
public partial class AddedCallTables3 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "Call");
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Customer_City_CityId",
table: "Customer",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Customer_Sms_SmsId",
table: "Customer",
column: "SmsId",
principalTable: "Sms",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_City_CityId",
table: "Housing",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_District_DistrictId",
table: "Housing",
column: "DistrictId",
principalTable: "District",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_Street_StreetId",
table: "Housing",
column: "StreetId",
principalTable: "Street",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Housing_TypesHousing_TypesHousingId",
table: "Housing",
column: "TypesHousingId",
principalTable: "TypesHousing",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_HousingCall_Housing_HousingId",
table: "Call",
column: "HousingId",
principalTable: "Housing",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_Customer_City_CityId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Customer_Sms_SmsId", table: "Customer");
migrationBuilder.DropForeignKey(name: "FK_Housing_City_CityId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_District_DistrictId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_Street_StreetId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_Housing_TypesHousing_TypesHousingId", table: "Housing");
migrationBuilder.DropForeignKey(name: "FK_HousingCall_Housing_HousingId", table: "Call");
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Customer_City_CityId",
table: "Customer",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Customer_Sms_SmsId",
table: "Customer",
column: "SmsId",
principalTable: "Sms",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_City_CityId",
table: "Housing",
column: "CityId",
principalTable: "City",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_District_DistrictId",
table: "Housing",
column: "DistrictId",
principalTable: "District",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_Street_StreetId",
table: "Housing",
column: "StreetId",
principalTable: "Street",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Housing_TypesHousing_TypesHousingId",
table: "Housing",
column: "TypesHousingId",
principalTable: "TypesHousing",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_HousingCall_Housing_HousingId",
table: "Call",
column: "HousingId",
principalTable: "Housing",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| |
using System;
using System.ComponentModel;
using System.Windows.Forms;
using Palaso.Email;
using Palaso.Reporting;
// TODO: Ideally we wouldn't need this here in the UI.
namespace Palaso.UI.WindowsForms.Miscellaneous
{
/// <summary>
/// Summary description for UsageEmailDialog.
/// </summary>
public class UsageEmailDialog : Form
{
private TabControl tabControl1;
private TabPage tabPage1;
private PictureBox pictureBox1;
private RichTextBox richTextBox2;
private Button btnSend;
private LinkLabel btnNope;
private RichTextBox m_topLineText;
private IEmailProvider _emailProvider;
private IEmailMessage _emailMessage;
/// <summary>
/// Required designer variable.
/// </summary>
private Container components = null;
internal UsageEmailDialog()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
richTextBox2.Text = "May we ask you a favor? We would like to send a tiny e-mail back to the software developers telling us of your progress.\nYou will be able to view the e-mail before it goes out. You do not need to be connected to the Internet right now...the e-mail will just open and you can save it in your outbox.";
m_topLineText.Text = string.Format(this.m_topLineText.Text, UsageReporter.AppNameToUseInDialogs);
_emailProvider = EmailProviderFactory.PreferredEmailProvider();
_emailMessage = _emailProvider.CreateMessage();
}
/// <summary>
/// Check to see if the object has been disposed.
/// All public Properties and Methods should call this
/// before doing anything else.
/// </summary>
public void CheckDisposed()
{
if (IsDisposed)
throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name));
}
/// <summary>
///
/// </summary>
public string TopLineText
{
set
{
CheckDisposed();
m_topLineText.Text = value;
}
get
{
CheckDisposed();
return m_topLineText.Text;
}
}
public IEmailMessage EmailMessage
{
get
{
return _emailMessage;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
//Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************");
// Must not be run more than once.
if (IsDisposed)
return;
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UsageEmailDialog));
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.m_topLineText = new System.Windows.Forms.RichTextBox();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.richTextBox2 = new System.Windows.Forms.RichTextBox();
this.btnSend = new System.Windows.Forms.Button();
this.btnNope = new System.Windows.Forms.LinkLabel();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Location = new System.Drawing.Point(9, 10);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(590, 240);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.BackColor = System.Drawing.SystemColors.Window;
this.tabPage1.Controls.Add(this.m_topLineText);
this.tabPage1.Controls.Add(this.pictureBox1);
this.tabPage1.Controls.Add(this.richTextBox2);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Size = new System.Drawing.Size(582, 214);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "Report";
//
// m_topLineText
//
this.m_topLineText.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.m_topLineText.Location = new System.Drawing.Point(218, 29);
this.m_topLineText.Name = "m_topLineText";
this.m_topLineText.Size = new System.Drawing.Size(339, 31);
this.m_topLineText.TabIndex = 1;
this.m_topLineText.Text = "Thank you for checking out {0}.";
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(18, 38);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(165, 71);
this.pictureBox1.TabIndex = 2;
this.pictureBox1.TabStop = false;
//
// richTextBox2
//
this.richTextBox2.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.richTextBox2.Location = new System.Drawing.Point(218, 74);
this.richTextBox2.Name = "richTextBox2";
this.richTextBox2.Size = new System.Drawing.Size(339, 147);
this.richTextBox2.TabIndex = 1;
this.richTextBox2.Text = resources.GetString("richTextBox2.Text");
//
// btnSend
//
this.btnSend.Location = new System.Drawing.Point(464, 263);
this.btnSend.Name = "btnSend";
this.btnSend.Size = new System.Drawing.Size(133, 23);
this.btnSend.TabIndex = 1;
this.btnSend.Text = "Create Email Message";
this.btnSend.Click += new System.EventHandler(this.btnSend_Click);
//
// btnNope
//
this.btnNope.Location = new System.Drawing.Point(14, 271);
this.btnNope.Name = "btnNope";
this.btnNope.Size = new System.Drawing.Size(278, 23);
this.btnNope.TabIndex = 2;
this.btnNope.TabStop = true;
this.btnNope.Text = "I\'m unable to send this information.";
this.btnNope.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.btnNope_LinkClicked);
//
// UsageEmailDialog
//
this.AcceptButton = this.btnSend;
this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.CancelButton = this.btnNope;
this.ClientSize = new System.Drawing.Size(618, 301);
this.ControlBox = false;
this.Controls.Add(this.btnNope);
this.Controls.Add(this.btnSend);
this.Controls.Add(this.tabControl1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MinimizeBox = false;
this.Name = "UsageEmailDialog";
this.Text = "Field Usage Report System";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private void btnSend_Click(object sender, EventArgs e)
{
try
{
// TODO: This can be moved out to the caller rather than in the UI.
_emailMessage.Send(_emailProvider);
}
catch
{
//swallow it
}
DialogResult = DialogResult.OK;
Close();
}
private void btnNope_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
DialogResult = DialogResult.No;
Close();
}
}
}
| |
//
// System.Data.ProviderBase.DbDataReaderBase
//
// Author:
// Tim Coleman (tim@timcoleman.com)
// Boris Kirzner (borisk@mainsoft.com)
//
// Copyright (C) Tim Coleman, 2003
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
// (C) 2005 Mainsoft Corporation (http://www.mainsoft.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0 || TARGET_JVM
using System.Collections;
using System.Data.Common;
using System.Runtime.InteropServices;
namespace System.Data.ProviderBase {
public abstract class DbDataReaderBase : DbDataReader
{
#region Fields
CommandBehavior behavior;
#endregion // Fields
#region Constructors
protected DbDataReaderBase (CommandBehavior behavior)
{
this.behavior = behavior;
}
#endregion // Constructors
#region Properties
protected CommandBehavior CommandBehavior {
get { return behavior; }
}
public override int Depth {
// default value to be overriden by user
get { return 0; }
}
[MonoTODO]
public override int FieldCount {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override bool HasRows {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override bool IsClosed {
get { throw new NotImplementedException (); }
}
#if NET_2_0
protected abstract bool IsValidRow { get; }
#endif
[MonoTODO]
public override object this [[Optional] int index] {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override object this [[Optional] string columnName] {
get { throw new NotImplementedException (); }
}
[MonoTODO]
public override int RecordsAffected {
get { throw new NotImplementedException (); }
}
#endregion // Properties
#region Methods
[MonoTODO]
protected void AssertReaderHasColumns ()
{
throw new NotImplementedException ();
}
[MonoTODO]
protected void AssertReaderHasData ()
{
throw new NotImplementedException ();
}
[MonoTODO]
protected void AssertReaderIsOpen (string methodName)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override void Close ()
{
throw new NotImplementedException ();
}
[MonoTODO]
protected static DataTable CreateSchemaTable ()
{
throw new NotImplementedException ();
}
public override void Dispose ()
{
Close ();
}
[MonoTODO]
protected virtual void FillSchemaTable (DataTable dataTable)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool GetBoolean (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override byte GetByte (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override long GetBytes (int ordinal, long fieldoffset, byte[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override char GetChar (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override long GetChars (int ordinal, long fieldoffset, char[] buffer, int bufferoffset, int length)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override string GetDataTypeName (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override DateTime GetDateTime (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override decimal GetDecimal (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override double GetDouble (int ordinal)
{
throw new NotImplementedException ();
}
public override IEnumerator GetEnumerator ()
{
bool closeReader = (CommandBehavior & CommandBehavior.CloseConnection) != 0;
return new DbEnumerator (this , closeReader);
}
[MonoTODO]
public override Type GetFieldType (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override float GetFloat (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override Guid GetGuid (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override short GetInt16 (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override int GetInt32 (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override long GetInt64 (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override string GetName (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override int GetOrdinal (string name)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override DataTable GetSchemaTable ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public override string GetString (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override object GetValue (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override int GetValues (object[] values)
{
throw new NotImplementedException ();
}
[MonoTODO]
protected bool IsCommandBehavior (CommandBehavior condition)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool IsDBNull (int ordinal)
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool NextResult ()
{
throw new NotImplementedException ();
}
[MonoTODO]
public override bool Read ()
{
throw new NotImplementedException ();
}
#endregion // Methods
}
}
#endif
| |
#region License
/* **********************************************************************************
* Copyright (c) Roman Ivantsov
* This source code is subject to terms and conditions of the MIT License
* for Irony. A copy of the license can be found in the License.txt file
* at the root of this distribution.
* By using this source code in any fashion, you are agreeing to be bound by the terms of the
* MIT License.
* You must not remove this notice from this software.
* **********************************************************************************/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace Irony.Parsing.Construction {
// Methods constructing LALR automaton.
// See _about_parser_construction.txt file in this folder for important comments
internal partial class ParserDataBuilder {
LanguageData _language;
ParserData _data;
Grammar _grammar;
ParserStateHash _stateHash = new ParserStateHash();
internal ParserDataBuilder(LanguageData language) {
_language = language;
_grammar = _language.Grammar;
}
public void Build() {
_stateHash.Clear();
_data = _language.ParserData;
CreateParserStates();
var itemsNeedLookaheads = GetReduceItemsInInadequateState();
ComputeTransitions(itemsNeedLookaheads);
ComputeLookaheads(itemsNeedLookaheads);
ComputeStatesExpectedTerminals();
ComputeConflicts();
ApplyHints();
HandleUnresolvedConflicts();
CreateRemainingReduceActions();
//Create error action - if it is not created yet by some hint or custom code
if (_data.ErrorAction == null)
_data.ErrorAction = new ErrorRecoveryParserAction();
}//method
#region Creating parser states
private void CreateParserStates() {
var grammarData = _language.GrammarData;
//1. Base automaton: create states for main augmented root for the grammar
_data.InitialState = CreateInitialState(grammarData.AugmentedRoot);
ExpandParserStateList(0);
CreateAcceptAction(_data.InitialState, grammarData.AugmentedRoot);
//2. Expand automaton: add parser states from additional roots
foreach(var augmRoot in grammarData.AugmentedSnippetRoots) {
var initialState = CreateInitialState(augmRoot);
ExpandParserStateList(_data.States.Count - 1); //start with just added state - it is the last state in the list
CreateAcceptAction(initialState, augmRoot);
}
}
private void CreateAcceptAction(ParserState initialState, NonTerminal augmentedRoot) {
var root = augmentedRoot.Productions[0].RValues[0];
var shiftAction = initialState.Actions[root] as ShiftParserAction;
var shiftOverRootState = shiftAction.NewState;
shiftOverRootState.Actions[_grammar.Eof] = new AcceptParserAction();
}
private ParserState CreateInitialState(NonTerminal augmentedRoot) {
//for an augmented root there is an initial production "Root' -> .Root"; so we need the LR0 item at 0 index
var iniItemSet = new LR0ItemSet();
iniItemSet.Add(augmentedRoot.Productions[0].LR0Items[0]);
var initialState = FindOrCreateState(iniItemSet);
var rootNt = augmentedRoot.Productions[0].RValues[0] as NonTerminal;
_data.InitialStates[rootNt] = initialState;
return initialState;
}
private void ExpandParserStateList(int initialIndex) {
// Iterate through states (while new ones are created) and create shift transitions and new states
for (int index = initialIndex; index < _data.States.Count; index++) {
var state = _data.States[index];
//Get all possible shifts
foreach (var term in state.BuilderData.ShiftTerms) {
var shiftItems = state.BuilderData.ShiftItems.SelectByCurrent(term);
//Get set of shifted cores and find/create target state
var shiftedCoreItems = shiftItems.GetShiftedCores();
var newState = FindOrCreateState(shiftedCoreItems);
//Create shift action
var newAction = new ShiftParserAction(term, newState);
state.Actions[term] = newAction;
//Link items in old/new states
foreach (var shiftItem in shiftItems) {
shiftItem.ShiftedItem = newState.BuilderData.AllItems.FindByCore(shiftItem.Core.ShiftedItem);
}//foreach shiftItem
}//foreach term
} //for index
}//method
private ParserState FindOrCreateState(LR0ItemSet coreItems) {
string key = ComputeLR0ItemSetKey(coreItems);
ParserState state;
if (_stateHash.TryGetValue(key, out state))
return state;
//create new state
state = new ParserState("S" + _data.States.Count);
state.BuilderData = new ParserStateData(state, coreItems);
_data.States.Add(state);
_stateHash[key] = state;
return state;
}
#endregion
#region Compute transitions, lookbacks, lookaheads
//We compute only transitions that are really needed to compute lookaheads in inadequate states.
// We start with reduce items in inadequate state and find their lookbacks - this is initial list of transitions.
// Then for each transition in the list we check if it has items with nullable tails; for those items we compute
// lookbacks - these are new or already existing transitons - and so on, we repeat the operation until no new transitions
// are created.
private void ComputeTransitions(LRItemSet forItems) {
var newItemsNeedLookbacks = forItems;
while(newItemsNeedLookbacks.Count > 0) {
var newTransitions = CreateLookbackTransitions(newItemsNeedLookbacks);
newItemsNeedLookbacks = SelectNewItemsThatNeedLookback(newTransitions);
}
}
private LRItemSet SelectNewItemsThatNeedLookback(TransitionList transitions) {
//Select items with nullable tails that don't have lookbacks yet
var items = new LRItemSet();
foreach(var trans in transitions)
foreach(var item in trans.Items)
if (item.Core.TailIsNullable && item.Lookbacks.Count == 0) //only if it does not have lookbacks yet
items.Add(item);
return items;
}
private LRItemSet GetReduceItemsInInadequateState() {
var result = new LRItemSet();
foreach(var state in _data.States) {
if (state.BuilderData.IsInadequate)
result.UnionWith(state.BuilderData.ReduceItems);
}
return result;
}
private TransitionList CreateLookbackTransitions(LRItemSet sourceItems) {
var newTransitions = new TransitionList();
//Build set of initial cores - this is optimization for performance
//We need to find all initial items in all states that shift into one of sourceItems
// Each such initial item would have the core from the "initial" cores set that we build from source items.
var iniCores = new LR0ItemSet();
foreach(var sourceItem in sourceItems)
iniCores.Add(sourceItem.Core.Production.LR0Items[0]);
//find
foreach(var state in _data.States) {
foreach(var iniItem in state.BuilderData.InitialItems) {
if (!iniCores.Contains(iniItem.Core)) continue;
var iniItemNt = iniItem.Core.Production.LValue; // iniItem's non-terminal (left side of production)
Transition lookback = null; // local var for lookback - transition over iniItemNt
var currItem = iniItem; // iniItem is initial item for all currItem's in the shift chain.
while (currItem != null) {
if(sourceItems.Contains(currItem)) {
// We create transitions lazily, only when we actually need them. Check if we have iniItem's transition
// in local variable; if not, get it from state's transitions table; if not found, create it.
if(lookback == null && !state.BuilderData.Transitions.TryGetValue(iniItemNt, out lookback)) {
lookback = new Transition(state, iniItemNt);
newTransitions.Add(lookback);
}
//Now for currItem, either add trans to Lookbacks, or "include" it into currItem.Transition
// We need lookbacks ONLY for final items; for non-Final items we need proper Include lists on transitions
if (currItem.Core.IsFinal)
currItem.Lookbacks.Add(lookback);
else // if (currItem.Transition != null)
// Note: looks like checking for currItem.Transition is redundant - currItem is either:
// - Final - always the case for the first run of this method;
// - it has a transition after the first run, due to the way we select sourceItems list
// in SelectNewItemsThatNeedLookback (by transitions)
currItem.Transition.Include(lookback);
}//if
//move to next item
currItem = currItem.ShiftedItem;
}//while
}//foreach iniItem
}//foreach state
return newTransitions;
}
private void ComputeLookaheads(LRItemSet forItems) {
foreach(var reduceItem in forItems) {
// Find all source states - those that contribute lookaheads
var sourceStates = new ParserStateSet();
foreach(var lookbackTrans in reduceItem.Lookbacks) {
sourceStates.Add(lookbackTrans.ToState);
sourceStates.UnionWith(lookbackTrans.ToState.BuilderData.ReadStateSet);
foreach(var includeTrans in lookbackTrans.Includes) {
sourceStates.Add(includeTrans.ToState);
sourceStates.UnionWith(includeTrans.ToState.BuilderData.ReadStateSet);
}//foreach includeTrans
}//foreach lookbackTrans
//Now merge all shift terminals from all source states
foreach(var state in sourceStates)
reduceItem.Lookaheads.UnionWith(state.BuilderData.ShiftTerminals);
//Remove SyntaxError - it is pseudo terminal
if (reduceItem.Lookaheads.Contains(_grammar.SyntaxError))
reduceItem.Lookaheads.Remove(_grammar.SyntaxError);
//Sanity check
if (reduceItem.Lookaheads.Count == 0)
_language.Errors.Add(GrammarErrorLevel.InternalError, reduceItem.State, "Reduce item '{0}' in state {1} has no lookaheads.", reduceItem.Core, reduceItem.State);
}//foreach reduceItem
}//method
#endregion
#region Analyzing and resolving conflicts
private void ComputeConflicts() {
foreach(var state in _data.States) {
if(!state.BuilderData.IsInadequate)
continue;
//first detect conflicts
var stateData = state.BuilderData;
stateData.Conflicts.Clear();
var allLkhds = new BnfTermSet();
//reduce/reduce --------------------------------------------------------------------------------------
foreach(var item in stateData.ReduceItems) {
foreach(var lkh in item.Lookaheads) {
if(allLkhds.Contains(lkh))
state.BuilderData.Conflicts.Add(lkh);
allLkhds.Add(lkh);
}//foreach lkh
}//foreach item
//shift/reduce ---------------------------------------------------------------------------------------
foreach(var term in stateData.ShiftTerminals)
if(allLkhds.Contains(term)) {
stateData.Conflicts.Add(term);
}
}
}//method
private void ApplyHints() {
foreach (var state in _data.States) {
var stateData = state.BuilderData;
//Add automatic precedence hints
if (stateData.Conflicts.Count > 0)
foreach (var conflict in stateData.Conflicts.ToList())
if (conflict.Flags.IsSet(TermFlags.IsOperator)) {
//Find any reduce item with this lookahead and add PrecedenceHint
var reduceItem = stateData.ReduceItems.SelectByLookahead(conflict).First();
var precHint = new PrecedenceHint();
reduceItem.Core.Hints.Add(precHint);
}
// Apply (activate) hints - these should resolve conflicts as well
foreach (var item in state.BuilderData.AllItems)
foreach (var hint in item.Core.Hints)
hint.Apply(_language, item);
}//foreach
}//method
//Resolve to default actions
private void HandleUnresolvedConflicts() {
foreach (var state in _data.States) {
if (state.BuilderData.Conflicts.Count == 0)
continue;
var shiftReduceConflicts = state.BuilderData.GetShiftReduceConflicts();
var reduceReduceConflicts = state.BuilderData.GetReduceReduceConflicts();
var stateData = state.BuilderData;
if (shiftReduceConflicts.Count > 0)
_language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrSRConflict, state, shiftReduceConflicts.ToString());
if (reduceReduceConflicts.Count > 0)
_language.Errors.Add(GrammarErrorLevel.Conflict, state, Resources.ErrRRConflict, state, reduceReduceConflicts.ToString());
//Create default actions for these conflicts. For shift-reduce, default action is shift, and shift action already
// exist for all shifts from the state, so we don't need to do anything, only report it
//For reduce-reduce create reduce actions for the first reduce item (whatever comes first in the set).
foreach (var conflict in reduceReduceConflicts) {
var reduceItems = stateData.ReduceItems.SelectByLookahead(conflict);
var firstProd = reduceItems.First().Core.Production;
var action = new ReduceParserAction(firstProd);
state.Actions[conflict] = action;
}
//stateData.Conflicts.Clear(); -- do not clear them, let the set keep the auto-resolved conflicts, may find more use for this later
}
}
#endregion
#region final actions: creating remaining reduce actions, computing expected terminals, cleaning up state data
//Create reduce actions for states with a single reduce item (and no shifts)
private void CreateRemainingReduceActions() {
foreach (var state in _data.States) {
if (state.DefaultAction != null) continue;
var stateData = state.BuilderData;
if (stateData.ShiftItems.Count == 0 && stateData.ReduceItems.Count == 1) {
state.DefaultAction = ReduceParserAction.Create(stateData.ReduceItems.First().Core.Production);
continue; //next state; if we have default reduce action, we don't need to fill actions dictionary for lookaheads
}
//create actions
foreach (var item in state.BuilderData.ReduceItems) {
var action = ReduceParserAction.Create(item.Core.Production);
foreach (var lkh in item.Lookaheads) {
if (state.Actions.ContainsKey(lkh)) continue;
state.Actions[lkh] = action;
}
}//foreach item
}//foreach state
}
//Note that for states with a single reduce item the result is empty
private void ComputeStatesExpectedTerminals() {
foreach (var state in _data.States) {
state.ExpectedTerminals.UnionWith(state.BuilderData.ShiftTerminals);
//Add lookaheads from reduce items
foreach (var reduceItem in state.BuilderData.ReduceItems)
state.ExpectedTerminals.UnionWith(reduceItem.Lookaheads);
RemoveTerminals(state.ExpectedTerminals, _grammar.SyntaxError, _grammar.Eof);
}//foreach state
}
private void RemoveTerminals(TerminalSet terms, params Terminal[] termsToRemove) {
foreach(var termToRemove in termsToRemove)
if (terms.Contains(termToRemove)) terms.Remove(termToRemove);
}
public void CleanupStateData() {
foreach (var state in _data.States)
state.ClearData();
}
#endregion
#region Utilities: ComputeLR0ItemSetKey
//Parser states are distinguished by the subset of kernel LR0 items.
// So when we derive new LR0-item list by shift operation,
// we need to find out if we have already a state with the same LR0Item list.
// We do it by looking up in a state hash by a key - [LR0 item list key].
// Each list's key is a concatenation of items' IDs separated by ','.
// Before producing the key for a list, the list must be sorted;
// thus we garantee one-to-one correspondence between LR0Item sets and keys.
// And of course, we count only kernel items (with dot NOT in the first position).
public static string ComputeLR0ItemSetKey(LR0ItemSet items) {
if (items.Count == 0) return string.Empty;
//Copy non-initial items to separate list, and then sort it
LR0ItemList itemList = new LR0ItemList();
foreach (var item in items)
itemList.Add(item);
//quick shortcut
if (itemList.Count == 1)
return itemList[0].ID.ToString();
itemList.Sort(CompareLR0Items); //Sort by ID
//now build the key
StringBuilder sb = new StringBuilder(100);
foreach (LR0Item item in itemList) {
sb.Append(item.ID);
sb.Append(",");
}//foreach
return sb.ToString();
}
private static int CompareLR0Items(LR0Item x, LR0Item y) {
if (x.ID < y.ID) return -1;
if (x.ID == y.ID) return 0;
return 1;
}
#endregion
#region comments
// Computes set of expected terms in a parser state. While there may be extended list of symbols expected at some point,
// we want to reorganize and reduce it. For example, if the current state expects all arithmetic operators as an input,
// it would be better to not list all operators (+, -, *, /, etc) but simply put "operator" covering them all.
// To achieve this grammar writer can group operators (or any other terminals) into named groups using Grammar's methods
// AddTermReportGroup, AddNoReportGroup etc. Then instead of reporting each operator separately, Irony would include
// a single "group name" to represent them all.
// The "expected report set" is not computed during parser construction (it would bite considerable time), but on demand during parsing,
// when error is detected and the expected set is actually needed for error message.
// Multi-threading concerns. When used in multi-threaded environment (web server), the LanguageData would be shared in
// application-wide cache to avoid rebuilding the parser data on every request. The LanguageData is immutable, except
// this one case - the expected sets are constructed late by CoreParser on the when-needed basis.
// We don't do any locking here, just compute the set and on return from this function the state field is assigned.
// We assume that this field assignment is an atomic, concurrency-safe operation. The worst thing that might happen
// is "double-effort" when two threads start computing the same set around the same time, and the last one to finish would
// leave its result in the state field.
#endregion
internal static StringSet ComputeGroupedExpectedSetForState(Grammar grammar, ParserState state) {
var terms = new TerminalSet();
terms.UnionWith(state.ExpectedTerminals);
var result = new StringSet();
//Eliminate no-report terminals
foreach (var group in grammar.TermReportGroups)
if (group.GroupType == TermReportGroupType.DoNotReport)
terms.ExceptWith(group.Terminals);
//Add normal and operator groups
foreach (var group in grammar.TermReportGroups)
if ((group.GroupType == TermReportGroupType.Normal || group.GroupType == TermReportGroupType.Operator) &&
terms.Overlaps(group.Terminals)) {
result.Add(group.Alias);
terms.ExceptWith(group.Terminals);
}
//Add remaining terminals "as is"
foreach (var terminal in terms)
result.Add(terminal.ErrorAlias);
return result;
}
}//class
}//namespace
| |
namespace dotless.Test.Config
{
using System;
using Core;
using Core.Abstractions;
using Core.Cache;
using Core.configuration;
using Core.Input;
using Core.Loggers;
using Core.Parser;
using Core.Response;
using NUnit.Framework;
public class ConfigurationFixture
{
private ILessEngine GetEngine(DotlessConfiguration config)
{
return ((ParameterDecorator)new EngineFactory(config).GetEngine(".")).Underlying;
}
[Test]
public void DefaultEngineIsParameterDecorator()
{
var engine = new EngineFactory().GetEngine(".");
Assert.That(engine, Is.TypeOf<ParameterDecorator>());
}
[Test]
public void CachingIsEnabledByDefault()
{
var engine = new EngineFactory().GetEngine(".");
engine = ((ParameterDecorator)engine).Underlying;
Assert.That(engine, Is.TypeOf<CacheDecorator>());
}
[Test]
public void IfMinifyOptionSetEngineIsLessEngine()
{
var config = new DotlessConfiguration { MinifyOutput = true, CacheEnabled = false };
var engine = GetEngine(config);
Assert.That(engine, Is.TypeOf<LessEngine>());
}
[Test]
public void IfWebOptionSetButCachedIsFalseEngineIsLessEngine()
{
var config = new DotlessConfiguration { Web = true, CacheEnabled = false };
var engine = GetEngine(config);
Assert.That(engine, Is.TypeOf<LessEngine>());
}
[Test]
public void IfWebAndCacheOptionsSetEngineIsCacheDecorator()
{
var config = new DotlessConfiguration { Web = true, CacheEnabled = true };
var engine = GetEngine(config);
Assert.That(engine, Is.TypeOf<CacheDecorator>());
var aspEngine = (CacheDecorator)engine;
Assert.That(aspEngine.Underlying, Is.TypeOf<LessEngine>());
}
[Test]
public void IfWebAndCacheOptionsSetCacheIsHttpCache()
{
var config = new DotlessConfiguration { Web = true, CacheEnabled = true };
var serviceLocator = new ContainerFactory().GetContainer(config);
var cache = serviceLocator.GetInstance<ICache>();
Assert.That(cache, Is.TypeOf<HttpCache>());
}
[Test]
public void IfCacheOptionSetCacheIsInMemoryCache()
{
var config = new DotlessConfiguration { Web = false, CacheEnabled = true };
var serviceLocator = new ContainerFactory().GetContainer(config);
var cache = serviceLocator.GetInstance<ICache>();
Assert.That(cache, Is.TypeOf<InMemoryCache>());
}
[Test]
public void IfWebCacheAndMinifyOptionsSetEngineIsCacheDecoratorThenLessEngine()
{
var config = new DotlessConfiguration { Web = true, CacheEnabled = true, MinifyOutput = true };
var engine = GetEngine(config);
Assert.That(engine, Is.TypeOf<CacheDecorator>());
var aspEngine = (CacheDecorator)engine;
Assert.That(aspEngine.Underlying, Is.TypeOf<LessEngine>());
}
[Test]
public void CanPassCustomLogger()
{
var config = new DotlessConfiguration { Logger = typeof(DummyLogger) };
var serviceLocator = new ContainerFactory().GetContainer(config);
var logger = serviceLocator.GetInstance<ILogger>();
Assert.That(logger, Is.TypeOf<DummyLogger>());
}
[Test]
public void CanPassCustomLessSource()
{
var config = new DotlessConfiguration { LessSource = typeof(DummyFileReader) };
var serviceLocator = new ContainerFactory().GetContainer(config);
var source = serviceLocator.GetInstance<IFileReader>();
Assert.That(source, Is.TypeOf<DummyFileReader>());
}
[Test]
public void CanOverrideOptimization()
{
var config = new DotlessConfiguration { Optimization = 7 };
var serviceLocator = new ContainerFactory().GetContainer(config);
var parser = serviceLocator.GetInstance<Parser>();
Assert.That(parser.Tokenizer.Optimization, Is.EqualTo(7));
}
[Test]
public void CanOverrideLogLevel()
{
var config = new DotlessConfiguration { LogLevel = LogLevel.Info };
var serviceLocator = new ContainerFactory().GetContainer(config);
var logger = serviceLocator.GetInstance<ILogger>();
Assert.That(logger, Is.TypeOf<ConsoleLogger>());
var consoleLogger = (ConsoleLogger)logger;
Assert.That(consoleLogger.Level, Is.EqualTo(LogLevel.Info));
}
[Test]
public void HttpInstanceIsTransient()
{
var config = new DotlessConfiguration { Web = true };
var serviceLocator = new ContainerFactory().GetContainer(config);
var http1 = serviceLocator.GetInstance<IHttp>();
var http2 = serviceLocator.GetInstance<IHttp>();
Assert.That(http1, Is.Not.SameAs(http2));
}
[Test]
public void CachedCssResponseInstanceIsTransient()
{
var config = new DotlessConfiguration { Web = true };
var serviceLocator = new ContainerFactory().GetContainer(config);
var response1 = serviceLocator.GetInstance<IResponse>();
var response2 = serviceLocator.GetInstance<IResponse>();
Assert.That(response1, Is.Not.SameAs(response2));
var http1 = (response1 as CachedCssResponse).Http;
var http2 = (response2 as CachedCssResponse).Http;
Assert.That(http1, Is.Not.SameAs(http2));
}
[Test]
public void CssResponseInstanceIsTransient()
{
var config = new DotlessConfiguration { Web = true, CacheEnabled = false };
var serviceLocator = new ContainerFactory().GetContainer(config);
var response1 = serviceLocator.GetInstance<IResponse>();
var response2 = serviceLocator.GetInstance<IResponse>();
Assert.That(response1, Is.Not.SameAs(response2));
var http1 = (response1 as CssResponse).Http;
var http2 = (response2 as CssResponse).Http;
Assert.That(http1, Is.Not.SameAs(http2));
}
[Test]
public void HandlerImplInstanceIsTransient()
{
var config = new DotlessConfiguration { Web = true };
var serviceLocator = new ContainerFactory().GetContainer(config);
var handler1 = serviceLocator.GetInstance<HandlerImpl>();
var handler2 = serviceLocator.GetInstance<HandlerImpl>();
Assert.That(handler1, Is.Not.SameAs(handler2));
var http1 = handler1.Http;
var http2 = handler2.Http;
Assert.That(http1, Is.Not.SameAs(http2));
var response1 = handler1.Response;
var response2 = handler2.Response;
Assert.That(response1, Is.Not.SameAs(response2));
var engine1 = handler1.Engine;
var engine2 = handler2.Engine;
Assert.That(engine1, Is.Not.SameAs(engine2));
}
public class DummyLogger : Logger
{
public DummyLogger(LogLevel level) : base(level) { }
protected override void Log(string message) { }
}
public class DummyFileReader : IFileReader
{
public string GetFileContents(string fileName)
{
throw new NotImplementedException();
}
}
}
}
| |
/*
*
* (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.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using AjaxPro;
using ASC.ActiveDirectory.Base.Settings;
using ASC.Core;
using ASC.Core.Users;
using ASC.MessagingSystem;
using ASC.Web.Core;
using ASC.Web.Core.Utility.Settings;
using ASC.Web.Core.Utility.Skins;
using ASC.Web.Core.WhiteLabel;
using ASC.Web.Studio.Controls.Users;
using ASC.Web.Studio.Core;
using ASC.Web.Studio.Core.Notify;
using ASC.Web.Studio.Core.Users;
using ASC.Web.Studio.PublicResources;
using ASC.Web.Studio.Utility;
using Newtonsoft.Json;
namespace ASC.Web.Studio.UserControls.Management
{
[ManagementControl(ManagementType.AccessRights, Location)]
[AjaxNamespace("AccessRightsController")]
public partial class AccessRights : UserControl
{
#region Properies
public const string Location = "~/UserControls/Management/AccessRights/AccessRights.ascx";
protected bool CanOwnerEdit;
private List<IWebItem> products;
protected List<IWebItem> Products
{
get { return products ?? (products = GetProductList()); }
}
protected string[] FullAccessOpportunities { get; set; }
protected List<string> LdapRights { get; set; }
protected bool EnableAddAdmin
{
get
{
return CoreContext.Configuration.Standalone ||
(TenantExtra.GetTenantQuota().CountAdmin > GetCountAdmins);
}
}
protected int GetCountAdmins
{
get
{
return WebItemSecurity.GetProductAdministrators(Guid.Empty).Count();
}
}
protected string TariffPageLink { get; set; }
#endregion
#region Events
protected void Page_Load(object sender, EventArgs e)
{
TariffPageLink = TenantExtra.GetTariffPageLink();
InitControl();
RegisterClientScript();
}
#endregion
#region Methods
private void InitControl()
{
AjaxPro.Utility.RegisterTypeForAjax(GetType());
//owner settings
var curTenant = CoreContext.TenantManager.GetCurrentTenant();
var currentOwner = CoreContext.UserManager.GetUsers(curTenant.OwnerId);
CanOwnerEdit = currentOwner.ID.Equals(SecurityContext.CurrentAccount.ID);
_phOwnerCard.Controls.Add(new EmployeeUserCard
{
EmployeeInfo = currentOwner,
EmployeeUrl = currentOwner.GetUserProfilePageURL(),
Width = 330
});
FullAccessOpportunities = Resource.AccessRightsFullAccessOpportunities.Split('|');
}
private void RegisterClientScript()
{
var isRetina = TenantLogoManager.IsRetina(HttpContext.Current.Request);
Page.RegisterBodyScripts("~/UserControls/Management/AccessRights/js/accessrights.js")
.RegisterStyle("~/UserControls/Management/AccessRights/css/accessrights.less");
var curTenant = CoreContext.TenantManager.GetCurrentTenant();
var currentOwner = CoreContext.UserManager.GetUsers(curTenant.OwnerId);
var admins = WebItemSecurity.GetProductAdministrators(Guid.Empty).ToList();
admins = admins
.GroupBy(admin => admin.ID)
.Select(group => group.First())
.Where(admin => admin.ID != currentOwner.ID)
.SortByUserName();
InitLdapRights();
var sb = new StringBuilder();
sb.AppendFormat("ownerId = \"{0}\";", curTenant.OwnerId);
sb.AppendFormat("adminList = {0};", JsonConvert.SerializeObject(admins.ConvertAll(u => new
{
id = u.ID,
smallFotoUrl = u.GetSmallPhotoURL(),
bigFotoUrl = isRetina ? u.GetBigPhotoURL() : "",
displayName = u.DisplayUserName(),
title = u.Title.HtmlEncode(),
userUrl = CommonLinkUtility.GetUserProfile(u.ID),
accessList = GetAccessList(u.ID, WebItemSecurity.IsProductAdministrator(Guid.Empty, u.ID)),
ldap = LdapRights.Contains(u.ID.ToString())
})));
sb.AppendFormat("imageHelper = {0};", JsonConvert.SerializeObject(new
{
PeopleImgSrc = WebImageSupplier.GetAbsoluteWebPath("user_12.png"),
GroupImgSrc = WebImageSupplier.GetAbsoluteWebPath("group_12.png"),
TrashImgSrc = WebImageSupplier.GetAbsoluteWebPath("trash_12.png"),
TrashImgTitle = Resource.DeleteButton
}));
var managementPage = Page as Studio.Management;
var tenantAccess = managementPage != null ? managementPage.TenantAccess : TenantAccessSettings.Load();
if (!tenantAccess.Anyone)
{
var productItemList = GetProductItemListForSerialization();
foreach (var productItem in productItemList.Where(productItem => !productItem.CanNotBeDisabled))
{
sb.AppendFormat("ASC.Settings.AccessRights.initProduct('{0}');", Convert.ToBase64String(
Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(productItem))));
}
}
sb.AppendFormat("ASC.Settings.AccessRights.init({0});",
JsonConvert.SerializeObject(Products.Select(p => p.GetSysName()).ToArray()));
Page.RegisterInlineScript(sb.ToString());
}
private void InitLdapRights()
{
if (LdapRights != null) return;
var ldapRightsSettings = LdapCurrentAcccessSettings.Load();
LdapRights = ldapRightsSettings.CurrentAccessRights == null
? new List<string>()
: ldapRightsSettings.CurrentAccessRights.SelectMany(r => r.Value).Distinct().ToList();
}
private static List<IWebItem> GetProductList()
{
var webItems = new List<IWebItem>();
webItems.AddRange(WebItemManager.Instance.GetItemsAll<IProduct>().Where(p => p.Visible).ToList());
webItems.Add(WebItemManager.Instance[WebItemManager.MailProductID]);
return webItems;
}
private IEnumerable<Item> GetProductItemListForSerialization()
{
var data = new List<Item>();
foreach (var p in Products)
{
if (String.IsNullOrEmpty(p.Name)) continue;
var userOpportunities = p.GetUserOpportunities();
var item = new Item
{
ID = p.ID,
Name = p.Name.HtmlEncode(),
IconUrl = p.GetIconAbsoluteURL(),
DisabledIconUrl = p.GetDisabledIconAbsoluteURL(),
SubItems = new List<Item>(),
ItemName = p.GetSysName(),
UserOpportunitiesLabel = String.Format(CustomNamingPeople.Substitute<Resource>("AccessRightsProductUsersCan"), p.Name).HtmlEncode(),
UserOpportunities = userOpportunities != null ? userOpportunities.ConvertAll(uo => uo.HtmlEncode()) : null,
CanNotBeDisabled = p.CanNotBeDisabled()
};
if (p.HasComplexHierarchyOfAccessRights())
item.UserOpportunitiesLabel = String.Format(CustomNamingPeople.Substitute<Resource>("AccessRightsProductUsersWithRightsCan"), item.Name).HtmlEncode();
var productInfo = WebItemSecurity.GetSecurityInfo(item.ID.ToString());
item.Disabled = !productInfo.Enabled;
item.SelectedGroups = productInfo.Groups.Select(g => new SelectedItem { ID = g.ID, Name = g.Name });
item.SelectedUsers = productInfo.Users.Select(g => new SelectedItem { ID = g.ID, Name = g.DisplayUserName() });
data.Add(item);
}
return data;
}
private object GetAccessList(Guid uId, bool fullAccess)
{
var res = new List<object>
{
new
{
pId = Guid.Empty,
pName = "full",
pAccess = fullAccess,
disabled = LdapRights.Contains(uId.ToString()) || uId == SecurityContext.CurrentAccount.ID
}
};
foreach (var p in Products)
res.Add(new
{
pId = p.ID,
pName = p.GetSysName(),
pAccess = fullAccess || WebItemSecurity.IsProductAdministrator(p.ID, uId),
disabled = LdapRights.Contains(uId.ToString()) || fullAccess
});
return res;
}
#endregion
#region AjaxMethods
[AjaxMethod]
public object ChangeOwner(Guid ownerId)
{
try
{
SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var curTenant = CoreContext.TenantManager.GetCurrentTenant();
var owner = CoreContext.UserManager.GetUsers(curTenant.OwnerId);
var newOwner = CoreContext.UserManager.GetUsers(ownerId);
if (newOwner.IsVisitor()) throw new System.Security.SecurityException("Collaborator can not be an owner");
if (!owner.ID.Equals(SecurityContext.CurrentAccount.ID) || Guid.Empty.Equals(newOwner.ID))
{
return new { Status = 0, Message = Resource.ErrorAccessDenied };
}
var confirmLink = CommonLinkUtility.GetConfirmationUrl(owner.Email, ConfirmType.PortalOwnerChange, newOwner.ID, newOwner.ID);
StudioNotifyService.Instance.SendMsgConfirmChangeOwner(owner, newOwner, confirmLink);
MessageService.Send(HttpContext.Current.Request, MessageAction.OwnerSentChangeOwnerInstructions, MessageTarget.Create(owner.ID), owner.DisplayUserName(false));
var emailLink = string.Format("<a href=\"mailto:{0}\">{0}</a>", owner.Email.HtmlEncode());
return new { Status = 1, Message = Resource.ChangePortalOwnerMsg.Replace(":email", emailLink) };
}
catch (Exception e)
{
return new { Status = 0, Message = e.Message.HtmlEncode() };
}
}
[AjaxMethod]
public object AddAdmin(Guid id)
{
var isRetina = TenantLogoManager.IsRetina(HttpContext.Current.Request);
SecurityContext.DemandPermissions(SecutiryConstants.EditPortalSettings);
var user = CoreContext.UserManager.GetUsers(id);
if (user.IsVisitor())
throw new System.Security.SecurityException("Collaborator can not be an administrator");
if (!EnableAddAdmin)
{
throw new System.Security.SecurityException("Maximum number of administrator exceeded");
}
WebItemSecurity.SetProductAdministrator(Guid.Empty, id, true);
MessageService.Send(HttpContext.Current.Request, MessageAction.AdministratorAdded, MessageTarget.Create(user.ID), user.DisplayUserName(false));
InitLdapRights();
return new
{
id = user.ID,
smallFotoUrl = user.GetSmallPhotoURL(),
bigFotoUrl = isRetina ? user.GetBigPhotoURL() : "",
displayName = user.DisplayUserName(),
title = user.Title.HtmlEncode(),
userUrl = CommonLinkUtility.GetUserProfile(user.ID),
accessList = GetAccessList(user.ID, true),
enable = EnableAddAdmin
};
}
#endregion
}
public class Item
{
public bool Disabled { get; set; }
public bool DisplayedAlways { get; set; }
public bool HasPermissionSettings { get; set; }
public bool CanNotBeDisabled { get; set; }
public string Name { get; set; }
public string ItemName { get; set; }
public string IconUrl { get; set; }
public string DisabledIconUrl { get; set; }
public string AccessSwitcherLabel { get; set; }
public string UserOpportunitiesLabel { get; set; }
public List<string> UserOpportunities { get; set; }
public Guid ID { get; set; }
public List<Item> SubItems { get; set; }
public IEnumerable<SelectedItem> SelectedUsers { get; set; }
public IEnumerable<SelectedItem> SelectedGroups { get; set; }
}
public class SelectedItem
{
public Guid ID { get; set; }
public 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.
using Xunit;
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.anonmethod001.anonmethod001
{
public class Test
{
public delegate int Del(object x);
private class Foo
{
public event Del Delete;
public int Raise()
{
int x = Delete(3);
return x;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
f.Delete += delegate (dynamic d)
{
return (int)d;
}
;
int x = f.Raise();
if ((int)x != 3)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.anonmethod002.anonmethod002
{
public class Test
{
public delegate int Del(dynamic x);
private class Foo
{
public event Del Delete;
public int Raise()
{
int x = Delete(3);
return x;
}
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
Foo f = new Foo();
f.Delete += delegate (dynamic d)
{
return (int)d;
}
;
int x = f.Raise();
if ((int)x != 3)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.for001.for001
{
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int i = 0;
for (dynamic d = 0; d < 3; d = d + 1)
{
d = i;
if (d != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.for002.for002
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class myFor
{
private int _index;
private int _max;
public void Initialize(int max)
{
_index = 0;
_max = max;
}
public bool Done()
{
return _index < _max;
}
public void Next()
{
_index++;
}
public int Current()
{
return _index;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new myFor();
int i = 0;
for (d.Initialize(5); d.Done(); d.Next())
{
if ((int)d.Current() != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.for003.for003
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class myFor
{
private int _index;
private int _max;
public void Initialize(int max)
{
_index = 0;
_max = max;
}
public bool Done
{
get
{
return _index < _max;
}
}
public void Next()
{
_index++;
}
public int Current
{
get
{
return _index;
}
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new myFor();
int i = 0;
for (d.Initialize(5); d.Done; d.Next())
{
if ((int)d.Current != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.for004.for004
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class myFor
{
private int _index;
private int _max;
public void Initialize(int max)
{
_index = 0;
_max = max;
}
public static implicit operator bool (myFor x)
{
return x.Done;
}
public bool Done
{
get
{
return _index < _max;
}
}
public void Next()
{
_index++;
}
public int Current
{
get
{
return _index;
}
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = new myFor();
int i = 0;
for (d.Initialize(5); d; d.Next())
{
if ((int)d.Current != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.for005.for005
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class myFor
{
private int _index;
private int _max;
public myFor(int max)
{
_index = 0;
_max = max;
}
public bool Done
{
get
{
return _index < _max;
}
}
public void Next()
{
_index++;
}
public int Current
{
get
{
return _index;
}
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int i = 0;
for (dynamic d = new myFor(5); d.Done; d.Next())
{
if ((int)d.Current != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.for006.for006
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// We only implement the op_true and op_false operators, but not a conversion from myFor to bool
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class myFor
{
private int _index;
private int _max;
public myFor(int max)
{
_index = 0;
_max = max;
}
public void Next()
{
_index++;
}
public int Current
{
get
{
return _index;
}
}
public static bool operator true(myFor d)
{
return d._index < d._max;
}
public static bool operator false(myFor d)
{
return d._index >= d._max;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int i = 0;
for (dynamic d = new myFor(5); d; d.Next())
{
if ((int)d.Current != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach001.freach001
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new List<int>()
{
1, 2, 3, 4, 5
}
;
int i = 1;
foreach (dynamic item in list)
{
if ((int)item != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach002.freach002
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int i = 1;
foreach (dynamic item in new List<int>()
{
1, 2, 3, 4, 5
}
)
{
if ((int)item != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach003.freach003
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int i = 1;
foreach (dynamic item in new List<dynamic>()
{
1, 2, 3, 4, 5
}
)
{
if ((int)item != i)
return 1;
i++;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach005.freach005
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
//<Expects Status=warning>\(21,13\).*CS0219</Expects>
using System.Collections.Generic;
public class Foo
{
public void Bar()
{
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new List<object>()
{
new Foo(), new Foo()}
;
int i = 1;
foreach (dynamic item in list)
{
item.Bar();
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach006.freach006
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections;
public class Foo : IEnumerable, IEnumerator
{
private int _x = 2;
public void Bar()
{
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
#endregion
#region IEnumerator Members
public object Current
{
get
{
return _x;
}
}
public bool MoveNext()
{
_x--;
if (_x < 0)
return false;
else
return true;
}
public void Reset()
{
_x = 2;
}
#endregion
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new Foo();
int i = 1;
foreach (var item in list)
{
if ((int)item != i--)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach007.freach007
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections;
public class Foo
{
private int _x = 2;
public void Bar()
{
}
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return (IEnumerator)this;
}
#endregion
#region IEnumerator Members
public object Current
{
get
{
return _x;
}
}
public bool MoveNext()
{
_x--;
if (_x < 0)
return false;
else
return true;
}
public void Reset()
{
_x = 2;
}
#endregion
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new Foo();
int i = 1;
try
{
foreach (var item in list)
{
if ((int)item != i--)
return 1;
}
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Foo", "System.Collections.IEnumerable"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach008.freach008
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Foo
{
public void Bar(int i)
{
Test.Status = i;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new List<dynamic>()
{
new Foo(), new Foo()}
;
int i = 1;
foreach (var item in list)
{
item.Bar(i);
if (Test.Status != i++)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach009.freach009
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Foo
{
public void Bar(int i)
{
Test.Status = i;
}
}
public class Foo2
{
public void Bar(int i)
{
Test.Status = i;
}
}
public class Test
{
public static int Status;
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new List<dynamic>()
{
new Foo(), new Foo2()}
;
int i = 1;
foreach (var item in list)
{
item.Bar(i);
if (Test.Status != i++)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.freach010.freach010
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Collections.Generic;
public class Foo
{
public void Bar(int i)
{
Test.Status = i;
}
}
public class Foo2
{
public void Bar(int i)
{
Test.Status = i;
}
}
public class Test
{
public static int Status;
public static void Method(Foo x)
{
Test.Status = 1;
}
public static void Method(Foo2 y)
{
Test.Status = 2;
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new List<dynamic>()
{
new Foo(), new Foo2()}
;
int i = 1;
foreach (var item in list)
{
Test.Method(item);
if (Test.Status != i++)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.lock001.lock001
{
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int x = 2;
dynamic d = new object();
lock (d)
{
x = 4;
}
if (x != 4)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.lock002.lock002
{
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic d = 2;
object o = d;
int x;
lock (o)
{
x = 4;
}
if (x != 4)
return 1;
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.negfreach001.negfreach001
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
public class Test
{
private class MyClass
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
dynamic list = new MyClass();
int i = 1;
try
{
foreach (dynamic item in list)
{
if ((int)item != i)
return 1;
i++;
}
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Test.MyClass", "System.Collections.IEnumerable"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.negusing001.negusing001
{
public class Test
{
private class MyClass
{
}
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
// string s = "Test";
try
{
using (dynamic d = new MyClass())
{
//<-this should work?!
}
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "Test.MyClass", "System.IDisposable"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.query001.query001
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Linq;
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int[] numbers = new int[]
{
1, 2, 3, 4, 5
}
;
var v =
from dynamic d in numbers
select (int)d;
int x = 0;
foreach (var i in v)
{
if (numbers[x++] != i)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.query002.query002
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System.Linq;
public class Test
{
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
int[] numbers = new int[]
{
1, 2, 3, 4, 5
}
;
var v =
from d in numbers
let f = (dynamic)3
select (int)f;
foreach (var i in v)
{
if (i != 3)
return 1;
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.trycatch002.trycatch002
{
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
try
{
dynamic d = 3;
string s = (string)d.ToString();
if (s != "3")
return 1;
}
catch
{
}
return 0;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.using001.using001
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class MyClass : IDisposable
{
public static int Status;
public void Foo()
{
MyClass.Status = 2;
}
public void Dispose()
{
if (MyClass.Status == 2)
MyClass.Status = 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
using (dynamic d = new MyClass())
{
d.Foo();
}
if (MyClass.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.using002.using002
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class MyClass : IDisposable
{
public static int Status;
public void Foo()
{
MyClass.Status = 2;
}
public void Dispose()
{
if (MyClass.Status == 2)
MyClass.Status = 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
using (dynamic d = new MyClass())
{
d.Foo();
}
if (MyClass.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.using003.using003
{
// <Title> Simple dynamic declarations </Title>
// <Description> Was compiler time checking - CS1674
// runtime check to give dynamic object (e.g. IDO) an Opportunity to cast
// </Description>
// <RelatedBugs></RelatedBugs>
// <Expects Status=success></Expects>
// <Code>
public class MyClass
{
public static int Status;
public void Foo()
{
MyClass.Status = 2;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
try
{
using (dynamic d = new MyClass())
{
d.Foo();
if (MyClass.Status == 1)
return 0;
}
}
catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e)
{
if (ErrorVerifier.Verify(ErrorMessageId.NoImplicitConvCast, e.Message, "MyClass", "System.IDisposable"))
return 0;
}
return 1;
}
}
// </Code>
}
namespace ManagedTests.DynamicCSharp.Conformance.dynamic.declarations.localVariable.blockVariable.using005.using005
{
// <Title> Simple dynamic declarations </Title>
// <Description>
// </Description>
// <RelatedBugs></RelatedBugs>
//<Expects Status=success></Expects>
// <Code>
using System;
public class MyClass : IDisposable
{
public static int Status;
public void Foo()
{
MyClass.Status = 2;
}
public void Dispose()
{
if (MyClass.Status == 2)
MyClass.Status = 1;
}
}
public class Test
{
[Fact]
public static void DynamicCSharpRunTest()
{
Assert.Equal(0, MainMethod(null));
}
public static int MainMethod(string[] args)
{
object o = new MyClass();
dynamic d = o;
using (d)
{
d.Foo();
}
if (MyClass.Status == 1)
return 0;
return 1;
}
}
// </Code>
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using log4net;
using RestSharp.Extensions.MonoHttp;
using Xpressive.Home.Contracts.Gateway;
using Xpressive.Home.Contracts.Messaging;
using Action = Xpressive.Home.Contracts.Gateway.Action;
namespace Xpressive.Home.Plugins.Sonos
{
internal class SonosGateway : GatewayBase, ISonosGateway
{
private static readonly ILog _log = LogManager.GetLogger(typeof(SonosGateway));
private readonly IMessageQueue _messageQueue;
private readonly ISonosSoapClient _soapClient;
public SonosGateway(IMessageQueue messageQueue, ISonosDeviceDiscoverer deviceDiscoverer, ISonosSoapClient soapClient) : base("Sonos")
{
_messageQueue = messageQueue;
_soapClient = soapClient;
_canCreateDevices = false;
deviceDiscoverer.DeviceFound += (s, e) =>
{
e.Id = e.Id.Replace("uuid:", string.Empty);
if (!string.IsNullOrEmpty(e.Type))
{
e.Icon = "SonosIcon SonosIcon_" + e.Type;
}
_devices.Add(e);
};
}
public override IDevice CreateEmptyDevice()
{
throw new NotSupportedException();
}
public IEnumerable<SonosDevice> GetDevices()
{
return Devices.OfType<SonosDevice>();
}
public override IEnumerable<IAction> GetActions(IDevice device)
{
if (device is SonosDevice)
{
yield return new Action("Play");
yield return new Action("Pause");
yield return new Action("Stop");
yield return new Action("Play Radio") { Fields = { "Stream", "Title" } };
yield return new Action("Play File") { Fields = { "File", "Title", "Album" } };
yield return new Action("Change Volume") { Fields = { "Volume" } };
}
}
public void Play(SonosDevice device)
{
StartActionInNewTask(device, new Action("Play"), new Dictionary<string, string>(0));
}
public void Pause(SonosDevice device)
{
StartActionInNewTask(device, new Action("Pause"), new Dictionary<string, string>(0));
}
public void Stop(SonosDevice device)
{
StartActionInNewTask(device, new Action("Stop"), new Dictionary<string, string>(0));
}
public void PlayRadio(SonosDevice device, string stream, string title)
{
var parameters = new Dictionary<string, string>
{
{"Stream", stream},
{"Title", title}
};
StartActionInNewTask(device, new Action("Play Radio"), parameters);
}
public void PlayFile(SonosDevice device, string file, string title, string album)
{
var parameters = new Dictionary<string, string>
{
{"File", file},
{"Title", title},
{"Album", album}
};
StartActionInNewTask(device, new Action("Play File"), parameters);
}
public void ChangeVolume(SonosDevice device, double volume)
{
var parameters = new Dictionary<string, string>
{
{"Volume", volume.ToString("F2")}
};
StartActionInNewTask(device, new Action("Change Volume"), parameters);
}
public override async Task StartAsync(CancellationToken cancellationToken)
{
await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken).ContinueWith(_ => { });
while (!cancellationToken.IsCancellationRequested)
{
try
{
var devices = GetDevices().ToList();
var masterDevices = devices.Where(d => d.IsMaster).ToList();
var others = devices.Except(masterDevices).ToList();
masterDevices.ForEach(async d => await UpdateDeviceVariablesAsync(d));
others.ForEach(async d => await UpdateDeviceVariablesAsync(d));
}
catch (Exception e)
{
_log.Error(e.Message, e);
}
await Task.Delay(TimeSpan.FromSeconds(10), cancellationToken).ContinueWith(_ => { });
}
}
protected override async Task ExecuteInternalAsync(IDevice device, IAction action, IDictionary<string, string> values)
{
if (device == null)
{
_log.Warn($"Unable to execute action {action.Name} because the device was not found.");
return;
}
var d = device as SonosDevice;
string stream;
string file;
string title;
string album;
string volume;
values.TryGetValue("Stream", out stream);
values.TryGetValue("File", out file);
values.TryGetValue("Title", out title);
values.TryGetValue("Album", out album);
values.TryGetValue("Volume", out volume);
if (d == null)
{
return;
}
var master = GetMaster(d);
switch (action.Name.ToLowerInvariant())
{
case "play":
await SendAvTransportControl(master, "Play");
break;
case "pause":
await SendAvTransportControl(master, "Pause");
break;
case "stop":
await SendAvTransportControl(master, "Stop");
break;
case "play radio":
if (!string.IsNullOrEmpty(stream) && !string.IsNullOrEmpty(title))
{
var metadata = GetRadioMetadata(title);
var url = ReplaceScheme(stream, "x-rincon-mp3radio");
await SendUrl(master, url, metadata);
await SendAvTransportControl(master, "Play");
}
break;
case "play file":
if (!string.IsNullOrEmpty(file))
{
var metadata = GetFileMetadata(file, album);
var url = ReplaceScheme(file, "x-file-cifs");
await SendUrl(master, url, metadata);
await SendAvTransportControl(master, "Play");
}
break;
case "change volume":
var v = Math.Min(Math.Max((int)(100 * double.Parse(volume)), 0), 100);
var rc = d.Services.Single(s => s.Id.Contains(":RenderingControl"));
var sv = rc.Actions.Single(s => s.Name.Equals("SetVolume"));
var parameters = new Dictionary<string, string>
{
{"InstanceID" , "0"},
{"Channel" , "Master"},
{"DesiredVolume" , v.ToString("D")}
};
await _soapClient.ExecuteAsync(d, rc, sv, parameters);
break;
}
}
private async Task UpdateDeviceVariablesAsync(SonosDevice device)
{
var avTransport = device.Services.Single(s => s.Id.Contains("AVTransport"));
var renderingControl = device.Services.Single(s => s.Id.Contains(":RenderingControl"));
var deviceProperties = device.Services.Single(s => s.Id.Contains("DeviceProperties"));
var getMediaInfo = avTransport.Actions.Single(s => s.Name.Equals("GetMediaInfo"));
var getTransportInfo = avTransport.Actions.Single(s => s.Name.Equals("GetTransportInfo"));
var getPositionInfo = avTransport.Actions.Single(s => s.Name.Equals("GetPositionInfo"));
var getVolume = renderingControl.Actions.Single(s => s.Name.Equals("GetVolume"));
var getZoneAttributes = deviceProperties.Actions.Single(s => s.Name.Equals("GetZoneAttributes"));
var values = new Dictionary<string, string>
{
{"InstanceID", "0"}
};
var mediaInfo = await _soapClient.ExecuteAsync(device, avTransport, getMediaInfo, values);
var transportInfo = await _soapClient.ExecuteAsync(device, avTransport, getTransportInfo, values);
var positionInfo = await _soapClient.ExecuteAsync(device, avTransport, getPositionInfo, values);
values.Add("Channel", "Master");
var volume = await _soapClient.ExecuteAsync(device, renderingControl, getVolume, values);
values.Clear();
var zoneAttributes = await _soapClient.ExecuteAsync(device, deviceProperties, getZoneAttributes, values);
string currentUri;
string metadata;
string transportState;
string currentVolume;
if (!mediaInfo.TryGetValue("CurrentURI", out currentUri) ||
!mediaInfo.TryGetValue("CurrentURIMetaData", out metadata) ||
!transportInfo.TryGetValue("CurrentTransportState", out transportState) ||
!volume.TryGetValue("CurrentVolume", out currentVolume))
{
return;
}
string trackUri;
positionInfo.TryGetValue("TrackURI", out trackUri);
transportState = transportState[0] + transportState.Substring(1).ToLowerInvariant();
device.CurrentUri = currentUri;
device.TransportState = transportState;
device.Volume = double.Parse(currentVolume);
device.IsMaster = string.IsNullOrEmpty(trackUri) || !trackUri.StartsWith("x-rincon:RINCON");
device.Zone = zoneAttributes["CurrentZoneName"] ?? string.Empty;
var master = GetMaster(device);
if (!ReferenceEquals(master, device))
{
device.TransportState = master.TransportState;
}
UpdateVariable(device, "TransportState", device.TransportState);
UpdateVariable(device, "CurrentUri", device.CurrentUri);
UpdateVariable(device, "Volume", device.Volume);
UpdateVariable(device, "IsMaster", device.IsMaster);
UpdateVariable(device, "Zone", device.Zone);
}
private SonosDevice GetMaster(SonosDevice device)
{
if (device.IsMaster)
{
return device;
}
var masterId = device.CurrentUri?.Replace("x-rincon:", string.Empty) ?? string.Empty;
var master = (SonosDevice) Devices.SingleOrDefault(d => d.Id.Equals(masterId, StringComparison.OrdinalIgnoreCase));
return master ?? device;
}
private string ReplaceScheme(string url, string scheme)
{
var uri = new Uri(url);
if (uri.Scheme.StartsWith("x-", StringComparison.OrdinalIgnoreCase))
{
return url;
}
var path = HttpUtility.UrlDecode(uri.PathAndQuery);
return $"{scheme}://{uri.Authority}{path}";
}
private async Task SendUrl(SonosDevice device, string url, string metadata)
{
metadata = HttpUtility.HtmlEncode(metadata);
url = HttpUtility.HtmlEncode(url);
var service = device.Services.Single(s => s.Id.Contains("AVTransport"));
var action = service.Actions.Single(s => s.Name.Equals("SetAVTransportURI"));
var values = new Dictionary<string, string>
{
{"InstanceID", "0"},
{"CurrentURI", url},
{"CurrentURIMetaData", metadata}
};
await _soapClient.ExecuteAsync(device, service, action, values);
}
private async Task SendAvTransportControl(SonosDevice device, string command)
{
var service = device.Services.Single(s => s.Id.Contains("AVTransport"));
var action = service.Actions.Single(s => s.Name.Equals(command));
var values = new Dictionary<string, string>
{
{"InstanceID", "0"},
{"Speed", "1"}
};
await _soapClient.ExecuteAsync(device, service, action, values);
}
private string GetRadioMetadata(string title)
{
var didl = $"<DIDL-Lite xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:upnp=\"urn:schemas-upnp-org:metadata-1-0/upnp/\" xmlns:r=\"urn:schemas-rinconnetworks-com:metadata-1-0/\" xmlns=\"urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/\"><item id=\"R:0/0/0\" parentID=\"R:0/0\" restricted=\"true\"><dc:title>{title}</dc:title><upnp:class>object.item.audioItem.audioBroadcast</upnp:class><desc id=\"cdudn\" nameSpace=\"urn:schemas-rinconnetworks-com:metadata-1-0/\">SA_RINCON65031_</desc></item></DIDL-Lite>";
return didl;
}
private string GetFileMetadata(string title, string album)
{
return null;
}
private void UpdateVariable(SonosDevice device, string variable, object value)
{
_messageQueue.Publish(new UpdateVariableMessage(Name, device.Id, variable, value));
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System.Collections.Generic;
using OpenMetaverse;
using Aurora.Framework;
using OpenSim.Region.Framework.Scenes;
namespace Aurora.Modules.Terrain.PaintBrushes
{
///<summary>
/// Speed-Optimised Hybrid Erosion Brush
///
/// As per Jacob Olsen's Paper
/// http://www.oddlabs.com/download/terrain_generation.pdf
///</summary>
public class OlsenSphere : ITerrainPaintableEffect
{
private const float nConst = 1024;
private const NeighbourSystem type = NeighbourSystem.Moore;
#region Supporting Functions
private static int[] Neighbours(NeighbourSystem neighbourType, int index)
{
int[] coord = new int[2];
index++;
switch (neighbourType)
{
case NeighbourSystem.Moore:
switch (index)
{
case 1:
coord[0] = -1;
coord[1] = -1;
break;
case 2:
coord[0] = -0;
coord[1] = -1;
break;
case 3:
coord[0] = +1;
coord[1] = -1;
break;
case 4:
coord[0] = -1;
coord[1] = -0;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
case 6:
coord[0] = +1;
coord[1] = -0;
break;
case 7:
coord[0] = -1;
coord[1] = +1;
break;
case 8:
coord[0] = -0;
coord[1] = +1;
break;
case 9:
coord[0] = +1;
coord[1] = +1;
break;
default:
break;
}
break;
case NeighbourSystem.VonNeumann:
switch (index)
{
case 1:
coord[0] = 0;
coord[1] = -1;
break;
case 2:
coord[0] = -1;
coord[1] = 0;
break;
case 3:
coord[0] = +1;
coord[1] = 0;
break;
case 4:
coord[0] = 0;
coord[1] = +1;
break;
case 5:
coord[0] = -0;
coord[1] = -0;
break;
default:
break;
}
break;
}
return coord;
}
private enum NeighbourSystem
{
Moore,
VonNeumann
};
#endregion
#region ITerrainPaintableEffect Members
public void PaintEffect(ITerrainChannel map, UUID userID, float rx, float ry, float rz, float strength,
float duration, float BrushSize, List<IScene> scene)
{
strength = TerrainUtil.MetersToSphericalStrength(strength);
int x;
int xFrom = (int) (rx - BrushSize + 0.5);
int xTo = (int) (rx + BrushSize + 0.5) + 1;
int yFrom = (int) (ry - BrushSize + 0.5);
int yTo = (int) (ry + BrushSize + 0.5) + 1;
if (xFrom < 0)
xFrom = 0;
if (yFrom < 0)
yFrom = 0;
if (xTo > map.Width)
xTo = map.Width;
if (yTo > map.Height)
yTo = map.Height;
for (x = xFrom; x < xTo; x++)
{
int y;
for (y = yFrom; y < yTo; y++)
{
if (!map.Scene.Permissions.CanTerraformLand(userID, new Vector3(x, y, 0)))
continue;
float z = TerrainUtil.SphericalFactor(x, y, rx, ry, strength);
if (z > 0) // add in non-zero amount
{
const int NEIGHBOUR_ME = 4;
const int NEIGHBOUR_MAX = 9;
float max = float.MinValue;
int loc = 0;
for (int j = 0; j < NEIGHBOUR_MAX; j++)
{
if (j != NEIGHBOUR_ME)
{
int[] coords = Neighbours(type, j);
coords[0] += x;
coords[1] += y;
if (coords[0] > map.Width - 1)
continue;
if (coords[1] > map.Height - 1)
continue;
if (coords[0] < 0)
continue;
if (coords[1] < 0)
continue;
float cellmax = map[x, y] - map[coords[0], coords[1]];
if (cellmax > max)
{
max = cellmax;
loc = j;
}
}
}
float T = nConst/((map.Width + map.Height)/2);
// Apply results
if (0 < max && max <= T)
{
int[] maxCoords = Neighbours(type, loc);
float heightDelta = 0.5f*max*z*duration;
map[x, y] -= heightDelta;
map[x + maxCoords[0], y + maxCoords[1]] += heightDelta;
}
}
}
}
}
#endregion
}
}
| |
namespace SandcastleBuilder.Utils.Design
{
partial class ApiFilterEditorDlg
{
/// <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)
{
if(italicFont != null)
italicFont.Dispose();
if(components != null)
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Documented APIs", 46, 46);
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Inherited APIs", 47, 47);
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ApiFilterEditorDlg));
this.btnClose = new System.Windows.Forms.Button();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
this.btnReset = new System.Windows.Forms.Button();
this.btnFind = new System.Windows.Forms.Button();
this.btnGoto = new System.Windows.Forms.Button();
this.btnInclude = new System.Windows.Forms.Button();
this.btnExclude = new System.Windows.Forms.Button();
this.btnHelp = new System.Windows.Forms.Button();
this.tvApiList = new System.Windows.Forms.TreeView();
this.ilTreeImages = new System.Windows.Forms.ImageList(this.components);
this.splitContainer = new System.Windows.Forms.SplitContainer();
this.lblLoading = new System.Windows.Forms.Label();
this.pbWait = new System.Windows.Forms.PictureBox();
this.lvSearchResults = new System.Windows.Forms.ListView();
this.colMember = new System.Windows.Forms.ColumnHeader();
this.colFullName = new System.Windows.Forms.ColumnHeader();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.pnlOptions = new System.Windows.Forms.FlowLayoutPanel();
this.chkCaseSensitive = new System.Windows.Forms.CheckBox();
this.chkFullyQualified = new System.Windows.Forms.CheckBox();
this.chkNamespaces = new System.Windows.Forms.CheckBox();
this.chkClasses = new System.Windows.Forms.CheckBox();
this.chkStructures = new System.Windows.Forms.CheckBox();
this.chkInterfaces = new System.Windows.Forms.CheckBox();
this.chkEnumerations = new System.Windows.Forms.CheckBox();
this.chkDelegates = new System.Windows.Forms.CheckBox();
this.chkConstructors = new System.Windows.Forms.CheckBox();
this.chkMethods = new System.Windows.Forms.CheckBox();
this.chkOperators = new System.Windows.Forms.CheckBox();
this.chkProperties = new System.Windows.Forms.CheckBox();
this.chkEvents = new System.Windows.Forms.CheckBox();
this.chkFields = new System.Windows.Forms.CheckBox();
this.chkPublic = new System.Windows.Forms.CheckBox();
this.chkProtected = new System.Windows.Forms.CheckBox();
this.chkInternal = new System.Windows.Forms.CheckBox();
this.chkPrivate = new System.Windows.Forms.CheckBox();
this.txtSearchText = new System.Windows.Forms.TextBox();
this.lblProgress = new System.Windows.Forms.Label();
this.epErrors = new System.Windows.Forms.ErrorProvider(this.components);
this.statusBarTextProvider1 = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components);
this.splitContainer.Panel1.SuspendLayout();
this.splitContainer.Panel2.SuspendLayout();
this.splitContainer.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pbWait)).BeginInit();
this.groupBox1.SuspendLayout();
this.pnlOptions.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.epErrors)).BeginInit();
this.SuspendLayout();
//
// btnClose
//
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnClose.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnClose.Location = new System.Drawing.Point(842, 611);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnClose, "Close: Close this form");
this.btnClose.TabIndex = 4;
this.btnClose.Text = "Close";
this.toolTip1.SetToolTip(this.btnClose, "Close this form");
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
//
// btnReset
//
this.btnReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnReset.Location = new System.Drawing.Point(748, 611);
this.btnReset.Name = "btnReset";
this.btnReset.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnReset, "Reset: Reset the API filter to its default state");
this.btnReset.TabIndex = 3;
this.btnReset.Text = "&Reset";
this.toolTip1.SetToolTip(this.btnReset, "Reset the API filter");
this.btnReset.UseVisualStyleBackColor = true;
this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
//
// btnFind
//
this.btnFind.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnFind.Location = new System.Drawing.Point(500, 16);
this.btnFind.Name = "btnFind";
this.btnFind.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnFind, "Find: Find all members matching the search expression");
this.btnFind.TabIndex = 1;
this.btnFind.Text = "&Find";
this.toolTip1.SetToolTip(this.btnFind, "Find matching members");
this.btnFind.UseVisualStyleBackColor = true;
this.btnFind.Click += new System.EventHandler(this.btnFind_Click);
//
// btnGoto
//
this.btnGoto.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnGoto.Enabled = false;
this.btnGoto.Location = new System.Drawing.Point(3, 558);
this.btnGoto.Name = "btnGoto";
this.btnGoto.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnGoto, "Goto: Goto the selected member in the tree view");
this.btnGoto.TabIndex = 3;
this.btnGoto.Text = "&Goto";
this.toolTip1.SetToolTip(this.btnGoto, "Goto the selected member");
this.btnGoto.UseVisualStyleBackColor = true;
this.btnGoto.Click += new System.EventHandler(this.btnGoto_Click);
//
// btnInclude
//
this.btnInclude.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnInclude.Enabled = false;
this.btnInclude.Location = new System.Drawing.Point(97, 558);
this.btnInclude.Name = "btnInclude";
this.btnInclude.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnInclude, "Include: Include the selected members");
this.btnInclude.TabIndex = 4;
this.btnInclude.Text = "&Include";
this.toolTip1.SetToolTip(this.btnInclude, "Include selected members");
this.btnInclude.UseVisualStyleBackColor = true;
this.btnInclude.Click += new System.EventHandler(this.btnIncludeExclude_Click);
//
// btnExclude
//
this.btnExclude.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
this.btnExclude.Enabled = false;
this.btnExclude.Location = new System.Drawing.Point(191, 558);
this.btnExclude.Name = "btnExclude";
this.btnExclude.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnExclude, "Exclude: Exclude the selected members");
this.btnExclude.TabIndex = 5;
this.btnExclude.Text = "&Exclude";
this.toolTip1.SetToolTip(this.btnExclude, "Exclude the selected members");
this.btnExclude.UseVisualStyleBackColor = true;
this.btnExclude.Click += new System.EventHandler(this.btnIncludeExclude_Click);
//
// btnHelp
//
this.btnHelp.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.btnHelp.Location = new System.Drawing.Point(654, 611);
this.btnHelp.Name = "btnHelp";
this.btnHelp.Size = new System.Drawing.Size(88, 32);
this.statusBarTextProvider1.SetStatusBarText(this.btnHelp, "Help: View help for this form");
this.btnHelp.TabIndex = 2;
this.btnHelp.Text = "&Help";
this.toolTip1.SetToolTip(this.btnHelp, "View help for this form");
this.btnHelp.UseVisualStyleBackColor = true;
this.btnHelp.Click += new System.EventHandler(this.btnHelp_Click);
//
// tvApiList
//
this.tvApiList.CheckBoxes = true;
this.tvApiList.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvApiList.HideSelection = false;
this.tvApiList.ImageIndex = 0;
this.tvApiList.ImageList = this.ilTreeImages;
this.tvApiList.Location = new System.Drawing.Point(0, 0);
this.tvApiList.Name = "tvApiList";
treeNode1.Checked = true;
treeNode1.ImageIndex = 46;
treeNode1.Name = "docNode";
treeNode1.SelectedImageIndex = 46;
treeNode1.Text = "Documented APIs";
treeNode1.ToolTipText = "Documented APIs in your assemblies";
treeNode2.Checked = true;
treeNode2.ImageIndex = 47;
treeNode2.Name = "inheritedNode";
treeNode2.SelectedImageIndex = 47;
treeNode2.Text = "Inherited APIs";
treeNode2.ToolTipText = "APIs inherited from classes in dependent assemblies and the .NET Framework";
this.tvApiList.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode2});
this.tvApiList.SelectedImageIndex = 0;
this.tvApiList.ShowNodeToolTips = true;
this.tvApiList.Size = new System.Drawing.Size(308, 593);
this.statusBarTextProvider1.SetStatusBarText(this.tvApiList, "The API list to filter");
this.tvApiList.TabIndex = 1;
this.tvApiList.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.tvApiList_AfterCheck);
this.tvApiList.BeforeExpand += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvApiList_BeforeExpand);
this.tvApiList.BeforeCheck += new System.Windows.Forms.TreeViewCancelEventHandler(this.tvApiList_BeforeCheck);
//
// ilTreeImages
//
this.ilTreeImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilTreeImages.ImageStream")));
this.ilTreeImages.TransparentColor = System.Drawing.Color.Magenta;
this.ilTreeImages.Images.SetKeyName(0, "Api_Unknown.bmp");
this.ilTreeImages.Images.SetKeyName(1, "Api_Namespace.bmp");
this.ilTreeImages.Images.SetKeyName(2, "Api_Public_Class.bmp");
this.ilTreeImages.Images.SetKeyName(3, "Api_Public_Structure.bmp");
this.ilTreeImages.Images.SetKeyName(4, "Api_Public_Interface.bmp");
this.ilTreeImages.Images.SetKeyName(5, "Api_Public_Enum.bmp");
this.ilTreeImages.Images.SetKeyName(6, "Api_Public_Delegate.bmp");
this.ilTreeImages.Images.SetKeyName(7, "Api_Public_Constructor.bmp");
this.ilTreeImages.Images.SetKeyName(8, "Api_Public_Method.bmp");
this.ilTreeImages.Images.SetKeyName(9, "Api_Public_Operator.bmp");
this.ilTreeImages.Images.SetKeyName(10, "Api_Public_Property.bmp");
this.ilTreeImages.Images.SetKeyName(11, "Api_Public_Event.bmp");
this.ilTreeImages.Images.SetKeyName(12, "Api_Public_Field.bmp");
this.ilTreeImages.Images.SetKeyName(13, "Api_Protected_Class.bmp");
this.ilTreeImages.Images.SetKeyName(14, "Api_Protected_Structure.bmp");
this.ilTreeImages.Images.SetKeyName(15, "Api_Protected_Interface.bmp");
this.ilTreeImages.Images.SetKeyName(16, "Api_Protected_Enum.bmp");
this.ilTreeImages.Images.SetKeyName(17, "Api_Protected_Delegate.bmp");
this.ilTreeImages.Images.SetKeyName(18, "Api_Protected_Constructor.bmp");
this.ilTreeImages.Images.SetKeyName(19, "Api_Protected_Method.bmp");
this.ilTreeImages.Images.SetKeyName(20, "Api_Protected_Operator.bmp");
this.ilTreeImages.Images.SetKeyName(21, "Api_Protected_Property.bmp");
this.ilTreeImages.Images.SetKeyName(22, "Api_Protected_Event.bmp");
this.ilTreeImages.Images.SetKeyName(23, "Api_Protected_Field.bmp");
this.ilTreeImages.Images.SetKeyName(24, "Api_Internal_Class.bmp");
this.ilTreeImages.Images.SetKeyName(25, "Api_Internal_Structure.bmp");
this.ilTreeImages.Images.SetKeyName(26, "Api_Internal_Interface.bmp");
this.ilTreeImages.Images.SetKeyName(27, "Api_Internal_Enum.bmp");
this.ilTreeImages.Images.SetKeyName(28, "Api_Internal_Delegate.bmp");
this.ilTreeImages.Images.SetKeyName(29, "Api_Internal_Constructor.bmp");
this.ilTreeImages.Images.SetKeyName(30, "Api_Internal_Method.bmp");
this.ilTreeImages.Images.SetKeyName(31, "Api_Internal_Operator.bmp");
this.ilTreeImages.Images.SetKeyName(32, "Api_Internal_Property.bmp");
this.ilTreeImages.Images.SetKeyName(33, "Api_Internal_Event.bmp");
this.ilTreeImages.Images.SetKeyName(34, "Api_Internal_Field.bmp");
this.ilTreeImages.Images.SetKeyName(35, "Api_Private_Class.bmp");
this.ilTreeImages.Images.SetKeyName(36, "Api_Private_Structure.bmp");
this.ilTreeImages.Images.SetKeyName(37, "Api_Private_Interface.bmp");
this.ilTreeImages.Images.SetKeyName(38, "Api_Private_Enum.bmp");
this.ilTreeImages.Images.SetKeyName(39, "Api_Private_Delegate.bmp");
this.ilTreeImages.Images.SetKeyName(40, "Api_Private_Constructor.bmp");
this.ilTreeImages.Images.SetKeyName(41, "Api_Private_Method.bmp");
this.ilTreeImages.Images.SetKeyName(42, "Api_Private_Operator.bmp");
this.ilTreeImages.Images.SetKeyName(43, "Api_Private_Property.bmp");
this.ilTreeImages.Images.SetKeyName(44, "Api_Private_Event.bmp");
this.ilTreeImages.Images.SetKeyName(45, "Api_Private_Field.bmp");
this.ilTreeImages.Images.SetKeyName(46, "Api_Documented.bmp");
this.ilTreeImages.Images.SetKeyName(47, "Api_Undocumented.bmp");
this.ilTreeImages.Images.SetKeyName(48, "Api_Protected.bmp");
this.ilTreeImages.Images.SetKeyName(49, "Api_Internal.bmp");
this.ilTreeImages.Images.SetKeyName(50, "Api_Private.bmp");
//
// splitContainer
//
this.splitContainer.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer.Location = new System.Drawing.Point(12, 12);
this.splitContainer.Name = "splitContainer";
//
// splitContainer.Panel1
//
this.splitContainer.Panel1.Controls.Add(this.lblLoading);
this.splitContainer.Panel1.Controls.Add(this.pbWait);
this.splitContainer.Panel1.Controls.Add(this.tvApiList);
//
// splitContainer.Panel2
//
this.splitContainer.Panel2.BackColor = System.Drawing.SystemColors.Control;
this.splitContainer.Panel2.Controls.Add(this.btnExclude);
this.splitContainer.Panel2.Controls.Add(this.btnInclude);
this.splitContainer.Panel2.Controls.Add(this.btnGoto);
this.splitContainer.Panel2.Controls.Add(this.lvSearchResults);
this.splitContainer.Panel2.Controls.Add(this.groupBox1);
this.splitContainer.Size = new System.Drawing.Size(918, 593);
this.splitContainer.SplitterDistance = 308;
this.splitContainer.SplitterWidth = 10;
this.splitContainer.TabIndex = 0;
//
// lblLoading
//
this.lblLoading.AutoSize = true;
this.lblLoading.BackColor = System.Drawing.SystemColors.Window;
this.lblLoading.Location = new System.Drawing.Point(50, 85);
this.lblLoading.Name = "lblLoading";
this.lblLoading.Size = new System.Drawing.Size(155, 17);
this.lblLoading.TabIndex = 0;
this.lblLoading.Text = "Loading namespaces...";
//
// pbWait
//
this.pbWait.BackColor = System.Drawing.SystemColors.Window;
this.pbWait.Image = global::SandcastleBuilder.Utils.Properties.Resources.SpinningWheel;
this.pbWait.Location = new System.Drawing.Point(12, 77);
this.pbWait.Name = "pbWait";
this.pbWait.Size = new System.Drawing.Size(32, 32);
this.pbWait.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.pbWait.TabIndex = 7;
this.pbWait.TabStop = false;
//
// lvSearchResults
//
this.lvSearchResults.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lvSearchResults.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colMember,
this.colFullName});
this.lvSearchResults.FullRowSelect = true;
this.lvSearchResults.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable;
this.lvSearchResults.HideSelection = false;
this.lvSearchResults.Location = new System.Drawing.Point(3, 217);
this.lvSearchResults.Name = "lvSearchResults";
this.lvSearchResults.Size = new System.Drawing.Size(594, 335);
this.lvSearchResults.SmallImageList = this.ilTreeImages;
this.lvSearchResults.TabIndex = 1;
this.lvSearchResults.UseCompatibleStateImageBehavior = false;
this.lvSearchResults.View = System.Windows.Forms.View.Details;
this.lvSearchResults.DoubleClick += new System.EventHandler(this.lvSearchResults_DoubleClick);
//
// colMember
//
this.colMember.Text = "Members Found";
this.colMember.Width = 200;
//
// colFullName
//
this.colFullName.Text = "Full Name";
this.colFullName.Width = 350;
//
// groupBox1
//
this.groupBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.groupBox1.Controls.Add(this.pnlOptions);
this.groupBox1.Controls.Add(this.btnFind);
this.groupBox1.Controls.Add(this.txtSearchText);
this.groupBox1.Location = new System.Drawing.Point(3, 3);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(594, 208);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "&Search Options";
//
// pnlOptions
//
this.pnlOptions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.pnlOptions.AutoScroll = true;
this.pnlOptions.Controls.Add(this.chkCaseSensitive);
this.pnlOptions.Controls.Add(this.chkFullyQualified);
this.pnlOptions.Controls.Add(this.chkNamespaces);
this.pnlOptions.Controls.Add(this.chkClasses);
this.pnlOptions.Controls.Add(this.chkStructures);
this.pnlOptions.Controls.Add(this.chkInterfaces);
this.pnlOptions.Controls.Add(this.chkEnumerations);
this.pnlOptions.Controls.Add(this.chkDelegates);
this.pnlOptions.Controls.Add(this.chkConstructors);
this.pnlOptions.Controls.Add(this.chkMethods);
this.pnlOptions.Controls.Add(this.chkOperators);
this.pnlOptions.Controls.Add(this.chkProperties);
this.pnlOptions.Controls.Add(this.chkEvents);
this.pnlOptions.Controls.Add(this.chkFields);
this.pnlOptions.Controls.Add(this.chkPublic);
this.pnlOptions.Controls.Add(this.chkProtected);
this.pnlOptions.Controls.Add(this.chkInternal);
this.pnlOptions.Controls.Add(this.chkPrivate);
this.pnlOptions.Location = new System.Drawing.Point(6, 49);
this.pnlOptions.Name = "pnlOptions";
this.pnlOptions.Size = new System.Drawing.Size(582, 151);
this.pnlOptions.TabIndex = 2;
//
// chkCaseSensitive
//
this.chkCaseSensitive.Location = new System.Drawing.Point(3, 3);
this.chkCaseSensitive.Name = "chkCaseSensitive";
this.chkCaseSensitive.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkCaseSensitive, "Perform a case-sensitive search");
this.chkCaseSensitive.TabIndex = 0;
this.chkCaseSensitive.Text = "Case-sensitive";
this.chkCaseSensitive.UseVisualStyleBackColor = true;
//
// chkFullyQualified
//
this.chkFullyQualified.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkFullyQualified.ImageIndex = 11;
this.chkFullyQualified.Location = new System.Drawing.Point(144, 3);
this.chkFullyQualified.Name = "chkFullyQualified";
this.chkFullyQualified.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkFullyQualified, "Search the fully-qualified names rather than just the member names");
this.chkFullyQualified.TabIndex = 1;
this.chkFullyQualified.Text = "Fully-qualified";
this.chkFullyQualified.UseVisualStyleBackColor = true;
//
// chkNamespaces
//
this.chkNamespaces.Checked = true;
this.chkNamespaces.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkNamespaces.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkNamespaces.ImageIndex = 1;
this.chkNamespaces.ImageList = this.ilTreeImages;
this.chkNamespaces.Location = new System.Drawing.Point(285, 3);
this.chkNamespaces.Name = "chkNamespaces";
this.chkNamespaces.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkNamespaces, "Include namespaces in the results");
this.chkNamespaces.TabIndex = 2;
this.chkNamespaces.Text = "Namespaces";
this.chkNamespaces.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkNamespaces.UseVisualStyleBackColor = true;
//
// chkClasses
//
this.chkClasses.Checked = true;
this.chkClasses.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkClasses.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkClasses.ImageIndex = 2;
this.chkClasses.ImageList = this.ilTreeImages;
this.chkClasses.Location = new System.Drawing.Point(426, 3);
this.chkClasses.Name = "chkClasses";
this.chkClasses.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkClasses, "Include classes in the results");
this.chkClasses.TabIndex = 3;
this.chkClasses.Text = "Classes";
this.chkClasses.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkClasses.UseVisualStyleBackColor = true;
//
// chkStructures
//
this.chkStructures.Checked = true;
this.chkStructures.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkStructures.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkStructures.ImageIndex = 3;
this.chkStructures.ImageList = this.ilTreeImages;
this.chkStructures.Location = new System.Drawing.Point(3, 33);
this.chkStructures.Name = "chkStructures";
this.chkStructures.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkStructures, "Include structures in the results");
this.chkStructures.TabIndex = 4;
this.chkStructures.Text = "Structures";
this.chkStructures.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkStructures.UseVisualStyleBackColor = true;
//
// chkInterfaces
//
this.chkInterfaces.Checked = true;
this.chkInterfaces.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkInterfaces.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkInterfaces.ImageIndex = 4;
this.chkInterfaces.ImageList = this.ilTreeImages;
this.chkInterfaces.Location = new System.Drawing.Point(144, 33);
this.chkInterfaces.Name = "chkInterfaces";
this.chkInterfaces.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkInterfaces, "Include interfaces in the results");
this.chkInterfaces.TabIndex = 5;
this.chkInterfaces.Text = "Interfaces";
this.chkInterfaces.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkInterfaces.UseVisualStyleBackColor = true;
//
// chkEnumerations
//
this.chkEnumerations.Checked = true;
this.chkEnumerations.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkEnumerations.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkEnumerations.ImageIndex = 5;
this.chkEnumerations.ImageList = this.ilTreeImages;
this.chkEnumerations.Location = new System.Drawing.Point(285, 33);
this.chkEnumerations.Name = "chkEnumerations";
this.chkEnumerations.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkEnumerations, "Include enumerations in the results");
this.chkEnumerations.TabIndex = 6;
this.chkEnumerations.Text = "Enumerations";
this.chkEnumerations.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkEnumerations.UseVisualStyleBackColor = true;
//
// chkDelegates
//
this.chkDelegates.Checked = true;
this.chkDelegates.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkDelegates.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkDelegates.ImageIndex = 6;
this.chkDelegates.ImageList = this.ilTreeImages;
this.chkDelegates.Location = new System.Drawing.Point(426, 33);
this.chkDelegates.Name = "chkDelegates";
this.chkDelegates.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkDelegates, "Include delegates in the results");
this.chkDelegates.TabIndex = 7;
this.chkDelegates.Text = "Delegates";
this.chkDelegates.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkDelegates.UseVisualStyleBackColor = true;
//
// chkConstructors
//
this.chkConstructors.Checked = true;
this.chkConstructors.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkConstructors.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkConstructors.ImageIndex = 7;
this.chkConstructors.ImageList = this.ilTreeImages;
this.chkConstructors.Location = new System.Drawing.Point(3, 63);
this.chkConstructors.Name = "chkConstructors";
this.chkConstructors.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkConstructors, "Include constructors in the results");
this.chkConstructors.TabIndex = 8;
this.chkConstructors.Text = "Constructors";
this.chkConstructors.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkConstructors.UseVisualStyleBackColor = true;
//
// chkMethods
//
this.chkMethods.Checked = true;
this.chkMethods.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkMethods.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkMethods.ImageIndex = 8;
this.chkMethods.ImageList = this.ilTreeImages;
this.chkMethods.Location = new System.Drawing.Point(144, 63);
this.chkMethods.Name = "chkMethods";
this.chkMethods.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkMethods, "Include methods in the results");
this.chkMethods.TabIndex = 9;
this.chkMethods.Text = "Methods";
this.chkMethods.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkMethods.UseVisualStyleBackColor = true;
//
// chkOperators
//
this.chkOperators.Checked = true;
this.chkOperators.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkOperators.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkOperators.ImageIndex = 9;
this.chkOperators.ImageList = this.ilTreeImages;
this.chkOperators.Location = new System.Drawing.Point(285, 63);
this.chkOperators.Name = "chkOperators";
this.chkOperators.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkOperators, "Include operators in the results");
this.chkOperators.TabIndex = 13;
this.chkOperators.Text = "Operators";
this.chkOperators.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkOperators.UseVisualStyleBackColor = true;
//
// chkProperties
//
this.chkProperties.Checked = true;
this.chkProperties.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkProperties.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkProperties.ImageIndex = 10;
this.chkProperties.ImageList = this.ilTreeImages;
this.chkProperties.Location = new System.Drawing.Point(426, 63);
this.chkProperties.Name = "chkProperties";
this.chkProperties.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkProperties, "Include properties in the results");
this.chkProperties.TabIndex = 10;
this.chkProperties.Text = "Properties";
this.chkProperties.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkProperties.UseVisualStyleBackColor = true;
//
// chkEvents
//
this.chkEvents.Checked = true;
this.chkEvents.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkEvents.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkEvents.ImageIndex = 11;
this.chkEvents.ImageList = this.ilTreeImages;
this.chkEvents.Location = new System.Drawing.Point(3, 93);
this.chkEvents.Name = "chkEvents";
this.chkEvents.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkEvents, "Include events in the results");
this.chkEvents.TabIndex = 11;
this.chkEvents.Text = "Events";
this.chkEvents.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkEvents.UseVisualStyleBackColor = true;
//
// chkFields
//
this.chkFields.Checked = true;
this.chkFields.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkFields.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkFields.ImageIndex = 12;
this.chkFields.ImageList = this.ilTreeImages;
this.chkFields.Location = new System.Drawing.Point(144, 93);
this.chkFields.Name = "chkFields";
this.chkFields.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkFields, "Include fields in the results");
this.chkFields.TabIndex = 12;
this.chkFields.Text = "Fields";
this.chkFields.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkFields.UseVisualStyleBackColor = true;
//
// chkPublic
//
this.chkPublic.Checked = true;
this.chkPublic.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkPublic.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkPublic.ImageList = this.ilTreeImages;
this.chkPublic.Location = new System.Drawing.Point(285, 93);
this.chkPublic.Name = "chkPublic";
this.chkPublic.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkPublic, "Include public members in the results");
this.chkPublic.TabIndex = 14;
this.chkPublic.Text = "Public";
this.chkPublic.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkPublic.UseVisualStyleBackColor = true;
//
// chkProtected
//
this.chkProtected.Checked = true;
this.chkProtected.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkProtected.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkProtected.ImageIndex = 48;
this.chkProtected.ImageList = this.ilTreeImages;
this.chkProtected.Location = new System.Drawing.Point(426, 93);
this.chkProtected.Name = "chkProtected";
this.chkProtected.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkProtected, "Include protected members in the results");
this.chkProtected.TabIndex = 15;
this.chkProtected.Text = "Protected";
this.chkProtected.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkProtected.UseVisualStyleBackColor = true;
//
// chkInternal
//
this.chkInternal.Checked = true;
this.chkInternal.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkInternal.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkInternal.ImageIndex = 49;
this.chkInternal.ImageList = this.ilTreeImages;
this.chkInternal.Location = new System.Drawing.Point(3, 123);
this.chkInternal.Name = "chkInternal";
this.chkInternal.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkInternal, "Include internal members in the results");
this.chkInternal.TabIndex = 16;
this.chkInternal.Text = "Internal";
this.chkInternal.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkInternal.UseVisualStyleBackColor = true;
//
// chkPrivate
//
this.chkPrivate.Checked = true;
this.chkPrivate.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkPrivate.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.chkPrivate.ImageIndex = 50;
this.chkPrivate.ImageList = this.ilTreeImages;
this.chkPrivate.Location = new System.Drawing.Point(144, 123);
this.chkPrivate.Name = "chkPrivate";
this.chkPrivate.Size = new System.Drawing.Size(135, 24);
this.statusBarTextProvider1.SetStatusBarText(this.chkPrivate, "Include private members in the results");
this.chkPrivate.TabIndex = 17;
this.chkPrivate.Text = "Private";
this.chkPrivate.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageBeforeText;
this.chkPrivate.UseVisualStyleBackColor = true;
//
// txtSearchText
//
this.txtSearchText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtSearchText.Location = new System.Drawing.Point(6, 21);
this.txtSearchText.Name = "txtSearchText";
this.txtSearchText.Size = new System.Drawing.Size(471, 22);
this.statusBarTextProvider1.SetStatusBarText(this.txtSearchText, "Search Text: Enter a string or regular expression for which to search");
this.txtSearchText.TabIndex = 0;
//
// lblProgress
//
this.lblProgress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.lblProgress.AutoEllipsis = true;
this.lblProgress.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblProgress.Location = new System.Drawing.Point(12, 616);
this.lblProgress.Name = "lblProgress";
this.lblProgress.Size = new System.Drawing.Size(636, 23);
this.lblProgress.TabIndex = 1;
this.lblProgress.Text = "--";
this.lblProgress.TextAlign = System.Drawing.ContentAlignment.MiddleLeft;
//
// epErrors
//
this.epErrors.ContainerControl = this;
//
// ApiFilterEditorDlg
//
this.AcceptButton = this.btnFind;
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
this.CancelButton = this.btnClose;
this.ClientSize = new System.Drawing.Size(942, 660);
this.Controls.Add(this.btnHelp);
this.Controls.Add(this.btnReset);
this.Controls.Add(this.lblProgress);
this.Controls.Add(this.splitContainer);
this.Controls.Add(this.btnClose);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimizeBox = false;
this.MinimumSize = new System.Drawing.Size(950, 600);
this.Name = "ApiFilterEditorDlg";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "API Filter";
this.Load += new System.EventHandler(this.ApiFilterEditorDlg_Load);
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.ApiFilterEditorDlg_FormClosing);
this.splitContainer.Panel1.ResumeLayout(false);
this.splitContainer.Panel1.PerformLayout();
this.splitContainer.Panel2.ResumeLayout(false);
this.splitContainer.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.pbWait)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.pnlOptions.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.epErrors)).EndInit();
this.ResumeLayout(false);
}
#endregion
private SandcastleBuilder.Utils.Controls.StatusBarTextProvider statusBarTextProvider1;
private System.Windows.Forms.ToolTip toolTip1;
private System.Windows.Forms.Button btnClose;
private System.Windows.Forms.SplitContainer splitContainer;
private System.Windows.Forms.TreeView tvApiList;
private System.Windows.Forms.Label lblLoading;
private System.Windows.Forms.PictureBox pbWait;
private System.Windows.Forms.Label lblProgress;
private System.Windows.Forms.ImageList ilTreeImages;
private System.Windows.Forms.Button btnReset;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnFind;
private System.Windows.Forms.TextBox txtSearchText;
private System.Windows.Forms.ErrorProvider epErrors;
private System.Windows.Forms.ListView lvSearchResults;
private System.Windows.Forms.ColumnHeader colMember;
private System.Windows.Forms.FlowLayoutPanel pnlOptions;
private System.Windows.Forms.CheckBox chkCaseSensitive;
private System.Windows.Forms.CheckBox chkNamespaces;
private System.Windows.Forms.CheckBox chkClasses;
private System.Windows.Forms.CheckBox chkStructures;
private System.Windows.Forms.CheckBox chkInterfaces;
private System.Windows.Forms.CheckBox chkEnumerations;
private System.Windows.Forms.CheckBox chkDelegates;
private System.Windows.Forms.CheckBox chkConstructors;
private System.Windows.Forms.CheckBox chkMethods;
private System.Windows.Forms.CheckBox chkProperties;
private System.Windows.Forms.CheckBox chkEvents;
private System.Windows.Forms.CheckBox chkFields;
private System.Windows.Forms.ColumnHeader colFullName;
private System.Windows.Forms.CheckBox chkFullyQualified;
private System.Windows.Forms.Button btnGoto;
private System.Windows.Forms.Button btnInclude;
private System.Windows.Forms.Button btnExclude;
private System.Windows.Forms.CheckBox chkOperators;
private System.Windows.Forms.CheckBox chkPublic;
private System.Windows.Forms.CheckBox chkProtected;
private System.Windows.Forms.CheckBox chkInternal;
private System.Windows.Forms.CheckBox chkPrivate;
private System.Windows.Forms.Button btnHelp;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Tagging;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.LineSeparators
{
/// <summary>
/// UI manager for graphic overlay tags. These tags will simply paint something related to the text.
/// </summary>
internal class AdornmentManager<T> where T : GraphicsTag
{
private readonly object _invalidatedSpansLock = new object();
/// <summary>View that created us.</summary>
private readonly IWpfTextView _textView;
/// <summary>Layer where we draw adornments.</summary>
private readonly IAdornmentLayer _adornmentLayer;
/// <summary>Aggregator that tells us where to draw.</summary>
private readonly ITagAggregator<T> _tagAggregator;
/// <summary>Notification system about operations we do</summary>
private readonly IAsynchronousOperationListener _asyncListener;
/// <summary>Spans that are invalidated, and need to be removed from the layer..</summary>
private List<IMappingSpan> _invalidatedSpans;
public static AdornmentManager<T> Create(
IWpfTextView textView,
IViewTagAggregatorFactoryService aggregatorService,
IAsynchronousOperationListener asyncListener,
string adornmentLayerName)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(aggregatorService);
Contract.ThrowIfNull(adornmentLayerName);
Contract.ThrowIfNull(asyncListener);
return new AdornmentManager<T>(textView, aggregatorService, asyncListener, adornmentLayerName);
}
internal AdornmentManager(
IWpfTextView textView,
IViewTagAggregatorFactoryService tagAggregatorFactoryService,
IAsynchronousOperationListener asyncListener,
string adornmentLayerName)
{
Contract.ThrowIfNull(textView);
Contract.ThrowIfNull(tagAggregatorFactoryService);
Contract.ThrowIfNull(adornmentLayerName);
Contract.ThrowIfNull(asyncListener);
_textView = textView;
_adornmentLayer = textView.GetAdornmentLayer(adornmentLayerName);
textView.LayoutChanged += OnLayoutChanged;
_asyncListener = asyncListener;
// If we are not on the UI thread, we are at race with Close, but we should be on UI thread
Contract.ThrowIfFalse(textView.VisualElement.Dispatcher.CheckAccess());
textView.Closed += OnTextViewClosed;
_tagAggregator = tagAggregatorFactoryService.CreateTagAggregator<T>(textView);
_tagAggregator.TagsChanged += OnTagsChanged;
}
private void OnTextViewClosed(object sender, System.EventArgs e)
{
// release the aggregator
_tagAggregator.TagsChanged -= OnTagsChanged;
_tagAggregator.Dispose();
// unhook from view
_textView.Closed -= OnTextViewClosed;
_textView.LayoutChanged -= OnLayoutChanged;
// At this point, this object should be available for garbage collection.
}
/// <summary>
/// This handler gets called whenever there is a visual change in the view.
/// Example: edit or a scroll.
/// </summary>
private void OnLayoutChanged(object sender, TextViewLayoutChangedEventArgs e)
{
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_OnLayoutChanged, CancellationToken.None))
using (_asyncListener.BeginAsyncOperation(GetType() + ".OnLayoutChanged"))
{
// Make sure we're on the UI thread.
Contract.ThrowIfFalse(_textView.VisualElement.Dispatcher.CheckAccess());
var reformattedSpans = e.NewOrReformattedSpans;
var viewSnapshot = _textView.TextSnapshot;
// No need to remove tags as these spans are reformatted anyways.
UpdateSpans_CallOnlyOnUIThread(reformattedSpans, removeOldTags: false);
// Compute any spans that had been invalidated but were not affected by layout.
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (invalidated != null)
{
var invalidatedAndNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
var invalidatedButNotReformatted = NormalizedSnapshotSpanCollection.Difference(
invalidatedAndNormalized,
e.NewOrReformattedSpans);
UpdateSpans_CallOnlyOnUIThread(invalidatedButNotReformatted, removeOldTags: true);
}
}
}
private static NormalizedSnapshotSpanCollection TranslateAndNormalize(
IEnumerable<IMappingSpan> spans,
ITextSnapshot targetSnapshot)
{
Contract.ThrowIfNull(spans);
var translated = spans.SelectMany(span => span.GetSpans(targetSnapshot));
return new NormalizedSnapshotSpanCollection(translated);
}
/// <summary>
/// This handler is called when tag aggregator notifies us about tag changes.
/// </summary>
private void OnTagsChanged(object sender, TagsChangedEventArgs e)
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".OnTagsChanged.1"))
{
var changedSpan = e.Span;
if (changedSpan == null)
{
return; // nothing changed
}
var needToScheduleUpdate = false;
lock (_invalidatedSpansLock)
{
if (_invalidatedSpans == null)
{
// set invalidated spans
var newInvalidatedSpans = new List<IMappingSpan>();
newInvalidatedSpans.Add(changedSpan);
_invalidatedSpans = newInvalidatedSpans;
needToScheduleUpdate = true;
}
else
{
// add to existing invalidated spans
_invalidatedSpans.Add(changedSpan);
}
}
if (needToScheduleUpdate)
{
// schedule an update
var asyncToken = _asyncListener.BeginAsyncOperation(GetType() + ".OnTagsChanged.2");
_textView.VisualElement.Dispatcher.BeginInvoke(
new System.Action(() =>
{
try
{
UpdateInvalidSpans();
}
finally
{
asyncToken.Dispose();
}
}), DispatcherPriority.Render);
}
}
}
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This function is used to update invalidates spans.
/// </summary>
private void UpdateInvalidSpans()
{
using (_asyncListener.BeginAsyncOperation(GetType().Name + ".UpdateInvalidSpans.1"))
using (Logger.LogBlock(FunctionId.Tagger_AdornmentManager_UpdateInvalidSpans, CancellationToken.None))
{
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(_textView.VisualElement.Dispatcher.CheckAccess());
List<IMappingSpan> invalidated;
lock (_invalidatedSpansLock)
{
invalidated = _invalidatedSpans;
_invalidatedSpans = null;
}
if (_textView.IsClosed)
{
return; // already closed
}
if (invalidated != null)
{
var viewSnapshot = _textView.TextSnapshot;
var invalidatedNormalized = TranslateAndNormalize(invalidated, viewSnapshot);
UpdateSpans_CallOnlyOnUIThread(invalidatedNormalized, removeOldTags: true);
}
}
}
/// <summary>
/// MUST BE CALLED ON UI THREAD!!!! This method touches WPF.
///
/// This is where we apply visuals to the text.
///
/// It happens when another region of the view becomes visible or there is a change in tags.
/// For us the end result is the same - get tags from tagger and update visuals correspondingly.
/// </summary>
private void UpdateSpans_CallOnlyOnUIThread(NormalizedSnapshotSpanCollection changedSpanCollection, bool removeOldTags)
{
Contract.ThrowIfNull(changedSpanCollection);
// this method should only run on UI thread as we do WPF here.
Contract.ThrowIfFalse(_textView.VisualElement.Dispatcher.CheckAccess());
var viewSnapshot = _textView.TextSnapshot;
var visualSnapshot = _textView.VisualSnapshot;
var viewLines = _textView.TextViewLines;
if (viewLines == null || viewLines.Count == 0)
{
return; // nothing to draw on
}
// removing is a separate pass from adding so that new stuff is not removed.
if (removeOldTags)
{
foreach (var changedSpan in changedSpanCollection)
{
// is there any effect on the view?
if (viewLines.IntersectsBufferSpan(changedSpan))
{
_adornmentLayer.RemoveAdornmentsByVisualSpan(changedSpan);
}
}
}
foreach (var changedSpan in changedSpanCollection)
{
// is there any effect on the view?
if (!viewLines.IntersectsBufferSpan(changedSpan))
{
continue;
}
var tagSpans = _tagAggregator.GetTags(changedSpan);
foreach (var tagMappingSpan in tagSpans)
{
// We don't want to draw line separators if they would intersect a collapsed outlining
// region. So we test if we can map the start of the line separator up to our visual
// snapshot. If we can't, then we just skip it.
var point = tagMappingSpan.Span.Start.GetPoint(changedSpan.Snapshot, PositionAffinity.Predecessor);
if (point == null)
{
continue;
}
var mappedPoint = _textView.BufferGraph.MapUpToSnapshot(
point.Value, PointTrackingMode.Negative, PositionAffinity.Predecessor, _textView.VisualSnapshot);
if (mappedPoint == null)
{
continue;
}
SnapshotSpan span;
if (!TryMapToSingleSnapshotSpan(tagMappingSpan.Span, viewSnapshot, out span))
{
continue;
}
if (!viewLines.IntersectsBufferSpan(span))
{
// span is outside of the view so we will not get geometry for it, but may
// spent a lot of time trying.
continue;
}
// add the visual to the adornment layer.
var geometry = viewLines.GetMarkerGeometry(span);
if (geometry != null)
{
var tag = tagMappingSpan.Tag;
var graphicsResult = tag.GetGraphics(_textView, geometry);
_adornmentLayer.AddAdornment(
behavior: AdornmentPositioningBehavior.TextRelative,
visualSpan: span,
tag: tag,
adornment: graphicsResult.VisualElement,
removedCallback: delegate { graphicsResult.Dispose(); });
}
}
}
}
// Map the mapping span to the visual snapshot. note that as a result of projection
// topology, originally single span may be mapped into several spans. Visual adornments do
// not make much sense on disjoint spans. We will not decorate spans that could not make it
// in one piece.
private bool TryMapToSingleSnapshotSpan(IMappingSpan mappingSpan, ITextSnapshot viewSnapshot, out SnapshotSpan span)
{
// IMappingSpan.GetSpans is a surprisingly expensive function that allocates multiple
// lists and collection if the view buffer is same as anchor we could just map the
// anchor to the viewSnapshot however, since the _anchor is not available, we have to
// map start and end TODO: verify that affinity is correct. If it does not matter we
// should use the cheapest.
if (viewSnapshot != null && mappingSpan.AnchorBuffer == viewSnapshot.TextBuffer)
{
var mappedStart = mappingSpan.Start.GetPoint(viewSnapshot, PositionAffinity.Predecessor).Value;
var mappedEnd = mappingSpan.End.GetPoint(viewSnapshot, PositionAffinity.Successor).Value;
span = new SnapshotSpan(mappedStart, mappedEnd);
return true;
}
// TODO: actually adornments do not make much sense on "cropped" spans either - Consider line separator on "nd Su"
// is it possible to cheaply detect cropping?
var spans = mappingSpan.GetSpans(viewSnapshot);
if (spans.Count != 1)
{
span = default(SnapshotSpan);
return false; // span is unmapped or disjoint.
}
span = spans[0];
return true;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Tests.LegacyTests
{
public class LastOrDefaultTests
{
public class LastOrDefault003
{
private static int LastOrDefault001()
{
var q = from x in new[] { 9999, 0, 888, -1, 66, -777, 1, 2, -12345 }
where x > Int32.MinValue
select x;
var rst1 = q.LastOrDefault<int>();
var rst2 = q.LastOrDefault<int>();
return ((rst1 == rst2) ? 0 : 1);
}
private static int LastOrDefault002()
{
var q = from x in new[] { "!@#$%^", "C", "AAA", "", "Calling Twice", "SoS", String.Empty }
where !String.IsNullOrEmpty(x)
select x;
var rst1 = q.LastOrDefault();
var rst2 = q.LastOrDefault();
return ((rst1 == rst2) ? 0 : 1);
}
public static int Main()
{
int ret = RunTest(LastOrDefault001) + RunTest(LastOrDefault002);
if (0 != ret)
Console.Write(s_errorMessage);
return ret;
}
private static string s_errorMessage = String.Empty;
private delegate int D();
private static int RunTest(D m)
{
int n = m();
if (0 != n)
s_errorMessage += m.ToString() + " - FAILED!\r\n";
return n;
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault1a
{
// source is of type IList, source is empty
public static int Test1a()
{
int[] source = { };
int expected = default(int);
IList<int> list = source as IList<int>;
if (list == null) return 1;
var actual = source.LastOrDefault();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault1b
{
// source is of type IList, source has one element
public static int Test1b()
{
int[] source = { 5 };
int expected = 5;
IList<int> list = source as IList<int>;
if (list == null) return 1;
var actual = source.LastOrDefault();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault1c
{
// source is of type IList, source has > 1 element
public static int Test1c()
{
int?[] source = { -10, 2, 4, 3, 0, 2, null };
int? expected = null;
IList<int?> list = source as IList<int?>;
if (list == null) return 1;
var actual = source.LastOrDefault();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault1d
{
// source is NOT of type IList, source is empty
public static int Test1d()
{
IEnumerable<int> source = Functions.NumList(0, 0);
int expected = default(int);
IList<int> list = source as IList<int>;
if (list != null) return 1;
var actual = source.LastOrDefault();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault1e
{
// source is NOT of type IList, source has one element
public static int Test1e()
{
IEnumerable<int> source = Functions.NumList(-5, 1);
int expected = -5;
IList<int> list = source as IList<int>;
if (list != null) return 1;
var actual = source.LastOrDefault();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault1f
{
// source is NOT of type IList, source has > 1 element
public static int Test1f()
{
IEnumerable<int> source = Functions.NumList(3, 10);
int expected = 12;
IList<int> list = source as IList<int>;
if (list != null) return 1;
var actual = source.LastOrDefault();
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test1f();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault2a
{
// source is empty
public static int Test2a()
{
int?[] source = { };
int? expected = null;
var actual = source.LastOrDefault((x) => true);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2a();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault2b
{
// source has one element, predicate is true
public static int Test2b()
{
int[] source = { 4 };
Func<int, bool> predicate = Functions.IsEven;
int expected = 4;
var actual = source.LastOrDefault(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2b();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault2c
{
// source has > one element, predicate is false for all
public static int Test2c()
{
int[] source = { 9, 5, 1, 3, 17, 21 };
Func<int, bool> predicate = Functions.IsEven;
int expected = default(int);
var actual = source.LastOrDefault(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2c();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault2d
{
// source has > one element, predicate is true only for last element
public static int Test2d()
{
int[] source = { 9, 5, 1, 3, 17, 21, 50 };
Func<int, bool> predicate = Functions.IsEven;
int expected = 50;
var actual = source.LastOrDefault(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2d();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
public class LastOrDefault2e
{
// source has > one element, predicate is true for 3rd, 6th and 8th element
public static int Test2e()
{
int[] source = { 3, 7, 10, 7, 9, 2, 11, 18, 13, 9 };
Func<int, bool> predicate = Functions.IsEven;
int expected = 18;
var actual = source.LastOrDefault(predicate);
return ((expected == actual) ? 0 : 1);
}
public static int Main()
{
return Test2e();
}
[Fact]
public void Test()
{
Assert.Equal(0, Main());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Collections.ObjectModel;
namespace Moq
{
/// <summary>
/// The intention of <see cref="ExpressionStringBuilder"/> is to create a more readable
/// string representation for the failure message.
/// </summary>
internal class ExpressionStringBuilder
{
private readonly Expression expression;
private StringBuilder builder;
private Func<Type, string> getTypeName;
internal static string GetString(Expression expression)
{
return GetString(expression, type => type.Name);
}
internal static string GetString(Expression expression, Func<Type, string> getTypeName)
{
var builder = new ExpressionStringBuilder(getTypeName, expression);
return builder.ToString();
}
public ExpressionStringBuilder(Func<Type, string> getTypeName, Expression expression)
{
this.getTypeName = getTypeName;
this.expression = expression;
}
public override string ToString()
{
builder = new StringBuilder();
ToString(expression);
return builder.ToString();
}
public void ToString(Expression exp)
{
if (exp == null)
{
builder.Append("null");
return;
}
switch (exp.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
ToStringUnary((UnaryExpression)exp);
return;
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
ToStringBinary((BinaryExpression)exp);
return;
case ExpressionType.TypeIs:
ToStringTypeIs((TypeBinaryExpression)exp);
return;
case ExpressionType.Conditional:
ToStringConditional((ConditionalExpression)exp);
return;
case ExpressionType.Constant:
ToStringConstant((ConstantExpression)exp);
return;
case ExpressionType.Parameter:
ToStringParameter((ParameterExpression)exp);
return;
case ExpressionType.MemberAccess:
ToStringMemberAccess((MemberExpression)exp);
return;
case ExpressionType.Call:
ToStringMethodCall((MethodCallExpression)exp);
return;
case ExpressionType.Lambda:
ToStringLambda((LambdaExpression)exp);
return;
case ExpressionType.New:
ToStringNew((NewExpression)exp);
return;
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
ToStringNewArray((NewArrayExpression)exp);
return;
case ExpressionType.Invoke:
ToStringInvocation((InvocationExpression)exp);
return;
case ExpressionType.MemberInit:
ToStringMemberInit((MemberInitExpression)exp);
return;
case ExpressionType.ListInit:
ToStringListInit((ListInitExpression)exp);
return;
default:
throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType));
}
}
private void ToStringBinding(MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
ToStringMemberAssignment((MemberAssignment)binding);
return;
case MemberBindingType.MemberBinding:
ToStringMemberMemberBinding((MemberMemberBinding)binding);
return;
case MemberBindingType.ListBinding:
ToStringMemberListBinding((MemberListBinding)binding);
return;
default:
throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType));
}
}
private void ToStringElementInitializer(ElementInit initializer)
{
builder.Append("{ ");
ToStringExpressionList(initializer.Arguments);
builder.Append(" }");
return;
}
private void ToStringUnary(UnaryExpression u)
{
switch (u.NodeType)
{
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
builder.Append("(").Append(this.getTypeName(u.Type)).Append(")");
ToString(u.Operand);
//builder.Append(")");
return;
case ExpressionType.ArrayLength:
ToString(u.Operand);
builder.Append(".Length");
return;
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
builder.Append("-");
ToString(u.Operand);
return;
case ExpressionType.Not:
builder.Append("!(");
ToString(u.Operand);
builder.Append(")");
return;
case ExpressionType.Quote:
ToString(u.Operand);
return;
case ExpressionType.TypeAs:
builder.Append("(");
ToString(u.Operand);
builder.Append(" as ");
builder.Append(u.Type.DisplayName(this.getTypeName));
builder.Append(")");
return;
}
return;
}
private void ToStringBinary(BinaryExpression b)
{
if (b.NodeType == ExpressionType.ArrayIndex)
{
ToString(b.Left);
builder.Append("[");
ToString(b.Right);
builder.Append("]");
}
else
{
string @operator = ToStringOperator(b.NodeType);
if (NeedEncloseInParen(b.Left))
{
builder.Append("(");
ToString(b.Left);
builder.Append(")");
}
else
{
ToString(b.Left);
}
builder.Append(" ");
builder.Append(@operator);
builder.Append(" ");
if (NeedEncloseInParen(b.Right))
{
builder.Append("(");
ToString(b.Right);
builder.Append(")");
}
else
{
ToString(b.Right);
}
}
}
private static bool NeedEncloseInParen(Expression operand)
{
return operand.NodeType == ExpressionType.AndAlso || operand.NodeType == ExpressionType.OrElse;
}
private void ToStringTypeIs(TypeBinaryExpression b)
{
ToString(b.Expression);
return;
}
private void ToStringConstant(ConstantExpression c)
{
var value = c.Value;
if (value != null)
{
if (value is string)
{
builder.Append("\"").Append(value).Append("\"");
}
else if (value.ToString() == value.GetType().ToString())
{
// Perhaps is better without nothing (at least for local variables)
//builder.Append("<value>");
}
else if (c.Type.IsEnum)
{
builder.Append(c.Type.DisplayName(this.getTypeName)).Append(".").Append(value);
}
else
{
builder.Append(value);
}
}
else
{
builder.Append("null");
}
}
private void ToStringConditional(ConditionalExpression c)
{
ToString(c.Test);
ToString(c.IfTrue);
ToString(c.IfFalse);
return;
}
private void ToStringParameter(ParameterExpression p)
{
if (p.Name != null)
{
builder.Append(p.Name);
}
else
{
builder.Append("<param>");
}
}
private void ToStringMemberAccess(MemberExpression m)
{
if (m.Expression != null)
{
ToString(m.Expression);
}
else
{
builder.Append(m.Member.DeclaringType.DisplayName(this.getTypeName));
}
builder.Append(".");
builder.Append(m.Member.Name);
return;
}
private void ToStringMethodCall(MethodCallExpression node)
{
if (node != null)
{
var paramFrom = 0;
var expression = node.Object;
if (Attribute.GetCustomAttribute(node.Method, typeof(ExtensionAttribute)) != null)
{
paramFrom = 1;
expression = node.Arguments[0];
}
if (expression != null)
{
ToString(expression);
}
else // Method is static
{
this.builder.Append(this.getTypeName(node.Method.DeclaringType));
}
if (node.Method.IsPropertyIndexerGetter())
{
this.builder.Append("[");
AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString);
this.builder.Append("]");
}
else if (node.Method.IsPropertyIndexerSetter())
{
this.builder.Append("[");
AsCommaSeparatedValues(node.Arguments
.Skip(paramFrom)
.Take(node.Arguments.Count - paramFrom), ToString);
this.builder.Append("] = ");
ToString(node.Arguments.Last());
}
else if (node.Method.IsPropertyGetter())
{
this.builder.Append(".").Append(node.Method.Name.Substring(4));
}
else if (node.Method.IsPropertySetter())
{
this.builder.Append(".").Append(node.Method.Name.Substring(4)).Append(" = ");
ToString(node.Arguments.Last());
}
else if (node.Method.IsGenericMethod)
{
this.builder
.Append(".")
.Append(node.Method.Name)
.Append("<")
.Append(string.Join(",", node.Method.GetGenericArguments().Select(s => this.getTypeName(s)).ToArray()))
.Append(">(");
AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString);
this.builder.Append(")");
}
else
{
this.builder
.Append(".")
.Append(node.Method.Name)
.Append("(");
AsCommaSeparatedValues(node.Arguments.Skip(paramFrom), ToString);
this.builder.Append(")");
}
}
}
private void ToStringExpressionList(ReadOnlyCollection<Expression> original)
{
AsCommaSeparatedValues(original, ToString);
return;
}
private void ToStringMemberAssignment(MemberAssignment assignment)
{
builder.Append(assignment.Member.Name);
builder.Append("= ");
ToString(assignment.Expression);
return;
}
private void ToStringMemberMemberBinding(MemberMemberBinding binding)
{
ToStringBindingList(binding.Bindings);
return;
}
private void ToStringMemberListBinding(MemberListBinding binding)
{
ToStringElementInitializerList(binding.Initializers);
return;
}
private void ToStringBindingList(IEnumerable<MemberBinding> original)
{
bool appendComma = false;
foreach (var exp in original)
{
if (appendComma)
{
builder.Append(", ");
}
ToStringBinding(exp);
appendComma = true;
}
return;
}
private void ToStringElementInitializerList(ReadOnlyCollection<ElementInit> original)
{
for (int i = 0, n = original.Count; i < n; i++)
{
ToStringElementInitializer(original[i]);
}
return;
}
private void ToStringLambda(LambdaExpression lambda)
{
if (lambda.Parameters.Count == 1)
{
ToStringParameter(lambda.Parameters[0]);
}
else
{
builder.Append("(");
AsCommaSeparatedValues(lambda.Parameters, ToStringParameter);
builder.Append(")");
}
builder.Append(" => ");
ToString(lambda.Body);
return;
}
private void ToStringNew(NewExpression nex)
{
Type type = (nex.Constructor == null) ? nex.Type : nex.Constructor.DeclaringType;
builder.Append("new ");
builder.Append(type.DisplayName(this.getTypeName));
builder.Append("(");
AsCommaSeparatedValues(nex.Arguments, ToString);
builder.Append(")");
return;
}
private void ToStringMemberInit(MemberInitExpression init)
{
ToStringNew(init.NewExpression);
builder.Append(" { ");
ToStringBindingList(init.Bindings);
builder.Append(" }");
return;
}
private void ToStringListInit(ListInitExpression init)
{
ToStringNew(init.NewExpression);
builder.Append(" { ");
bool appendComma = false;
foreach (var initializer in init.Initializers)
{
if (appendComma)
{
builder.Append(", ");
}
ToStringElementInitializer(initializer);
appendComma = true;
}
builder.Append(" }");
return;
}
private void ToStringNewArray(NewArrayExpression na)
{
switch (na.NodeType)
{
case ExpressionType.NewArrayInit:
builder.Append("new[] { ");
AsCommaSeparatedValues(na.Expressions, ToString);
builder.Append(" }");
return;
case ExpressionType.NewArrayBounds:
builder.Append("new ");
builder.Append(na.Type.GetElementType().DisplayName(this.getTypeName));
builder.Append("[");
AsCommaSeparatedValues(na.Expressions, ToString);
builder.Append("]");
return;
}
}
private void AsCommaSeparatedValues<T>(IEnumerable<T> source, Action<T> toStringAction) where T : Expression
{
bool appendComma = false;
foreach (var exp in source)
{
if (appendComma)
{
builder.Append(", ");
}
toStringAction(exp);
appendComma = true;
}
}
private void ToStringInvocation(InvocationExpression iv)
{
ToStringExpressionList(iv.Arguments);
return;
}
internal static string ToStringOperator(ExpressionType nodeType)
{
switch (nodeType)
{
case ExpressionType.Add:
case ExpressionType.AddChecked:
return "+";
case ExpressionType.And:
return "&";
case ExpressionType.AndAlso:
return "&&";
case ExpressionType.Coalesce:
return "??";
case ExpressionType.Divide:
return "/";
case ExpressionType.Equal:
return "==";
case ExpressionType.ExclusiveOr:
return "^";
case ExpressionType.GreaterThan:
return ">";
case ExpressionType.GreaterThanOrEqual:
return ">=";
case ExpressionType.LeftShift:
return "<<";
case ExpressionType.LessThan:
return "<";
case ExpressionType.LessThanOrEqual:
return "<=";
case ExpressionType.Modulo:
return "%";
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return "*";
case ExpressionType.NotEqual:
return "!=";
case ExpressionType.Or:
return "|";
case ExpressionType.OrElse:
return "||";
case ExpressionType.Power:
return "^";
case ExpressionType.RightShift:
return ">>";
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return "-";
}
return nodeType.ToString();
}
}
internal static class StringExtensions
{
public static string[] Lines(this string source)
{
return source.Split(new[] { Environment.NewLine }, StringSplitOptions.None);
}
public static string AsCommaSeparatedValues(this IEnumerable<string> source)
{
if (source == null)
{
return string.Empty;
}
var result = new StringBuilder(100);
bool appendComma = false;
foreach (var value in source)
{
if (appendComma)
{
result.Append(", ");
}
result.Append(value);
appendComma = true;
}
return result.ToString();
}
}
internal static class TypeExtensions
{
public static string DisplayName(this Type source, Func<Type, string> getName)
{
if (source == null)
{
throw new ArgumentNullException("source");
}
var builder = new StringBuilder(100);
builder.Append(getName(source).Split('`').First());
if (source.IsGenericType)
{
builder.Append("<");
builder.Append(source.GetGenericArguments().Select(t => getName(t)).AsCommaSeparatedValues());
builder.Append(">");
}
return builder.ToString();
}
}
// internal class ExpressionStringBuilder : ExpressionVisitor
// {
// private StringBuilder output = new StringBuilder();
// private Func<MethodInfo, string> getMethodName;
// private ExpressionStringBuilder(Func<MethodInfo, string> getMethodName)
// {
// this.getMethodName = getMethodName;
// }
// internal static string GetString(Expression expression)
// {
// return GetString(expression, method => method.GetName());
// }
// internal static string GetString(Expression expression, Func<MethodInfo, string> getMethodName)
// {
// var builder = new ExpressionStringBuilder(getMethodName);
// builder.Visit(expression);
// return builder.output.ToString();
// }
// protected override Expression VisitBinary(BinaryExpression node)
// {
// if (node != null)
// {
// if (node.NodeType == ExpressionType.ArrayIndex)
// {
// this.Visit(node.Left);
// this.output.Append("[");
// this.Visit(node.Right);
// this.output.Append("]");
// }
// else
// {
// var @operator = GetStringOperator(node.NodeType);
// if (IsParentEnclosed(node.Left))
// {
// this.output.Append("(");
// this.Visit(node.Left);
// this.output.Append(")");
// }
// else
// {
// this.Visit(node.Left);
// }
// output.Append(" ").Append(@operator).Append(" ");
// if (IsParentEnclosed(node.Right))
// {
// this.output.Append("(");
// this.Visit(node.Right);
// this.output.Append(")");
// }
// else
// {
// this.Visit(node.Right);
// }
// }
// }
// return node;
// }
// protected override Expression VisitConditional(ConditionalExpression node)
// {
// if (node != null)
// {
// this.Visit(node.Test);
// this.Visit(node.IfTrue);
// this.Visit(node.IfFalse);
// }
// return node;
// }
// protected override Expression VisitConstant(ConstantExpression node)
// {
// if (node != null)
// {
// var value = node.Value;
// if (value != null)
// {
// if (value is string)
// {
// this.output.Append('"').Append(value).Append('"');
// }
// else if (node.Type.IsEnum)
// {
// this.output.Append(node.Type.Name).Append(".").Append(value);
// }
// else if (value.ToString() != value.GetType().ToString())
// {
// this.output.Append(value);
// }
// }
// else
// {
// this.output.Append("null");
// }
// }
// return node;
// }
// protected override ElementInit VisitElementInit(ElementInit node)
// {
// if (node != null)
// {
// this.Visit(node.Arguments);
// }
// return node;
// }
// protected override Expression VisitInvocation(InvocationExpression node)
// {
// if (node != null)
// {
// this.Visit(node.Arguments);
// }
// return node;
// }
//#if NET3x
// protected override Expression VisitLambda(LambdaExpression node)
//#else
// protected override Expression VisitLambda<T>(Expression<T> node)
//#endif
// {
// if (node != null)
// {
// if (node.Parameters.Count == 1)
// {
// this.VisitParameter(node.Parameters[0]);
// }
// else
// {
// this.output.Append("(");
// this.Visit(node.Parameters, n => this.VisitParameter(n), 0, node.Parameters.Count);
// this.output.Append(")");
// }
// output.Append(" => ");
// this.Visit(node.Body);
// }
// return node;
// }
// protected override Expression VisitListInit(ListInitExpression node)
// {
// if (node != null)
// {
// this.VisitNew(node.NewExpression);
// Visit(node.Initializers, n => this.VisitElementInit(n));
// }
// return node;
// }
// protected override Expression VisitMember(MemberExpression node)
// {
// if (node != null)
// {
// if (node.Expression != null)
// {
// this.Visit(node.Expression);
// }
// else
// {
// this.output.Append(node.Member.DeclaringType.Name);
// }
// this.output.Append(".").Append(node.Member.Name);
// }
// return node;
// }
// protected override Expression VisitMemberInit(MemberInitExpression node)
// {
// if (node != null)
// {
// this.VisitNew(node.NewExpression);
// Visit(node.Bindings, n => this.VisitMemberBinding(n));
// }
// return node;
// }
// protected override MemberListBinding VisitMemberListBinding(MemberListBinding node)
// {
// if (node != null)
// {
// Visit(node.Initializers, n => this.VisitElementInit(n));
// }
// return node;
// }
// protected override MemberAssignment VisitMemberAssignment(MemberAssignment node)
// {
// if (node != null)
// {
// this.Visit(node.Expression);
// }
// return node;
// }
// protected override MemberBinding VisitMemberBinding(MemberBinding node)
// {
// if (node != null)
// {
// switch (node.BindingType)
// {
// case MemberBindingType.Assignment:
// this.VisitMemberAssignment((MemberAssignment)node);
// break;
// case MemberBindingType.MemberBinding:
// this.VisitMemberMemberBinding((MemberMemberBinding)node);
// break;
// case MemberBindingType.ListBinding:
// this.VisitMemberListBinding((MemberListBinding)node);
// break;
// default:
// throw new InvalidOperationException(string.Format(
// CultureInfo.CurrentCulture,
// "Unhandled binding type '{0}'",
// node.BindingType));
// }
// }
// return node;
// }
// protected override MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node)
// {
// if (node != null)
// {
// Visit(node.Bindings, n => this.VisitMemberBinding(n));
// }
// return node;
// }
// protected override Expression VisitMethodCall(MethodCallExpression node)
// {
// if (node != null)
// {
// var paramFrom = 0;
// var expression = node.Object;
// if (Attribute.GetCustomAttribute(node.Method, typeof(ExtensionAttribute)) != null)
// {
// paramFrom = 1;
// expression = node.Arguments[0];
// }
// if (expression != null)
// {
// this.Visit(expression);
// }
// else // Method is static
// {
// this.output.Append(node.Method.DeclaringType.Name);
// }
// if (node.Method.IsPropertyIndexerGetter())
// {
// this.output.Append("[");
// this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count);
// this.output.Append("]");
// }
// else if (node.Method.IsPropertyIndexerSetter())
// {
// this.output.Append("[");
// this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count - 1);
// this.output.Append("] = ");
// this.Visit(node.Arguments.Last());
// }
// else if (node.Method.IsPropertyGetter())
// {
// this.output.Append(".").Append(node.Method.Name.Substring(4));
// }
// else if (node.Method.IsPropertySetter())
// {
// this.output.Append(".").Append(node.Method.Name.Substring(4)).Append(" = ");
// this.Visit(node.Arguments.Last());
// }
// else if (node.Method.IsGenericMethod)
// {
// this.output
// .Append(".")
// .Append(this.getMethodName(node.Method))
// .Append("<")
// .Append(string.Join(",", node.Method.GetGenericArguments().Select(s => s.Name)))
// .Append(">(");
// this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count);
// output.Append(")");
// }
// else
// {
// this.output.Append(".").Append(this.getMethodName(node.Method)).Append("(");
// this.Visit(node.Arguments, n => this.Visit(n), paramFrom, node.Arguments.Count);
// output.Append(")");
// }
// }
// return node;
// }
// protected override Expression VisitNew(NewExpression node)
// {
// if (node != null)
// {
// this.Visit(node.Arguments);
// }
// return node;
// }
// protected override Expression VisitNewArray(NewArrayExpression node)
// {
// if (node != null)
// {
// this.output.Append("new[] { ");
// this.Visit(node.Expressions);
// this.output.Append(" }");
// }
// return node;
// }
// protected override Expression VisitParameter(ParameterExpression node)
// {
// if (node != null)
// {
// this.output.Append(node.Name != null ? node.Name : "<param>");
// }
// return node;
// }
// protected override Expression VisitTypeBinary(TypeBinaryExpression node)
// {
// return node != null ? this.Visit(node.Expression) : node;
// }
// protected override Expression VisitUnary(UnaryExpression node)
// {
// if (node != null)
// {
// switch (node.NodeType)
// {
// case ExpressionType.Negate:
// case ExpressionType.NegateChecked:
// this.output.Append("-");
// this.Visit(node.Operand);
// break;
// case ExpressionType.Not:
// this.output.Append("!(");
// this.Visit(node.Operand);
// this.output.Append(")");
// break;
// case ExpressionType.Quote:
// this.Visit(node.Operand);
// break;
// case ExpressionType.TypeAs:
// this.output.Append("(");
// this.Visit(node.Operand);
// this.output.Append(" as ").Append(node.Type.Name).Append(")");
// break;
// }
// }
// return node;
// }
// private static string GetStringOperator(ExpressionType nodeType)
// {
// switch (nodeType)
// {
// case ExpressionType.Add:
// case ExpressionType.AddChecked:
// return "+";
// case ExpressionType.And:
// return "&";
// case ExpressionType.AndAlso:
// return "&&";
// case ExpressionType.Coalesce:
// return "??";
// case ExpressionType.Divide:
// return "/";
// case ExpressionType.Equal:
// return "==";
// case ExpressionType.ExclusiveOr:
// return "^";
// case ExpressionType.GreaterThan:
// return ">";
// case ExpressionType.GreaterThanOrEqual:
// return ">=";
// case ExpressionType.LeftShift:
// return "<<";
// case ExpressionType.LessThan:
// return "<";
// case ExpressionType.LessThanOrEqual:
// return "<=";
// case ExpressionType.Modulo:
// return "%";
// case ExpressionType.Multiply:
// case ExpressionType.MultiplyChecked:
// return "*";
// case ExpressionType.NotEqual:
// return "!=";
// case ExpressionType.Or:
// return "|";
// case ExpressionType.OrElse:
// return "||";
// case ExpressionType.Power:
// return "^";
// case ExpressionType.RightShift:
// return ">>";
// case ExpressionType.Subtract:
// case ExpressionType.SubtractChecked:
// return "-";
// }
// return nodeType.ToString();
// }
// private static bool IsParentEnclosed(Expression node)
// {
// return node.NodeType == ExpressionType.AndAlso || node.NodeType == ExpressionType.OrElse;
// }
// private void Visit<T>(IList<T> arguments, Func<T, Expression> elementVisitor, int paramFrom, int paramTo)
// {
// var appendComma = false;
// for (var index = paramFrom; index < paramTo; index++)
// {
// if (appendComma)
// {
// this.output.Append(", ");
// }
// elementVisitor(arguments[index]);
// appendComma = true;
// }
// }
// }
}
| |
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace Zunix.Gameplay
{
/// <summary>
/// A code container for collision-related mathematical functions.
/// </summary>
static public class CollisionMath
{
/// <summary>
/// Determines if there is overlap of the non-transparent pixels
/// between two sprites.
/// </summary>
/// <param name="rectangleA">Bounding rectangle of the first sprite</param>
/// <param name="dataA">Pixel data of the first sprite</param>
/// <param name="rectangleB">Bouding rectangle of the second sprite</param>
/// <param name="dataB">Pixel data of the second sprite</param>
/// <returns>True if non-transparent pixels overlap; false otherwise</returns>
public static bool IntersectPixels(Rectangle rectangleA, Color[] dataA,
Rectangle rectangleB, Color[] dataB)
{
// Find the bounds of the rectangle intersection
int top = Math.Max(rectangleA.Top, rectangleB.Top);
int bottom = Math.Min(rectangleA.Bottom, rectangleB.Bottom);
int left = Math.Max(rectangleA.Left, rectangleB.Left);
int right = Math.Min(rectangleA.Right, rectangleB.Right);
// Check every point within the intersection bounds
for (int y = top; y < bottom; y++)
{
for (int x = left; x < right; x++)
{
// Get the color of both pixels at this point
Color colorA = dataA[(x - rectangleA.Left) +
(y - rectangleA.Top) * rectangleA.Width];
Color colorB = dataB[(x - rectangleB.Left) +
(y - rectangleB.Top) * rectangleB.Width];
// If both pixels are not completely transparent,
if (colorA.A != 0 && colorB.A != 0)
{
// then an intersection has been found
return true;
}
}
}
// No intersection found
return false;
}
/// <summary>
/// Determines if there is overlap of the non-transparent pixels between two
/// sprites.
/// </summary>
/// <param name="transformA">World transform of the first sprite.</param>
/// <param name="widthA">Width of the first sprite's texture.</param>
/// <param name="heightA">Height of the first sprite's texture.</param>
/// <param name="dataA">Pixel color data of the first sprite.</param>
/// <param name="transformB">World transform of the second sprite.</param>
/// <param name="widthB">Width of the second sprite's texture.</param>
/// <param name="heightB">Height of the second sprite's texture.</param>
/// <param name="dataB">Pixel color data of the second sprite.</param>
/// <returns>True if non-transparent pixels overlap; false otherwise</returns>
public static bool IntersectPixels(
Matrix transformA, int widthA, int heightA, Color[] dataA,
Matrix transformB, int widthB, int heightB, Color[] dataB)
{
// Calculate a matrix which transforms from A's local space into
// world space and then into B's local space
Matrix transformAToB = transformA * Matrix.Invert(transformB);
// When a point moves in A's local space, it moves in B's local space with a
// fixed direction and distance proportional to the movement in A.
// This algorithm steps through A one pixel at a time along A's X and Y axes
// Calculate the analogous steps in B:
Vector2 stepX = Vector2.TransformNormal(Vector2.UnitX, transformAToB);
Vector2 stepY = Vector2.TransformNormal(Vector2.UnitY, transformAToB);
// Calculate the top left corner of A in B's local space
// This variable will be reused to keep track of the start of each row
Vector2 yPosInB = Vector2.Transform(Vector2.Zero, transformAToB);
// For each row of pixels in A
for (int yA = 0; yA < heightA; yA++)
{
// Start at the beginning of the row
Vector2 posInB = yPosInB;
// For each pixel in this row
for (int xA = 0; xA < widthA; xA++)
{
// Round to the nearest pixel
int xB = (int)Math.Round(posInB.X);
int yB = (int)Math.Round(posInB.Y);
// If the pixel lies within the bounds of B
if (0 <= xB && xB < widthB &&
0 <= yB && yB < heightB)
{
// Get the colors of the overlapping pixels
Color colorA = dataA[xA + yA * widthA];
Color colorB = dataB[xB + yB * widthB];
// If both pixels are not completely transparent,
if (colorA.A != 0 && colorB.A != 0)
{
// then an intersection has been found
return true;
}
}
// Move to the next pixel in the row
posInB += stepX;
}
// Move to the next row
yPosInB += stepY;
}
// No intersection found
return false;
}
/// <summary>
/// Calculates an axis aligned rectangle which fully contains an arbitrarily
/// transformed axis aligned rectangle.
/// </summary>
/// <param name="rectangle">Original bounding rectangle.</param>
/// <param name="transform">World transform of the rectangle.</param>
/// <returns>A new rectangle which contains the trasnformed rectangle.</returns>
public static Rectangle CalculateBoundingRectangle(Rectangle rectangle,
Matrix transform)
{
// Get all four corners in local space
Vector2 leftTop = new Vector2(rectangle.Left, rectangle.Top);
Vector2 rightTop = new Vector2(rectangle.Right, rectangle.Top);
Vector2 leftBottom = new Vector2(rectangle.Left, rectangle.Bottom);
Vector2 rightBottom = new Vector2(rectangle.Right, rectangle.Bottom);
// Transform all four corners into work space
Vector2.Transform(ref leftTop, ref transform, out leftTop);
Vector2.Transform(ref rightTop, ref transform, out rightTop);
Vector2.Transform(ref leftBottom, ref transform, out leftBottom);
Vector2.Transform(ref rightBottom, ref transform, out rightBottom);
// Find the minimum and maximum extents of the rectangle in world space
Vector2 min = Vector2.Min(Vector2.Min(leftTop, rightTop),
Vector2.Min(leftBottom, rightBottom));
Vector2 max = Vector2.Max(Vector2.Max(leftTop, rightTop),
Vector2.Max(leftBottom, rightBottom));
// Return that as a rectangle
return new Rectangle((int)min.X, (int)min.Y,
(int)(max.X - min.X), (int)(max.Y - min.Y));
}
//#region Helper Types
///// <summary>
///// Data defining a circle/line collision result.
///// </summary>
///// <remarks>Also used for circle/rectangles.</remarks>
//public struct CircleLineCollisionResult
//{
// public bool Collision;
// public Vector2 Point;
// public Vector2 Normal;
// public float Distance;
//}
//#endregion
//#region Collision Methods
//public static void CalcHull(GameObject gameObject)
//{
// uint[] bits = new uint[gameObject.Sprite.Width * gameObject.Sprite.Height];
// gameObject.Sprite.GetData<uint>(bits);
// gameObject.Hull = new List<Point>();
// for (int x = 0; x < gameObject.Sprite.Width; x++)
// {
// for (int y = 0; y < gameObject.Sprite.Height; y++)
// {
// if ((bits[x + y * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// continue;
// bool bSilouette = false;
// //check for an alpha next to a color to make sure this is an edge
// //right
// if (x < gameObject.Sprite.Width - 1)
// {
// if ((bits[x + 1 + y * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// //left
// if (!bSilouette && x > 0)
// {
// if ((bits[x - 1 + y * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// //top
// if (!bSilouette && y > 0)
// {
// if ((bits[x + (y - 1) * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// //bottom
// if (!bSilouette && y < gameObject.Sprite.Height-1)
// {
// if ((bits[x + (y + 1) * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// //bottom left
// if (!bSilouette && x > 0 && y < gameObject.Sprite.Height - 1)
// {
// if ((bits[x - 1 + (y + 1) * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// //bottom right
// if (!bSilouette && x < gameObject.Sprite.Width - 1 && y < gameObject.Sprite.Height-1)
// {
// if ((bits[x + 1 + (y + 1) * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// //top left
// if (!bSilouette && x > 0 && y > 0)
// {
// if ((bits[x - 1 + (y - 1) * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// //top right
// if (!bSilouette && x < gameObject.Sprite.Width && y > 0)
// {
// if ((bits[x + 1 + (y - 1) * gameObject.Sprite.Width] & 0xFF000000) >> 24 <= 20)
// bSilouette = true;
// }
// Point p = new Point(x, y);
// if(bSilouette && !gameObject.Hull.Contains(p))
// gameObject.Hull.Add(p);
// }
// }
//}
//public static void UpdateHull(GameObject gameObject)
//{
// gameObject.HullTransformed = new Dictionary<Point, bool>(gameObject.HullTransformed == null ? 0 : gameObject.HullTransformed.Count);
// float cos = (float)Math.Cos(gameObject.Rotation);
// float sin = (float)Math.Sin(gameObject.Rotation);
// foreach (Point p in gameObject.Hull)
// {
// int newX = (int)Math.Round((p.X - gameObject.Origin.X) * cos - (p.Y - gameObject.Origin.Y) * sin);
// int newY = (int)Math.Round((p.Y - gameObject.Origin.Y) * cos + (p.X - gameObject.Origin.X) * sin);
// if (gameObject.MinX > newX) gameObject.MinX = newX;
// if (gameObject.MinY > newY) gameObject.MinY = newY;
// if (gameObject.MaxX < newX) gameObject.MaxX = newX;
// if (gameObject.MaxY < newY) gameObject.MaxY = newY;
// Point newP = new Point(newX, newY);
// if(!gameObject.HullTransformed.ContainsKey(newP))
// {
// gameObject.HullTransformed.Add(newP, true);
// }
// }
// gameObject.UpdateHull = false;
//}
//public static bool IntersectsGameObject(GameObject a, GameObject b)
//{
// BoundingSphere aboundingSphere;
// BoundingSphere bboundingSphere;
// aboundingSphere.Center = new Vector3(a.Position, 0);
// aboundingSphere.Radius = (float)Math.Sqrt(a.LastKnownSize.X * a.LastKnownSize.X + a.LastKnownSize.Y * a.LastKnownSize.Y) / 2.0f;
// bboundingSphere.Center = new Vector3(a.Position, 0);
// bboundingSphere.Radius = (float)Math.Sqrt(b.LastKnownSize.X * b.LastKnownSize.X + b.LastKnownSize.Y * b.LastKnownSize.Y) / 2.0f;
// if (!aboundingSphere.Intersects(bboundingSphere))
// return false;
// if (a.UpdateHull)
// CollisionMath.UpdateHull(a);
// if (b.UpdateHull)
// CollisionMath.UpdateHull(b);
// int minX1 = a.MinX + (int)a.Position.X;
// int maxX1 = a.MaxX + (int)a.Position.X;
// int minY1 = a.MinY + (int)a.Position.Y;
// int maxY1 = a.MaxY + (int)a.Position.Y;
// int minX2 = b.MinX + (int)b.Position.X;
// int maxX2 = b.MaxX + (int)b.Position.X;
// int minY2 = b.MinY + (int)b.Position.Y;
// int maxY2 = b.MaxY + (int)b.Position.Y;
// if (maxX1 < minX2 || minX1 > maxX2 ||
// maxY1 < minY2 || minY1 > maxY2)
// return false;
// Dictionary<Point,bool>.Enumerator enumer = a.HullTransformed.GetEnumerator();
// while(enumer.MoveNext())
// {
// Point point1 = enumer.Current.Key;
// int x1 = point1.X + (int)a.Position.X;
// int y1 = point1.Y + (int)a.Position.Y;
// if (x1 < minX2 || x1 > maxX2 ||
// y1 < minY2 || y1 > maxY2)
// continue;
// if (b.HullTransformed.ContainsKey(new Point(x1 - (int)b.Position.X, y1 - (int)b.Position.Y)))
// return true;
// }
// return false;
//}
//public static bool IntersectsPoint(Point a, GameObject b)
//{
// if (b.UpdateHull)
// CollisionMath.UpdateHull(b);
// if (b.HullTransformed.ContainsKey(a))
// return true;
// return false;
//}
///// <summary>
///// Determines the point of intersection between two line segments,
///// as defined by four points.
///// </summary>
///// <param name="a">The first point on the first line segment.</param>
///// <param name="b">The second point on the first line segment.</param>
///// <param name="c">The first point on the second line segment.</param>
///// <param name="d">The second point on the second line segment.</param>
///// <param name="point">The output value with the interesection, if any.</param>
///// <remarks>The output parameter "point" is only valid
///// when the return value is true.</remarks>
///// <returns>True if intersecting, false otherwise.</returns>
//public static bool LineLineIntersect(Vector2 a, Vector2 b, Vector2 c,
// Vector2 d, out Vector2 point)
//{
// point = Vector2.Zero;
// double r, s;
// double denominator = (b.X - a.X) * (d.Y - c.Y) - (b.Y - a.Y) * (d.X - c.X);
// // If the denominator in above is zero, AB & CD are colinear
// if (denominator == 0)
// {
// return false;
// }
// double numeratorR = (a.Y - c.Y) * (d.X - c.X) - (a.X - c.X) * (d.Y - c.Y);
// r = numeratorR / denominator;
// double numeratorS = (a.Y - c.Y) * (b.X - a.X) - (a.X - c.X) * (b.Y - a.Y);
// s = numeratorS / denominator;
// // non-intersecting
// if (r < 0 || r > 1 || s < 0 || s > 1)
// {
// return false;
// }
// // find intersection point
// point.X = (float)(a.X + (r * (b.X - a.X)));
// point.Y = (float)(a.Y + (r * (b.Y - a.Y)));
// return true;
//}
///// <summary>
///// Determine if two circles intersect or contain each other.
///// </summary>
///// <param name="center1">The center of the first circle.</param>
///// <param name="radius1">The radius of the first circle.</param>
///// <param name="center2">The center of the second circle.</param>
///// <param name="radius2">The radius of the second circle.</param>
///// <returns>True if the circles intersect or contain one another.</returns>
//public static bool CircleCircleIntersect(Vector2 center1, float radius1,
// Vector2 center2, float radius2)
//{
// Vector2 line = center2 - center1;
// // we use LengthSquared to avoid a costly square-root call
// return (line.LengthSquared() <= (radius1 + radius2) * (radius1 + radius2));
//}
///// <summary>
///// Determines if a circle and line segment intersect, and if so, how they do.
///// </summary>
///// <param name="center">The center of the circle.</param>
///// <param name="radius">The radius of the circle.</param>
///// <param name="rectangle">The rectangle.</param>
///// <param name="result">The result data for the collision.</param>
///// <returns>True if a collision occurs, provided for convenience.</returns>
//public static bool CircleRectangleCollide(Vector2 center, float radius,
// Rectangle rectangle, ref CircleLineCollisionResult result)
//{
// float xVal = center.X;
// if (xVal < rectangle.Left) xVal = rectangle.Left;
// if (xVal > rectangle.Right) xVal = rectangle.Right;
// float yVal = center.Y;
// if (yVal < rectangle.Top) yVal = rectangle.Top;
// if (yVal > rectangle.Bottom) yVal = rectangle.Bottom;
// Vector2 direction = new Vector2(center.X - xVal, center.Y - yVal);
// float distance = direction.Length();
// if ((distance > 0) && (distance < radius))
// {
// result.Collision = true;
// result.Distance = radius - distance;
// result.Normal = Vector2.Normalize(direction);
// result.Point = new Vector2(xVal, yVal);
// }
// else
// {
// result.Collision = false;
// }
// return result.Collision;
//}
///// <summary>
///// Determines if a circle and line segment intersect, and if so, how they do.
///// </summary>
///// <param name="center">The center of the circle.</param>
///// <param name="radius">The radius of the circle.</param>
///// <param name="lineStart">The first point on the line segment.</param>
///// <param name="lineEnd">The second point on the line segment.</param>
///// <param name="result">The result data for the collision.</param>
///// <returns>True if a collision occurs, provided for convenience.</returns>
//public static bool CircleLineCollide(Vector2 center, float radius,
// Vector2 lineStart, Vector2 lineEnd, ref CircleLineCollisionResult result)
//{
// Vector2 AC = center - lineStart;
// Vector2 AB = lineEnd - lineStart;
// float ab2 = AB.LengthSquared();
// if (ab2 <= 0f)
// {
// return false;
// }
// float acab = Vector2.Dot(AC, AB);
// float t = acab / ab2;
// if (t < 0.0f)
// t = 0.0f;
// else if (t > 1.0f)
// t = 1.0f;
// result.Point = lineStart + t * AB;
// result.Normal = center - result.Point;
// float h2 = result.Normal.LengthSquared();
// float r2 = radius * radius;
// if ((h2 > 0) && (h2 <= r2))
// {
// result.Normal.Normalize();
// result.Distance = (radius - (center - result.Point).Length());
// result.Collision = true;
// }
// else
// {
// result.Collision = false;
// }
// return result.Collision;
//}
//#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IO;
namespace System.Security.Claims
{
/// <summary>
/// A Claim is a statement about an entity by an Issuer.
/// A Claim consists of a Type, Value, a Subject and an Issuer.
/// Additional properties, ValueType, Properties and OriginalIssuer help understand the claim when making decisions.
/// </summary>
public class Claim
{
private enum SerializationMask
{
None = 0,
NameClaimType = 1,
RoleClaimType = 2,
StringType = 4,
Issuer = 8,
OriginalIssuerEqualsIssuer = 16,
OriginalIssuer = 32,
HasProperties = 64,
UserData = 128,
}
private byte[] _userSerializationData;
private string _issuer;
private string _originalIssuer;
private Dictionary<string, string> _properties = new Dictionary<string, string>();
private ClaimsIdentity _subject;
private string _type;
private string _value;
private string _valueType;
/// <summary>
/// Initializes an instance of <see cref="Claim"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="Claim"/>.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public Claim(BinaryReader reader)
: this(reader, null)
{
}
/// <summary>
/// Initializes an instance of <see cref="Claim"/> using a <see cref="BinaryReader"/>.
/// Normally the <see cref="BinaryReader"/> is constructed using the bytes from <see cref="WriteTo(BinaryWriter)"/> and initialized in the same way as the <see cref="BinaryWriter"/>.
/// </summary>
/// <param name="reader">a <see cref="BinaryReader"/> pointing to a <see cref="Claim"/>.</param>
/// <param name="subject"> the value for <see cref="Claim.Subject"/>, which is the <see cref="ClaimsIdentity"/> that has these claims.</param>
/// <exception cref="ArgumentNullException">if 'reader' is null.</exception>
public Claim(BinaryReader reader, ClaimsIdentity subject)
{
if (reader == null)
throw new ArgumentNullException("reader");
Initialize(reader, subject);
}
/// <summary>
/// Creates a <see cref="Claim"/> with the specified type and value.
/// </summary>
/// <param name="type">The claim type.</param>
/// <param name="value">The claim value.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception>
/// <remarks>
/// <see cref="Claim.Issuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>,
/// <see cref="Claim.ValueType"/> is set to <see cref="ClaimValueTypes.String"/>,
/// <see cref="Claim.OriginalIssuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>, and
/// <see cref="Claim.Subject"/> is set to null.
/// </remarks>
/// <seealso cref="ClaimsIdentity"/>
/// <seealso cref="ClaimTypes"/>
/// <seealso cref="ClaimValueTypes"/>
public Claim(string type, string value)
: this(type, value, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, ClaimsIdentity.DefaultIssuer, (ClaimsIdentity)null)
{
}
/// <summary>
/// Creates a <see cref="Claim"/> with the specified type, value, and value type.
/// </summary>
/// <param name="type">The claim type.</param>
/// <param name="value">The claim value.</param>
/// <param name="valueType">The claim value type.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception>
/// <remarks>
/// <see cref="Claim.Issuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>,
/// <see cref="Claim.OriginalIssuer"/> is set to <see cref="ClaimsIdentity.DefaultIssuer"/>,
/// and <see cref="Claim.Subject"/> is set to null.
/// </remarks>
/// <seealso cref="ClaimsIdentity"/>
/// <seealso cref="ClaimTypes"/>
/// <seealso cref="ClaimValueTypes"/>
public Claim(string type, string value, string valueType)
: this(type, value, valueType, ClaimsIdentity.DefaultIssuer, ClaimsIdentity.DefaultIssuer, (ClaimsIdentity)null)
{
}
/// <summary>
/// Creates a <see cref="Claim"/> with the specified type, value, value type, and issuer.
/// </summary>
/// <param name="type">The claim type.</param>
/// <param name="value">The claim value.</param>
/// <param name="valueType">The claim value type. If this parameter is empty or null, then <see cref="ClaimValueTypes.String"/> is used.</param>
/// <param name="issuer">The claim issuer. If this parameter is empty or null, then <see cref="ClaimsIdentity.DefaultIssuer"/> is used.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception>
/// <remarks>
/// <see cref="Claim.OriginalIssuer"/> is set to value of the <paramref name="issuer"/> parameter,
/// <see cref="Claim.Subject"/> is set to null.
/// </remarks>
/// <seealso cref="ClaimsIdentity"/>
/// <seealso cref="ClaimTypes"/>
/// <seealso cref="ClaimValueTypes"/>
public Claim(string type, string value, string valueType, string issuer)
: this(type, value, valueType, issuer, issuer, (ClaimsIdentity)null)
{
}
/// <summary>
/// Creates a <see cref="Claim"/> with the specified type, value, value type, issuer and original issuer.
/// </summary>
/// <param name="type">The claim type.</param>
/// <param name="value">The claim value.</param>
/// <param name="valueType">The claim value type. If this parameter is null, then <see cref="ClaimValueTypes.String"/> is used.</param>
/// <param name="issuer">The claim issuer. If this parameter is empty or null, then <see cref="ClaimsIdentity.DefaultIssuer"/> is used.</param>
/// <param name="originalIssuer">The original issuer of this claim. If this parameter is empty or null, then orignalIssuer == issuer.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception>
/// <remarks>
/// <see cref="Claim.Subject"/> is set to null.
/// </remarks>
/// <seealso cref="ClaimsIdentity"/>
/// <seealso cref="ClaimTypes"/>
/// <seealso cref="ClaimValueTypes"/>
public Claim(string type, string value, string valueType, string issuer, string originalIssuer)
: this(type, value, valueType, issuer, originalIssuer, (ClaimsIdentity)null)
{
}
/// <summary>
/// Creates a <see cref="Claim"/> with the specified type, value, value type, issuer, original issuer and subject.
/// </summary>
/// <param name="type">The claim type.</param>
/// <param name="value">The claim value.</param>
/// <param name="valueType">The claim value type. If this parameter is null, then <see cref="ClaimValueTypes.String"/> is used.</param>
/// <param name="issuer">The claim issuer. If this parameter is empty or null, then <see cref="ClaimsIdentity.DefaultIssuer"/> is used.</param>
/// <param name="originalIssuer">The original issuer of this claim. If this parameter is empty or null, then orignalIssuer == issuer.</param>
/// <param name="subject">The subject that this claim describes.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="value"/> is null.</exception>
/// <seealso cref="ClaimsIdentity"/>
/// <seealso cref="ClaimTypes"/>
/// <seealso cref="ClaimValueTypes"/>
public Claim(string type, string value, string valueType, string issuer, string originalIssuer, ClaimsIdentity subject)
: this(type, value, valueType, issuer, originalIssuer, subject, null, null)
{
}
/// <summary>
/// This internal constructor was added as a performance boost when adding claims that are found in the NTToken.
/// We need to add a property value to distinguish DeviceClaims from UserClaims.
/// </summary>
/// <param name="propertyKey">This allows adding a property when adding a Claim.</param>
/// <param name="propertyValue">The value associcated with the property.</param>
internal Claim(string type, string value, string valueType, string issuer, string originalIssuer, ClaimsIdentity subject, string propertyKey, string propertyValue)
{
if (type == null)
{
throw new ArgumentNullException("type");
}
if (value == null)
{
throw new ArgumentNullException("value");
}
Contract.EndContractBlock();
_type = type;
_value = value;
_valueType = string.IsNullOrEmpty(valueType) ? ClaimValueTypes.String : valueType;
_issuer = string.IsNullOrEmpty(issuer) ? ClaimsIdentity.DefaultIssuer : issuer;
_originalIssuer = string.IsNullOrEmpty(originalIssuer) ? _issuer : originalIssuer;
_subject = subject;
if (propertyKey != null)
{
_properties[propertyKey] = propertyValue;
}
}
/// <summary>
/// Copy constructor for <see cref="Claim"/>
/// </summary>
/// <param name="other">the <see cref="Claim"/> to copy.</param>
/// <remarks><see cref="Claim.Subject"/>will be set to 'null'.</remarks>
/// <exception cref="ArgumentNullException">if 'other' is null.</exception>
protected Claim(Claim other)
: this(other, (other == null ? (ClaimsIdentity)null : other._subject))
{
}
/// <summary>
/// Copy constructor for <see cref="Claim"/>
/// </summary>
/// <param name="other">the <see cref="Claim"/> to copy.</param>
/// <param name="subject">the <see cref="ClaimsIdentity"/> to assign to <see cref="Claim.Subject"/>.</param>
/// <remarks><see cref="Claim.Subject"/>will be set to 'subject'.</remarks>
/// <exception cref="ArgumentNullException">if 'other' is null.</exception>
protected Claim(Claim other, ClaimsIdentity subject)
{
if (other == null)
throw new ArgumentNullException("other");
_issuer = other._issuer;
_originalIssuer = other._originalIssuer;
_subject = subject;
_type = other._type;
_value = other._value;
_valueType = other._valueType;
foreach (var key in other._properties.Keys)
{
_properties.Add(key, other._properties[key]);
}
if (other._userSerializationData != null)
{
_userSerializationData = other._userSerializationData.Clone() as byte[];
}
}
/// <summary>
/// Contains any additional data provided by a derived type, typically set when calling <see cref="WriteTo(BinaryWriter, byte[])"/>.</param>
/// </summary>
protected virtual byte[] CustomSerializationData
{
get
{
return _userSerializationData;
}
}
/// <summary>
/// Gets the issuer of the <see cref="Claim"/>.
/// </summary>
public string Issuer
{
get { return _issuer; }
}
/// <summary>
/// Gets the original issuer of the <see cref="Claim"/>.
/// </summary>
/// <remarks>
/// When the <see cref="OriginalIssuer"/> differs from the <see cref="Issuer"/>, it means
/// that the claim was issued by the <see cref="OriginalIssuer"/> and was re-issued
/// by the <see cref="Issuer"/>.
/// </remarks>
public string OriginalIssuer
{
get { return _originalIssuer; }
}
/// <summary>
/// Gets the collection of Properties associated with the <see cref="Claim"/>.
/// </summary>
public IDictionary<string, string> Properties
{
get
{
return _properties;
}
}
/// <summary>
/// Gets the subject of the <see cref="Claim"/>.
/// </summary>
public ClaimsIdentity Subject
{
get { return _subject; }
internal set { _subject = value; }
}
/// <summary>
/// Gets the claim type of the <see cref="Claim"/>.
/// <seealso cref="ClaimTypes"/>.
/// </summary>
public string Type
{
get { return _type; }
}
/// <summary>
/// Gets the value of the <see cref="Claim"/>.
/// </summary>
public string Value
{
get { return _value; }
}
/// <summary>
/// Gets the value type of the <see cref="Claim"/>.
/// <seealso cref="ClaimValueTypes"/>
/// </summary>
public string ValueType
{
get { return _valueType; }
}
/// <summary>
/// Creates a new instance <see cref="Claim"/> with values copied from this object.
/// </summary>
public virtual Claim Clone()
{
return Clone((ClaimsIdentity)null);
}
/// <summary>
/// Creates a new instance <see cref="Claim"/> with values copied from this object.
/// </summary>
/// <param name="identity">the value for <see cref="Claim.Subject"/>, which is the <see cref="ClaimsIdentity"/> that has these claims.
/// <remarks><see cref="Claim.Subject"/> will be set to 'identity'.</remarks>
public virtual Claim Clone(ClaimsIdentity identity)
{
return new Claim(this, identity);
}
private void Initialize(BinaryReader reader, ClaimsIdentity subject)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
_subject = subject;
SerializationMask mask = (SerializationMask)reader.ReadInt32();
int numPropertiesRead = 1;
int numPropertiesToRead = reader.ReadInt32();
_value = reader.ReadString();
if ((mask & SerializationMask.NameClaimType) == SerializationMask.NameClaimType)
{
_type = ClaimsIdentity.DefaultNameClaimType;
}
else if ((mask & SerializationMask.RoleClaimType) == SerializationMask.RoleClaimType)
{
_type = ClaimsIdentity.DefaultRoleClaimType;
}
else
{
_type = reader.ReadString();
numPropertiesRead++;
}
if ((mask & SerializationMask.StringType) == SerializationMask.StringType)
{
_valueType = reader.ReadString();
numPropertiesRead++;
}
else
{
_valueType = ClaimValueTypes.String;
}
if ((mask & SerializationMask.Issuer) == SerializationMask.Issuer)
{
_issuer = reader.ReadString();
numPropertiesRead++;
}
else
{
_issuer = ClaimsIdentity.DefaultIssuer;
}
if ((mask & SerializationMask.OriginalIssuerEqualsIssuer) == SerializationMask.OriginalIssuerEqualsIssuer)
{
_originalIssuer = _issuer;
}
else if ((mask & SerializationMask.OriginalIssuer) == SerializationMask.OriginalIssuer)
{
_originalIssuer = reader.ReadString();
numPropertiesRead++;
}
else
{
_originalIssuer = ClaimsIdentity.DefaultIssuer;
}
if ((mask & SerializationMask.HasProperties) == SerializationMask.HasProperties)
{
// TODO - brentsch, maximum # of properties
int numProperties = reader.ReadInt32();
for (int i = 0; i < numProperties; i++)
{
Properties.Add(reader.ReadString(), reader.ReadString());
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
// TODO - brentschmaltz - maximum size ??
int cb = reader.ReadInt32();
_userSerializationData = reader.ReadBytes(cb);
numPropertiesRead++;
}
for (int i = numPropertiesRead; i < numPropertiesToRead; i++)
{
reader.ReadString();
}
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
public virtual void WriteTo(BinaryWriter writer)
{
WriteTo(writer, null);
}
/// <summary>
/// Serializes using a <see cref="BinaryWriter"/>
/// </summary>
/// <param name="writer">the <see cref="BinaryWriter"/> to use for data storage.</param>
/// <param name="userData">additional data provided by derived type.</param>
/// <exception cref="ArgumentNullException">if 'writer' is null.</exception>
protected virtual void WriteTo(BinaryWriter writer, byte[] userData)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
// TODO - brentsch, given that there may be a bunch of NameClaims and or RoleClaims, we should account for this.
// This would require coordination between ClaimsIdentity and Claim since the ClaimsIdentity defines these 'types'. For now just use defaults.
int numberOfPropertiesWritten = 1;
SerializationMask mask = SerializationMask.None;
if (string.Equals(_type, ClaimsIdentity.DefaultNameClaimType))
{
mask |= SerializationMask.NameClaimType;
}
else if (string.Equals(_type, ClaimsIdentity.DefaultRoleClaimType))
{
mask |= SerializationMask.RoleClaimType;
}
else
{
numberOfPropertiesWritten++;
}
if (!string.Equals(_valueType, ClaimValueTypes.String, StringComparison.Ordinal))
{
numberOfPropertiesWritten++;
mask |= SerializationMask.StringType;
}
if (!string.Equals(_issuer, ClaimsIdentity.DefaultIssuer, StringComparison.Ordinal))
{
numberOfPropertiesWritten++;
mask |= SerializationMask.Issuer;
}
if (string.Equals(_originalIssuer, _issuer, StringComparison.Ordinal))
{
mask |= SerializationMask.OriginalIssuerEqualsIssuer;
}
else if (!string.Equals(_originalIssuer, ClaimsIdentity.DefaultIssuer, StringComparison.Ordinal))
{
numberOfPropertiesWritten++;
mask |= SerializationMask.OriginalIssuer;
}
if (Properties.Count > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.HasProperties;
}
// TODO - brentschmaltz - maximum size ??
if (userData != null && userData.Length > 0)
{
numberOfPropertiesWritten++;
mask |= SerializationMask.UserData;
}
writer.Write((Int32)mask);
writer.Write((Int32)numberOfPropertiesWritten);
writer.Write(_value);
if (((mask & SerializationMask.NameClaimType) != SerializationMask.NameClaimType) && ((mask & SerializationMask.RoleClaimType) != SerializationMask.RoleClaimType))
{
writer.Write(_type);
}
if ((mask & SerializationMask.StringType) == SerializationMask.StringType)
{
writer.Write(_valueType);
}
if ((mask & SerializationMask.Issuer) == SerializationMask.Issuer)
{
writer.Write(_issuer);
}
if ((mask & SerializationMask.OriginalIssuer) == SerializationMask.OriginalIssuer)
{
writer.Write(_originalIssuer);
}
if ((mask & SerializationMask.HasProperties) == SerializationMask.HasProperties)
{
writer.Write(Properties.Count);
foreach (var key in Properties.Keys)
{
writer.Write(key);
writer.Write(Properties[key]);
}
}
if ((mask & SerializationMask.UserData) == SerializationMask.UserData)
{
writer.Write((Int32)userData.Length);
writer.Write(userData);
}
writer.Flush();
}
/// <summary>
/// Returns a string representation of the <see cref="Claim"/> object.
/// </summary>
/// <remarks>
/// The returned string contains the values of the <see cref="Type"/> and <see cref="Value"/> properties.
/// </remarks>
/// <returns>The string representation of the <see cref="Claim"/> object.</returns>
public override string ToString()
{
return String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}: {1}", _type, _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.ObjectModel;
using System.Diagnostics;
using System.Text;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.VisualStudio.Debugger.Clr;
using Roslyn.Utilities;
using Type = Microsoft.VisualStudio.Debugger.Metadata.Type;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator
{
internal sealed partial class CSharpFormatter : Formatter
{
private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name)
{
if (typeToDisplayOpt != null)
{
// We're showing the type of a value, so "dynamic" does not apply.
bool unused;
int index1 = 0;
int index2 = 0;
AppendQualifiedTypeName(
builder,
typeToDisplayOpt,
null,
ref index1,
null,
ref index2,
escapeKeywordIdentifiers: true,
sawInvalidIdentifier: out unused);
builder.Append('.');
AppendIdentifierEscapingPotentialKeywords(builder, name, sawInvalidIdentifier: out unused);
}
else
{
builder.Append(name);
}
}
internal override string GetArrayDisplayString(DkmClrAppDomain appDomain, Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options)
{
Debug.Assert(lmrType.IsArray);
Type originalLmrType = lmrType;
// Strip off all array types. We'll process them at the end.
while (lmrType.IsArray)
{
lmrType = lmrType.GetElementType();
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append('{');
// We're showing the type of a value, so "dynamic" does not apply.
bool unused;
builder.Append(GetTypeName(new TypeAndCustomInfo(DkmClrType.Create(appDomain, lmrType)), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused)); // NOTE: call our impl directly, since we're coupled anyway.
var numSizes = sizes.Count;
builder.Append('[');
for (int i = 0; i < numSizes; i++)
{
if (i > 0)
{
builder.Append(", ");
}
var lowerBound = lowerBounds[i];
var size = sizes[i];
if (lowerBound == 0)
{
builder.Append(FormatLiteral(size, options));
}
else
{
builder.Append(FormatLiteral(lowerBound, options));
builder.Append("..");
builder.Append(FormatLiteral(size + lowerBound - 1, options));
}
}
builder.Append(']');
lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled).
while (lmrType.IsArray)
{
builder.Append('[');
builder.Append(',', lmrType.GetArrayRank() - 1);
builder.Append(']');
lmrType = lmrType.GetElementType();
}
builder.Append('}');
return pooled.ToStringAndFree();
}
internal override string GetArrayIndexExpression(string[] indices)
{
return indices.ToCommaSeparatedString('[', ']');
}
internal override string GetCastExpression(string argument, string type, DkmClrCastExpressionOptions options)
{
Debug.Assert(!string.IsNullOrEmpty(argument));
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
if ((options & DkmClrCastExpressionOptions.ParenthesizeEntireExpression) != 0)
{
builder.Append('(');
}
if ((options & DkmClrCastExpressionOptions.ParenthesizeArgument) != 0)
{
argument = $"({argument})";
}
if ((options & DkmClrCastExpressionOptions.ConditionalCast) != 0)
{
builder.Append(argument);
builder.Append(" as ");
builder.Append(type);
}
else
{
builder.Append('(');
builder.Append(type);
builder.Append(')');
builder.Append(argument);
}
if ((options & DkmClrCastExpressionOptions.ParenthesizeEntireExpression) != 0)
{
builder.Append(')');
}
return pooled.ToStringAndFree();
}
internal override string GetTupleExpression(string[] values)
{
return values.ToCommaSeparatedString('(', ')');
}
internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
var usedFields = ArrayBuilder<EnumField>.GetInstance();
FillUsedEnumFields(usedFields, fields, underlyingValue);
if (usedFields.Count == 0)
{
return null;
}
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first.
{
AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name);
if (i > 0)
{
builder.Append(" | ");
}
}
usedFields.Free();
return pooled.ToStringAndFree();
}
internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt)
{
foreach (var field in fields)
{
// First match wins (deterministic since sorted).
if (underlyingValue == field.Value)
{
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name);
return pooled.ToStringAndFree();
}
}
return null;
}
internal override string GetObjectCreationExpression(string type, string[] arguments)
{
Debug.Assert(!string.IsNullOrEmpty(type));
var pooled = PooledStringBuilder.GetInstance();
var builder = pooled.Builder;
builder.Append("new ");
builder.Append(type);
builder.Append('(');
builder.AppendCommaSeparatedList(arguments);
builder.Append(')');
return pooled.ToStringAndFree();
}
internal override string FormatLiteral(char c, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(c, options);
}
internal override string FormatLiteral(int value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(value, options & ~(ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters));
}
internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatPrimitive(value, options);
}
internal override string FormatString(string str, ObjectDisplayOptions options)
{
return ObjectDisplay.FormatLiteral(str, options);
}
}
}
| |
using System;
using Glass.Mapper.Pipelines.DataMapperResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.DataMappers;
using Glass.Mapper.Sc.FakeDb.Infrastructure;
using Glass.Mapper.Sc.IoC;
using NSubstitute;
using NUnit.Framework;
using Sitecore.Data;
using Sitecore.FakeDb;
using Sitecore.Resources.Media;
using Image = Glass.Mapper.Sc.Fields.Image;
#if SC90 || SC91 || SC92 || SC93 || SC100
using Sitecore.Abstractions;
using Sitecore.DependencyInjection;
#endif
namespace Glass.Mapper.Sc.FakeDb.DataMappers
{
[TestFixture]
public class SitecoreFieldImageMapperFixture
{
protected const string FieldName = "Field";
#region Method - GetField
[Test]
public void GetField_ImageInField_ReturnsImageObject()
{
//Assign
var fieldValue =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" mediapath=\"/Files/20121222_001405\" src=\"~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx\" hspace=\"15\" vspace=\"20\" />";
var mediaId = new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}");
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
{
Value = fieldValue
}
},
new Sitecore.FakeDb.DbItem("MediaItem", mediaId)
{
new DbField("alt") {Value = "test alt"},
new DbField("height") {Value = "480"},
new DbField("width") {Value = "640"},
}
})
{
#if SC90 || SC91 || SC92 || SC93 || SC100
var mediaUrlProvider = Substitute.For<BaseMediaManager>();
SitecoreVersionAbstractions.MediaManager = new LazyResetable<BaseMediaManager>(() => mediaUrlProvider);
mediaUrlProvider
.GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId), Arg.Any<MediaUrlOptions>())
.Returns("/~/media/Test.ashx");
#else
Sitecore.Resources.Media.MediaProvider mediaProvider =
Substitute.For<Sitecore.Resources.Media.MediaProvider>();
mediaProvider
.GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId), Arg.Any<MediaUrlOptions>())
.Returns("/~/media/Test.ashx");
new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider);
#endif
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Image;
//Assert
Assert.AreEqual("test alt", result.Alt);
// Assert.Equals(null, result.Border);
Assert.AreEqual(string.Empty, result.Class);
Assert.AreEqual(15, result.HSpace);
Assert.AreEqual(480, result.Height);
Assert.AreEqual(new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), result.MediaId);
Assert.IsTrue(result.Src.EndsWith("/~/media/Test.ashx"));
Assert.AreEqual(20, result.VSpace);
Assert.AreEqual(640, result.Width);
Assert.AreEqual(true, result.MediaExists);
}
}
[Test]
public void GetField_ImageInField_MissingMediaItem_ReturnsImageObjectWithSrc()
{
//Assign
var fieldValue =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" mediapath=\"/Files/20121222_001405\" src=\"~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx\" hspace=\"15\" vspace=\"20\" />";
var mediaId = new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}");
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
{
Value = fieldValue
}
}
})
{
#if SC90 || SC91 || SC92 || SC93 || SC100
var mediaUrlProvider = Substitute.For<BaseMediaManager>();
SitecoreVersionAbstractions.MediaManager = new LazyResetable<BaseMediaManager>(() => mediaUrlProvider);
mediaUrlProvider
.GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId), Arg.Any<MediaUrlOptions>())
.Returns("/~/media/Test.ashx");
#else
Sitecore.Resources.Media.MediaProvider mediaProvider =
Substitute.For<Sitecore.Resources.Media.MediaProvider>();
mediaProvider
.GetMediaUrl(Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId), Arg.Any<MediaUrlOptions>())
.Returns("/~/media/Test.ashx");
new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider);
#endif
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
//Act
var result = mapper.GetField(field, new SitecoreFieldConfiguration(), null) as Image;
//Assert
Assert.IsEmpty(result.Alt);
// Assert.Equals(null, result.Border);
Assert.AreEqual(string.Empty, result.Class);
Assert.AreEqual(15, result.HSpace);
Assert.AreEqual(0, result.Height);
Assert.AreEqual(new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), result.MediaId);
Assert.IsTrue(string.IsNullOrEmpty(result.Src));
Assert.AreEqual(20, result.VSpace);
Assert.AreEqual(0, result.Width);
Assert.AreEqual(false, result.MediaExists);
}
}
[Test]
public void GetField_ImageFieldEmpty_ReturnsNull()
{
//Assign
var fieldValue = string.Empty;
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
{
Value = fieldValue
}
}
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var context = Context.Create(new DependencyResolver(new Config()));
var service = new SitecoreService(database.Database, context);
//Act
var result =
service.GetItem<StubImage>("/sitecore/content/TestItem");
//Assert
Assert.IsNull(result.Field);
}
}
[Test]
public void GetField_FieldIsEmpty_ReturnsNullImageObject()
{
//Assign
var fieldValue = string.Empty;
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
{
Value = fieldValue
}
}
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var service = Substitute.For<ISitecoreService>();
var options = new GetItemOptionsParams();
service.Config = new Config();
var context = new SitecoreDataMappingContext(null, null, service, options);
//Act
var result = mapper.GetField(field, null, context) as Image;
//Assert
Assert.IsNull(result);
}
}
[Test]
public void GetField_FieldIsNull_ReturnsNullImageObject()
{
//Assign
string fieldValue = null;
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
{
Value = fieldValue
}
}
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var options = new GetItemOptionsParams();
var service = Substitute.For<ISitecoreService>();
service.Config = new Config();
var context = new SitecoreDataMappingContext(null, null, service, options);
//Act
var result = mapper.GetField(field, null, context) as Image;
//Assert
Assert.IsNull(result);
}
}
[Test]
[TestCase(SitecoreMediaUrlOptions.Default)]
[TestCase(SitecoreMediaUrlOptions.RemoveExtension)]
[TestCase(SitecoreMediaUrlOptions.LowercaseUrls)]
public void GetField_FieldNotNull_ReturnsNullImageObject(
SitecoreMediaUrlOptions option
)
{
//Assign
var config = new SitecoreFieldConfiguration();
config.MediaUrlOptions = option;
string expected = "/~/media/Test.ashx";
var fieldValue =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" mediapath=\"/Files/20121222_001405\" src=\"~/media/D897833C1F534FAEB54BBB5B11B8F851.ashx\" hspace=\"15\" vspace=\"20\" />";
var mediaId = new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}");
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
{
Value = fieldValue
}
},
new Sitecore.FakeDb.DbItem("MediaItem", mediaId)
{
new DbField("alt") {Value = "test alt"},
new DbField("height") {Value = "480"},
new DbField("width") {Value = "640"},
}
})
{
Func<MediaUrlOptions, bool> pred = x =>
{
switch (option)
{
case SitecoreMediaUrlOptions.Default:
return true;
case SitecoreMediaUrlOptions.RemoveExtension:
return x.IncludeExtension == false;
case SitecoreMediaUrlOptions.LowercaseUrls:
return x.LowercaseUrls == true;
default:
return false;
}
};
#if SC90 || SC91 || SC92 || SC93 || SC100
var mediaUrlProvider = Substitute.For<BaseMediaManager>();
SitecoreVersionAbstractions.MediaManager = new LazyResetable<BaseMediaManager>(() => mediaUrlProvider);
mediaUrlProvider
.GetMediaUrl(
Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId),
Arg.Is<MediaUrlOptions>(x => pred(x))
)
.Returns(expected);
#else
Sitecore.Resources.Media.MediaProvider mediaProvider =
Substitute.For<Sitecore.Resources.Media.MediaProvider>();
mediaProvider
.GetMediaUrl(
Arg.Is<Sitecore.Data.Items.MediaItem>(i => i.ID == mediaId),
Arg.Is<MediaUrlOptions>(x => pred(x))
)
.Returns(expected);
new Sitecore.FakeDb.Resources.Media.MediaProviderSwitcher(mediaProvider);
#endif
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
mapper.Setup(new DataMapperResolverArgs(null, config));
//Act
var result = mapper.GetField(field, config, null) as Image;
//Assert
Assert.AreEqual("test alt", result.Alt);
// Assert.Equals(null, result.Border);
Assert.AreEqual(string.Empty, result.Class);
Assert.AreEqual(15, result.HSpace);
Assert.AreEqual(480, result.Height);
Assert.AreEqual(new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"), result.MediaId);
Assert.IsTrue(result.Src.EndsWith(expected));
Assert.AreEqual(20, result.VSpace);
Assert.AreEqual(640, result.Width);
}
}
#endregion
#region Method - SetField
[Test]
public void SetField_ImagePassed_ReturnsPopulatedField()
{
//Assign
var expected =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" width=\"640\" vspace=\"50\" height=\"480\" hspace=\"30\" alt=\"test alt\" />";
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
},
new Sitecore.FakeDb.DbItem("MediaItem", new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"))
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var image = new Image()
{
Alt = "test alt",
HSpace = 30,
Height = 480,
MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"),
VSpace = 50,
Width = 640,
Border = String.Empty,
Class = String.Empty
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, image, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "image");
}
}
[Test]
public void SetField_JustImageId_ReturnsPopulatedField()
{
//Assign
var expected =
"<image mediaid=\"{D897833C-1F53-4FAE-B54B-BB5B11B8F851}\" />";
using (Db database = new Db
{
new Sitecore.FakeDb.DbItem("TestItem")
{
new DbField(FieldName)
},
new Sitecore.FakeDb.DbItem("MediaItem", new ID("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"))
})
{
var item = database.GetItem("/sitecore/content/TestItem");
var field = item.Fields[FieldName];
var mapper = new SitecoreFieldImageMapper();
var image = new Image()
{
MediaId = new Guid("{D897833C-1F53-4FAE-B54B-BB5B11B8F851}"),
};
using (new ItemEditing(item, true))
{
field.Value = string.Empty;
}
//Act
using (new ItemEditing(item, true))
{
mapper.SetField(field, image, null, null);
}
//Assert
AssertHtml.AreHtmlElementsEqual(expected, field.Value, "image");
}
}
#endregion
#region Stubs
public class StubImage
{
public virtual Image Field { get; set; }
}
#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.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class HttpClientHandler_ServerCertificates_Test
{
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_ValidCertificate_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public void UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
var handler = new HttpClientHandler();
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent("This is a test"));
Task.WaitAll(proxyTask, responseTask);
using (responseTask.Result)
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
Assert.Equal(SslPolicyErrors.None, errors);
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
Assert.Equal(checkRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck, chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagates()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
Assert.Same(e, await Assert.ThrowsAsync<DivideByZeroException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer)));
}
}
public static readonly object[][] CertificateValidationServers =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
// On macOS (libcurl+darwinssl) we cannot turn revocation off.
// But we also can't realistically say that the default value for
// CheckCertificateRevocationList throws in the general case.
try
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
catch (HttpRequestException)
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
throw;
// If a run on a clean macOS ever fails we need to consider that "false"
// for CheckCertificateRevocationList is actually "use a system default" now,
// and may require changing how this option is exposed. Considering the variety of
// systems this should probably be complex like
// enum RevocationCheckingOption {
// // Use it if able
// BestPlatformSecurity = 0,
// // Don't use it, if that's an option.
// BestPlatformPerformance,
// // Required
// MustCheck,
// // Prohibited
// MustNotCheck,
// }
switch (CurlSslVersionDescription())
{
case "SecureTransport":
// Suppress the exception, making the test pass.
break;
default:
throw;
}
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
}
}
public static readonly object[][] CertificateValidationServersAndExpectedPolicies =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
[OuterLoop] // TODO: Issue #11345
[ActiveIssue(7812, TestPlatforms.Windows)]
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandling))]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
Assert.Equal(expectedErrors, errors);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendDoesNotSupportCustomCertificateHandling))]
// For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply.
[PlatformSpecific(~TestPlatforms.OSX)]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
internal static bool BackendSupportsCustomCertificateHandling
{
get
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return true;
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
return false;
}
// For other Unix-based systems it's true if (and only if) the openssl backend
// is used with libcurl.
return (CurlSslVersionDescription()?.StartsWith("OpenSSL") ?? false);
}
}
private static bool BackendDoesNotSupportCustomCertificateHandling => !BackendSupportsCustomCertificateHandling;
[DllImport("System.Net.Http.Native", EntryPoint = "HttpNative_GetSslVersionDescription")]
private static extern string CurlSslVersionDescription();
}
}
| |
// 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;
using System;
using System.IO;
using System.Text;
namespace System.IO.Tests
{
public class BinaryWriter_WriteByteCharTests
{
protected virtual Stream CreateStream()
{
return new MemoryStream();
}
/// <summary>
/// Cases Tested:
/// 1) Tests that BinaryWriter properly writes chars into a stream.
/// 2) Tests that if someone writes surrogate characters, an argument exception is thrown
/// 3) Casting an int to char and writing it, works.
/// </summary>
[Fact]
public void BinaryWriter_WriteCharTest()
{
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
BinaryReader dr2 = new BinaryReader(mstr);
char[] chArr = new char[0];
int ii = 0;
// [] Write a series of characters to a MemoryStream and read them back
chArr = new char[] { 'A', 'c', '\0', '\u2701', '$', '.', '1', 'l', '\u00FF', '\n', '\t', '\v' };
for (ii = 0; ii < chArr.Length; ii++)
dw2.Write(chArr[ii]);
dw2.Flush();
mstr.Position = 0;
for (ii = 0; ii < chArr.Length; ii++)
{
char c = dr2.ReadChar();
Assert.Equal(chArr[ii], c);
}
Assert.Throws<EndOfStreamException>(() => dr2.ReadChar());
dw2.Dispose();
dr2.Dispose();
mstr.Dispose();
//If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in.
//They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int).
//A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF
char ch;
Stream mem = CreateStream();
BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode);
//between 1 <= x < 255
int[] randomNumbers = new int[] { 1, 254, 210, 200, 105, 135, 98, 54 };
for (int i = 0; i < randomNumbers.Length; i++)
{
ch = (char)randomNumbers[i];
writer.Write(ch);
}
mem.Position = 0;
writer.Dispose();
mem.Dispose();
}
[Fact]
public void BinaryWriter_WriteCharTest_Negative()
{
//If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in.
//They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int).
//A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF
char ch;
Stream mem = CreateStream();
BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode);
// between 55296 <= x < 56319
int[] randomNumbers = new int[] { 55296, 56318, 55305, 56019, 55888, 55900, 56251 };
for (int i = 0; i < randomNumbers.Length; i++)
{
ch = (char)randomNumbers[i];
AssertExtensions.Throws<ArgumentException>(null, () => writer.Write(ch));
}
// between 56320 <= x < 57343
randomNumbers = new int[] { 56320, 57342, 56431, 57001, 56453, 57245, 57111 };
for (int i = 0; i < randomNumbers.Length; i++)
{
ch = (char)randomNumbers[i];
AssertExtensions.Throws<ArgumentException>(null, () => writer.Write(ch));
}
writer.Dispose();
mem.Dispose();
}
/// <summary>
/// Cases Tested:
/// Writing bytes casted to chars and using a different encoding; iso-2022-jp.
/// </summary>
[Fact]
public void BinaryWriter_WriteCharTest2()
{
// BinaryReader/BinaryWriter don't do well when mixing char or char[] data and binary data.
// This behavior remains for compat.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Stream stream = CreateStream();
// string name = iso-2022-jp, codepage = 50220 (original test used a code page number).
// taken from http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756(v=vs.85).aspx
string codepageName = "iso-2022-jp";
BinaryWriter writer = new BinaryWriter(stream, Encoding.GetEncoding(codepageName));
byte[] bytes = { 0x01, 0x02, 0x03, 0x04, 0x05 };
writer.Write((char)0x30ca);
writer.Write(bytes);
writer.Flush();
writer.Write('\0');
stream.Seek(0, SeekOrigin.Begin);
BinaryReader reader = new BinaryReader(stream, Encoding.GetEncoding(codepageName));
char japanese = reader.ReadChar();
Assert.Equal(0x30ca, (int)japanese);
byte[] readBytes = reader.ReadBytes(5);
for (int i = 0; i < 5; i++)
{
//We pretty much don't expect this to work
Assert.NotEqual(readBytes[i], bytes[i]);
}
stream.Dispose();
writer.Dispose();
reader.Dispose();
}
/// <summary>
/// Testing that bytes can be written to a stream with BinaryWriter.
/// </summary>
[Fact]
public void BinaryWriter_WriteByteTest()
{
int ii = 0;
byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 100, 1, 10, byte.MaxValue / 2, byte.MaxValue - 100 };
// [] read/Write with Memorystream
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
for (ii = 0; ii < bytArr.Length; ii++)
dw2.Write(bytArr[ii]);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < bytArr.Length; ii++)
{
Assert.Equal(bytArr[ii], dr2.ReadByte());
}
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadByte());
dr2.Dispose();
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Testing that SBytes can be written to a stream with BinaryWriter.
/// </summary>
[Fact]
public void BinaryWriter_WriteSByteTest()
{
int ii = 0;
sbyte[] sbArr = new sbyte[] {
sbyte.MinValue, sbyte.MaxValue, -100, 100, 0, sbyte.MinValue / 2, sbyte.MaxValue / 2,
10, 20, 30, -10, -20, -30, sbyte.MaxValue - 100 };
// [] read/Write with Memorystream
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
for (ii = 0; ii < sbArr.Length; ii++)
dw2.Write(sbArr[ii]);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < sbArr.Length; ii++)
{
Assert.Equal(sbArr[ii], dr2.ReadSByte());
}
dr2.Dispose();
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Testing that an ArgumentException is thrown when Sbytes are written to a stream
/// and read past the end of that stream.
/// </summary>
[Fact]
public void BinaryWriter_WriteSByteTest_NegativeCase()
{
int ii = 0;
sbyte[] sbArr = new sbyte[] {
sbyte.MinValue, sbyte.MaxValue, -100, 100, 0, sbyte.MinValue / 2, sbyte.MaxValue / 2,
10, 20, 30, -10, -20, -30, sbyte.MaxValue - 100 };
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
for (ii = 0; ii < sbArr.Length; ii++)
dw2.Write(sbArr[ii]);
dw2.Flush();
BinaryReader dr2 = new BinaryReader(mstr);
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadSByte());
dr2.Dispose();
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Testing that a byte[] can be written to a stream with BinaryWriter.
/// </summary>
[Fact]
public void BinaryWriter_WriteBArrayTest()
{
int ii = 0;
byte[] bytArr = new byte[] { byte.MinValue, byte.MaxValue, 1, 5, 10, 100, 200 };
// [] read/Write with Memorystream
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
dw2.Write(bytArr);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < bytArr.Length; ii++)
{
Assert.Equal(bytArr[ii], dr2.ReadByte());
}
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadByte());
mstr.Dispose();
dw2.Dispose();
dr2.Dispose();
}
[Fact]
public void BinaryWriter_WriteBArrayTest_Negative()
{
int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue };
int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
byte[] bArr = new byte[0];
// [] ArgumentNullException for null argument
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((byte[])null));
mstr.Dispose();
dw2.Dispose();
// [] ArgumentNullException for null argument
mstr = CreateStream();
dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((byte[])null, 0, 0));
dw2.Dispose();
mstr.Dispose();
mstr = CreateStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++)
{
// [] ArgumentOutOfRange for negative offset
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, iArrInvalidValues[iLoop], 0));
// [] ArgumentOutOfRangeException for negative count
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(bArr, 0, iArrInvalidValues[iLoop]));
}
dw2.Dispose();
mstr.Dispose();
mstr = CreateStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++)
{
// [] Offset out of range
AssertExtensions.Throws<ArgumentException>(null, () => dw2.Write(bArr, iArrLargeValues[iLoop], 0));
// [] Invalid count value
AssertExtensions.Throws<ArgumentException>(null, () => dw2.Write(bArr, 0, iArrLargeValues[iLoop]));
}
dw2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Cases Tested:
/// 1) Testing that bytes can be written to a stream with BinaryWriter.
/// 2) Tests exceptional scenarios.
/// </summary>
[Fact]
public void BinaryWriter_WriteBArrayTest2()
{
BinaryWriter dw2 = null;
BinaryReader dr2 = null;
Stream mstr = null;
byte[] bArr = new byte[0];
int ii = 0;
byte[] bReadArr = new byte[0];
int ReturnValue;
bArr = new byte[1000];
bArr[0] = byte.MinValue;
bArr[1] = byte.MaxValue;
for (ii = 2; ii < 1000; ii++)
bArr[ii] = (byte)(ii % 255);
// []read/ Write character values 0-1000 with Memorystream
mstr = CreateStream();
dw2 = new BinaryWriter(mstr);
dw2.Write(bArr, 0, bArr.Length);
dw2.Flush();
mstr.Position = 0;
dr2 = new BinaryReader(mstr);
bReadArr = new byte[bArr.Length];
ReturnValue = dr2.Read(bReadArr, 0, bArr.Length);
Assert.Equal(bArr.Length, ReturnValue);
for (ii = 0; ii < bArr.Length; ii++)
{
Assert.Equal(bArr[ii], bReadArr[ii]);
}
dw2.Dispose();
dr2.Dispose();
mstr.Dispose();
}
/// <summary>
/// Cases Tested:
/// 1) Testing that char[] can be written to a stream with BinaryWriter.
/// 2) Tests exceptional scenarios.
/// </summary>
[Fact]
public void BinaryWriter_WriteCharArrayTest()
{
int ii = 0;
char[] chArr = new char[1000];
chArr[0] = char.MinValue;
chArr[1] = char.MaxValue;
chArr[2] = '1';
chArr[3] = 'A';
chArr[4] = '\0';
chArr[5] = '#';
chArr[6] = '\t';
for (ii = 7; ii < 1000; ii++)
chArr[ii] = (char)ii;
// [] read/Write with Memorystream
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
dw2.Write(chArr);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
for (ii = 0; ii < chArr.Length; ii++)
{
Assert.Equal(chArr[ii], dr2.ReadChar());
}
// [] Check End Of Stream
Assert.Throws<EndOfStreamException>(() => dr2.ReadChar());
dw2.Dispose();
dr2.Dispose();
mstr.Dispose();
}
[Fact]
public void BinaryWriter_WriteCharArrayTest_Negative()
{
int[] iArrInvalidValues = new int[] { -1, -2, -100, -1000, -10000, -100000, -1000000, -10000000, -100000000, -1000000000, int.MinValue, short.MinValue };
int[] iArrLargeValues = new int[] { int.MaxValue, int.MaxValue - 1, int.MaxValue / 2, int.MaxValue / 10, int.MaxValue / 100 };
char[] chArr = new char[1000];
// [] ArgumentNullException for null argument
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((char[])null));
dw2.Dispose();
mstr.Dispose();
// [] ArgumentNullException for null argument
mstr = CreateStream();
dw2 = new BinaryWriter(mstr);
Assert.Throws<ArgumentNullException>(() => dw2.Write((char[])null, 0, 0));
mstr.Dispose();
dw2.Dispose();
mstr = CreateStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrInvalidValues.Length; iLoop++)
{
// [] ArgumentOutOfRange for negative offset
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrInvalidValues[iLoop], 0));
// [] negative count.
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrInvalidValues[iLoop]));
}
mstr.Dispose();
dw2.Dispose();
mstr = CreateStream();
dw2 = new BinaryWriter(mstr);
for (int iLoop = 0; iLoop < iArrLargeValues.Length; iLoop++)
{
// [] Offset out of range
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, iArrLargeValues[iLoop], 0));
// [] Invalid count value
Assert.Throws<ArgumentOutOfRangeException>(() => dw2.Write(chArr, 0, iArrLargeValues[iLoop]));
}
mstr.Dispose();
dw2.Dispose();
}
/// <summary>
/// Cases Tested:
/// If someone writes out characters using BinaryWriter's Write(char[]) method, they must use something like BinaryReader's ReadChars(int) method to read it back in.
/// They cannot use BinaryReader's ReadChar(). Similarly, data written using Write(char) can't be read back using ReadChars(int).
/// A high-surrogate is a Unicode code point in the range U+D800 through U+DBFF and a low-surrogate is a Unicode code point in the range U+DC00 through U+DFFF
///
/// We don't throw on the second read but then throws continuously - note the loop count difference in the 2 loops
///
/// BinaryReader was reverting to its original location instead of advancing. This was changed to skip past the char in the surrogate range.
/// The affected method is InternalReadOneChar (IROC). Note that the work here is slightly complicated by the way surrogates are handled by
/// the decoding classes. When IROC calls decoder.GetChars(), if the bytes passed in are surrogates, UnicodeEncoding doesn't report it.
/// charsRead would end up being one value, and since BinaryReader doesn't have the logic telling it exactly how many bytes total to expect,
/// it calls GetChars in a second loop. In that loop, UnicodeEncoding matches up a surrogate pair. If it realizes it's too big for the encoding,
/// then it throws an ArgumentException (chars overflow). This meant that BinaryReader.IROC is advancing past two chars in the surrogate
/// range, which is why the position actually needs to be moved back (but not past the first surrogate char).
///
/// Note that UnicodeEncoding doesn't always throw when it encounters two successive chars in the surrogate range. The exception
/// encountered here happens if it finds a valid pair but then determines it's too long. If the pair isn't valid (a low then a high),
/// then it returns 0xfffd, which is why BinaryReader.ReadChar needs to do an explicit check. (It always throws when it encounters a surrogate)
/// </summary>
[Fact]
public void BinaryWriter_WriteCharArrayTest2()
{
Stream mem = CreateStream();
BinaryWriter writer = new BinaryWriter(mem, Encoding.Unicode);
// between 55296 <= x < 56319
// between 56320 <= x < 57343
char[] randomChars = new char[] {
(char)55296, (char)57297, (char)55513, (char)56624, (char)55334, (char)56957, (char)55857,
(char)56355, (char)56095, (char)56887, (char) 56126, (char) 56735, (char)55748, (char)56405,
(char)55787, (char)56707, (char) 56300, (char)56417, (char)55465, (char)56944
};
writer.Write(randomChars);
mem.Position = 0;
BinaryReader reader = new BinaryReader(mem, Encoding.Unicode);
for (int i = 0; i < 50; i++)
{
try
{
reader.ReadChar();
Assert.Equal(1, i);
}
catch (ArgumentException)
{
// ArgumentException is sometimes thrown on ReadChar() due to the
// behavior outlined in the method summary.
}
}
char[] chars = reader.ReadChars(randomChars.Length);
for (int i = 0; i < randomChars.Length; i++)
Assert.Equal(randomChars[i], chars[i]);
reader.Dispose();
writer.Dispose();
}
/// <summary>
/// Cases Tested:
/// 1) Tests that char[] can be written to a stream with BinaryWriter.
/// 2) Tests Exceptional cases.
/// </summary>
[Fact]
public void BinaryWriter_WriteCharArrayTest3()
{
char[] chArr = new char[1000];
chArr[0] = char.MinValue;
chArr[1] = char.MaxValue;
chArr[2] = '1';
chArr[3] = 'A';
chArr[4] = '\0';
chArr[5] = '#';
chArr[6] = '\t';
for (int ii = 7; ii < 1000; ii++)
chArr[ii] = (char)ii;
// []read/ Write character values 0-1000 with Memorystream
Stream mstr = CreateStream();
BinaryWriter dw2 = new BinaryWriter(mstr);
dw2.Write(chArr, 0, chArr.Length);
dw2.Flush();
mstr.Position = 0;
BinaryReader dr2 = new BinaryReader(mstr);
char[] chReadArr = new char[chArr.Length];
int charsRead = dr2.Read(chReadArr, 0, chArr.Length);
Assert.Equal(chArr.Length, charsRead);
for (int ii = 0; ii < chArr.Length; ii++)
{
Assert.Equal(chArr[ii], chReadArr[ii]);
}
mstr.Dispose();
dw2.Dispose();
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BindableBase.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>This class implements INotifyPropertyChanged</summary>
//-----------------------------------------------------------------------
using System;
using System.ComponentModel;
namespace Csla.Core
{
/// <summary>
/// This class implements INotifyPropertyChanged
/// and INotifyPropertyChanging in a
/// serialization-safe manner.
/// </summary>
[Serializable()]
public abstract class BindableBase :
MobileObject,
INotifyPropertyChanged,
INotifyPropertyChanging
{
/// <summary>
/// Creates an instance of the object.
/// </summary>
protected BindableBase()
{ }
#if NETFX_CORE
/// <summary>
/// Event raised when a property is changed.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for a specific property.
/// </summary>
/// <param name="propertyInfo">The property info for the property that has changed.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanged(IPropertyInfo propertyInfo)
{
OnPropertyChanged(propertyInfo.Name);
}
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for a specific property.
/// </summary>
/// <param name="propertyName">The name of the property that has changed.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for a MetaData (IsXYZ) property
/// </summary>
/// <param name="propertyName">The name of the property that has changed.</param>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMetaPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new MetaPropertyChangedEventArgs(propertyName));
}
#else
[NonSerialized()]
private PropertyChangedEventHandler _nonSerializableChangedHandlers;
private PropertyChangedEventHandler _serializableChangedHandlers;
/// <summary>
/// Implements a serialization-safe PropertyChanged event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
"CA1062:ValidateArgumentsOfPublicMethods")]
public event PropertyChangedEventHandler PropertyChanged
{
add
{
if (ShouldHandlerSerialize(value))
_serializableChangedHandlers = (PropertyChangedEventHandler)
System.Delegate.Combine(_serializableChangedHandlers, value);
else
_nonSerializableChangedHandlers = (PropertyChangedEventHandler)
System.Delegate.Combine(_nonSerializableChangedHandlers, value);
}
remove
{
if (ShouldHandlerSerialize(value))
_serializableChangedHandlers = (PropertyChangedEventHandler)
System.Delegate.Remove(_serializableChangedHandlers, value);
else
_nonSerializableChangedHandlers = (PropertyChangedEventHandler)
System.Delegate.Remove(_nonSerializableChangedHandlers, value);
}
}
/// <summary>
/// Override this method to change the default logic for determining
/// if the event handler should be serialized
/// </summary>
/// <param name="value">the event handler to review</param>
/// <returns></returns>
protected virtual bool ShouldHandlerSerialize(PropertyChangedEventHandler value)
{
return value.Method.IsPublic &&
value.Method.DeclaringType != null &&
(value.Method.DeclaringType.IsSerializable || value.Method.IsStatic);
}
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for a specific property.
/// </summary>
/// <param name="propertyName">Name of the property that
/// has changed.</param>
/// <remarks>
/// This method may be called by properties in the business
/// class to indicate the change in a specific property.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanged(string propertyName)
{
if (ApplicationContext.PropertyChangedMode != ApplicationContext.PropertyChangedModes.None)
{
if (_nonSerializableChangedHandlers != null)
_nonSerializableChangedHandlers.Invoke(this,
new PropertyChangedEventArgs(propertyName));
if (_serializableChangedHandlers != null)
_serializableChangedHandlers.Invoke(this,
new PropertyChangedEventArgs(propertyName));
}
}
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for a MetaData (IsXYZ) property
/// </summary>
/// <param name="propertyName">Name of the property that
/// has changed.</param>
/// <remarks>
/// This method may be called by properties in the business
/// class to indicate the change in a specific property.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnMetaPropertyChanged(string propertyName)
{
if (_nonSerializableChangedHandlers != null)
_nonSerializableChangedHandlers.Invoke(this,
new MetaPropertyChangedEventArgs(propertyName));
if (_serializableChangedHandlers != null)
_serializableChangedHandlers.Invoke(this,
new MetaPropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for a specific property.
/// </summary>
/// <param name="propertyInfo">PropertyInfo of the property that
/// has changed.</param>
/// <remarks>
/// This method may be called by properties in the business
/// class to indicate the change in a specific property.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanged(IPropertyInfo propertyInfo)
{
OnPropertyChanged(propertyInfo.Name);
}
#endif
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for all object properties.
/// </summary>
/// <remarks>
/// This method is for backward compatibility with
/// CSLA .NET 1.x.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnIsDirtyChanged()
{
OnUnknownPropertyChanged();
}
/// <summary>
/// Call this method to raise the PropertyChanged event
/// for all object properties.
/// </summary>
/// <remarks>
/// This method is automatically called by MarkDirty. It
/// actually raises PropertyChanged for an empty string,
/// which tells data binding to refresh all properties.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnUnknownPropertyChanged()
{
OnPropertyChanged(string.Empty);
}
#if NETFX_CORE
/// <summary>
/// Event raised when a property is changing.
/// </summary>
public event PropertyChangingEventHandler PropertyChanging;
/// <summary>
/// Raises the PropertyChanging event.
/// </summary>
/// <param name="propertyName">Name of the property that
/// is being changed.</param>
/// <remarks>
/// This method may be called by properties in the business
/// class to indicate the change that is about to occur
/// in a specific property.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanging(string propertyName)
{
if (PropertyChanging != null)
PropertyChanging(this, new PropertyChangingEventArgs(propertyName));
}
/// <summary>
/// Raises the PropertyChanging event.
/// </summary>
/// <param name="propertyInfo">The property info for the property that has changed.</param>
/// <remarks>
/// This method may be called by properties in the business
/// class to indicate the change that is about to occur
/// in a specific property.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanging(IPropertyInfo propertyInfo)
{
OnPropertyChanging(propertyInfo.Name);
}
#else
[NonSerialized()]
private PropertyChangingEventHandler _nonSerializableChangingHandlers;
private PropertyChangingEventHandler _serializableChangingHandlers;
/// <summary>
/// Implements a serialization-safe PropertyChanging event.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design",
"CA1062:ValidateArgumentsOfPublicMethods")]
public event PropertyChangingEventHandler PropertyChanging
{
add
{
if (ShouldHandlerSerialize(value))
_serializableChangingHandlers = (PropertyChangingEventHandler)
System.Delegate.Combine(_serializableChangingHandlers, value);
else
_nonSerializableChangingHandlers = (PropertyChangingEventHandler)
System.Delegate.Combine(_nonSerializableChangingHandlers, value);
}
remove
{
if (ShouldHandlerSerialize(value))
_serializableChangingHandlers = (PropertyChangingEventHandler)
System.Delegate.Remove(_serializableChangingHandlers, value);
else
_nonSerializableChangingHandlers = (PropertyChangingEventHandler)
System.Delegate.Remove(_nonSerializableChangingHandlers, value);
}
}
/// <summary>
/// Call this method to raise the PropertyChanging event
/// for all object properties.
/// </summary>
/// <remarks>
/// This method is for backward compatibility with
/// CSLA .NET 1.x.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnIsDirtyChanging()
{
OnUnknownPropertyChanging();
}
/// <summary>
/// Call this method to raise the PropertyChanging event
/// for all object properties.
/// </summary>
/// <remarks>
/// This method is automatically called by MarkDirty. It
/// actually raises PropertyChanging for an empty string,
/// which tells data binding to refresh all properties.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnUnknownPropertyChanging()
{
OnPropertyChanging(string.Empty);
}
/// <summary>
/// Call this method to raise the PropertyChanging event
/// for a specific property.
/// </summary>
/// <param name="propertyName">Name of the property that
/// has Changing.</param>
/// <remarks>
/// This method may be called by properties in the business
/// class to indicate the change in a specific property.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanging(string propertyName)
{
if (ApplicationContext.PropertyChangedMode != ApplicationContext.PropertyChangedModes.None)
{
if (_nonSerializableChangingHandlers != null)
_nonSerializableChangingHandlers.Invoke(this,
new PropertyChangingEventArgs(propertyName));
if (_serializableChangingHandlers != null)
_serializableChangingHandlers.Invoke(this,
new PropertyChangingEventArgs(propertyName));
}
}
/// <summary>
/// Call this method to raise the PropertyChanging event
/// for a specific property.
/// </summary>
/// <param name="propertyInfo">PropertyInfo of the property that
/// has Changing.</param>
/// <remarks>
/// This method may be called by properties in the business
/// class to indicate the change in a specific property.
/// </remarks>
[EditorBrowsable(EditorBrowsableState.Advanced)]
protected virtual void OnPropertyChanging(IPropertyInfo propertyInfo)
{
OnPropertyChanging(propertyInfo.Name);
}
/// <summary>
/// Override this method to change the default logic for determining
/// if the event handler should be serialized
/// </summary>
/// <param name="value">the event handler to review</param>
/// <returns></returns>
protected virtual bool ShouldHandlerSerialize(PropertyChangingEventHandler value)
{
return value.Method.IsPublic &&
value.Method.DeclaringType != null &&
(value.Method.DeclaringType.IsSerializable || value.Method.IsStatic);
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using Microsoft.PowerShell.Commands.Internal.Format;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Enum for SelectionMode parameter.
/// </summary>
public enum OutputModeOption
{
/// <summary>
/// None is the default and it means OK and Cancel will not be present
/// and no objects will be written to the pipeline.
/// The selectionMode of the actual list will still be multiple.
/// </summary>
None,
/// <summary>
/// Allow selection of one single item to be written to the pipeline.
/// </summary>
Single,
/// <summary>
///Allow select of multiple items to be written to the pipeline.
/// </summary>
Multiple
}
/// <summary>
/// Implementation for the Out-GridView command.
/// </summary>
[Cmdlet(VerbsData.Out, "GridView", DefaultParameterSetName = "PassThru", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2109378")]
public class OutGridViewCommand : PSCmdlet, IDisposable
{
#region Properties
private const string DataNotQualifiedForGridView = "DataNotQualifiedForGridView";
private const string RemotingNotSupported = "RemotingNotSupported";
private TypeInfoDataBase _typeInfoDataBase;
private PSPropertyExpressionFactory _expressionFactory;
private OutWindowProxy _windowProxy;
private GridHeader _gridHeader;
#endregion Properties
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="OutGridViewCommand"/> class.
/// </summary>
public OutGridViewCommand()
{
}
#endregion Constructors
#region Input Parameters
/// <summary>
/// This parameter specifies the current pipeline object.
/// </summary>
[Parameter(ValueFromPipeline = true)]
public PSObject InputObject { get; set; } = AutomationNull.Value;
/// <summary>
/// Gets/sets the title of the Out-GridView window.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string Title { get; set; }
/// <summary>
/// Get or sets a value indicating whether the cmdlet should wait for the window to be closed.
/// </summary>
[Parameter(ParameterSetName = "Wait")]
public SwitchParameter Wait { get; set; }
/// <summary>
/// Get or sets a value indicating whether the selected items should be written to the pipeline
/// and if it should be possible to select multiple or single list items.
/// </summary>
[Parameter(ParameterSetName = "OutputMode")]
public OutputModeOption OutputMode { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the selected items should be written to the pipeline.
/// Setting this to true is the same as setting the OutputMode to Multiple.
/// </summary>
[Parameter(ParameterSetName = "PassThru")]
public SwitchParameter PassThru
{
get { return OutputMode == OutputModeOption.Multiple ? new SwitchParameter(true) : new SwitchParameter(false); }
set { this.OutputMode = value.IsPresent ? OutputModeOption.Multiple : OutputModeOption.None; }
}
#endregion Input Parameters
#region Public Methods
/// <summary>
/// Provides a one-time, pre-processing functionality for the cmdlet.
/// </summary>
protected override void BeginProcessing()
{
// Set up the ExpressionFactory
_expressionFactory = new PSPropertyExpressionFactory();
// If the value of the Title parameter is valid, use it as a window's title.
if (this.Title != null)
{
_windowProxy = new OutWindowProxy(this.Title, OutputMode, this);
}
else
{
// Using the command line as a title.
_windowProxy = new OutWindowProxy(this.MyInvocation.Line, OutputMode, this);
}
// Load the Type info database.
_typeInfoDataBase = this.Context.FormatDBManager.GetTypeInfoDataBase();
}
/// <summary>
/// Blocks depending on the wait and selected.
/// </summary>
protected override void EndProcessing()
{
base.EndProcessing();
if (_windowProxy == null)
{
return;
}
// If -Wait is used or outputMode is not None we have to wait for the window to be closed
// The pipeline will be blocked while we don't return
if (this.Wait || this.OutputMode != OutputModeOption.None)
{
_windowProxy.BlockUntillClosed();
}
// Output selected items to pipeline.
List<PSObject> selectedItems = _windowProxy.GetSelectedItems();
if (this.OutputMode != OutputModeOption.None && selectedItems != null)
{
foreach (PSObject selectedItem in selectedItems)
{
if (selectedItem == null)
{
continue;
}
PSPropertyInfo originalObjectProperty = selectedItem.Properties[OutWindowProxy.OriginalObjectPropertyName];
if (originalObjectProperty == null)
{
return;
}
this.WriteObject(originalObjectProperty.Value, false);
}
}
}
/// <summary>
/// Provides a record-by-record processing functionality for the cmdlet.
/// </summary>
protected override void ProcessRecord()
{
if (InputObject == null || InputObject == AutomationNull.Value)
{
return;
}
IDictionary dictionary = InputObject.BaseObject as IDictionary;
if (dictionary != null)
{
// Dictionaries should be enumerated through because the pipeline does not enumerate through them.
foreach (DictionaryEntry entry in dictionary)
{
ProcessObject(PSObjectHelper.AsPSObject(entry));
}
}
else
{
ProcessObject(InputObject);
}
}
/// <summary>
/// StopProcessing is called close the window when Ctrl+C in the command prompt.
/// </summary>
protected override void StopProcessing()
{
if (this.Wait || this.OutputMode != OutputModeOption.None)
{
_windowProxy.CloseWindow();
}
}
/// <summary>
/// Converts the provided PSObject to a string preserving PowerShell formatting.
/// </summary>
/// <param name="liveObject">PSObject to be converted to a string.</param>
internal string ConvertToString(PSObject liveObject)
{
StringFormatError formatErrorObject = new();
string smartToString = PSObjectHelper.SmartToString(liveObject,
_expressionFactory,
InnerFormatShapeCommand.FormatEnumerationLimit(),
formatErrorObject);
if (formatErrorObject.exception != null)
{
// There was a formatting error that should be sent to the console.
this.WriteError(
new ErrorRecord(
formatErrorObject.exception,
"ErrorFormattingType",
ErrorCategory.InvalidResult,
liveObject)
);
}
return smartToString;
}
#endregion Public Methods
#region Private Methods
/// <summary>
/// Execute formatting on a single object.
/// </summary>
/// <param name="input">Object to process.</param>
private void ProcessObject(PSObject input)
{
// Make sure the OGV window is not closed.
if (_windowProxy.IsWindowClosed())
{
LocalPipeline pipeline = (LocalPipeline)this.Context.CurrentRunspace.GetCurrentlyRunningPipeline();
if (pipeline != null && !pipeline.IsStopping)
{
// Stop the pipeline cleanly.
pipeline.StopAsync();
}
return;
}
object baseObject = input.BaseObject;
// Throw a terminating error for types that are not supported.
if (baseObject is ScriptBlock ||
baseObject is SwitchParameter ||
baseObject is PSReference ||
baseObject is FormatInfoData ||
baseObject is PSObject)
{
ErrorRecord error = new(
new FormatException(StringUtil.Format(FormatAndOut_out_gridview.DataNotQualifiedForGridView)),
DataNotQualifiedForGridView,
ErrorCategory.InvalidType,
null);
this.ThrowTerminatingError(error);
}
if (_gridHeader == null)
{
// Columns have not been added yet; Start the main window and add columns.
_windowProxy.ShowWindow();
_gridHeader = GridHeader.ConstructGridHeader(input, this);
}
else
{
_gridHeader.ProcessInputObject(input);
}
// Some thread synchronization needed.
Exception exception = _windowProxy.GetLastException();
if (exception != null)
{
ErrorRecord error = new(
exception,
"ManagementListInvocationException",
ErrorCategory.OperationStopped,
null);
this.ThrowTerminatingError(error);
}
}
#endregion Private Methods
internal abstract class GridHeader
{
protected OutGridViewCommand parentCmd;
internal GridHeader(OutGridViewCommand parentCmd)
{
this.parentCmd = parentCmd;
}
internal static GridHeader ConstructGridHeader(PSObject input, OutGridViewCommand parentCmd)
{
if (DefaultScalarTypes.IsTypeInList(input.TypeNames) ||
!OutOfBandFormatViewManager.HasNonRemotingProperties(input))
{
return new ScalarTypeHeader(parentCmd, input);
}
return new NonscalarTypeHeader(parentCmd, input);
}
internal abstract void ProcessInputObject(PSObject input);
}
internal class ScalarTypeHeader : GridHeader
{
private readonly Type _originalScalarType;
internal ScalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd)
{
_originalScalarType = input.BaseObject.GetType();
// On scalar types the type name is used as a column name.
this.parentCmd._windowProxy.AddColumnsAndItem(input);
}
internal override void ProcessInputObject(PSObject input)
{
if (!_originalScalarType.Equals(input.BaseObject.GetType()))
{
parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input);
}
else
{
// Columns are already added; Add the input PSObject as an item to the underlying Management List.
base.parentCmd._windowProxy.AddItem(input);
}
}
}
internal class NonscalarTypeHeader : GridHeader
{
private readonly AppliesTo _appliesTo = null;
internal NonscalarTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd)
{
// Prepare a table view.
TableView tableView = new();
tableView.Initialize(parentCmd._expressionFactory, parentCmd._typeInfoDataBase);
// Request a view definition from the type database.
ViewDefinition viewDefinition = DisplayDataQuery.GetViewByShapeAndType(parentCmd._expressionFactory, parentCmd._typeInfoDataBase, FormatShape.Table, input.TypeNames, null);
if (viewDefinition != null)
{
// Create a header using a view definition provided by the types database.
parentCmd._windowProxy.AddColumnsAndItem(input, tableView, (TableControlBody)viewDefinition.mainControl);
// Remember all type names and type groups the current view applies to.
_appliesTo = viewDefinition.appliesTo;
}
else
{
// Create a header using only the input object's properties.
parentCmd._windowProxy.AddColumnsAndItem(input, tableView);
_appliesTo = new AppliesTo();
// Add all type names except for Object and MarshalByRefObject types because they are too generic.
// Leave the Object type name if it is the only type name.
int index = 0;
foreach (string typeName in input.TypeNames)
{
if (index > 0 && (typeName.Equals(typeof(object).FullName, StringComparison.OrdinalIgnoreCase) ||
typeName.Equals(typeof(MarshalByRefObject).FullName, StringComparison.OrdinalIgnoreCase)))
{
break;
}
_appliesTo.AddAppliesToType(typeName);
index++;
}
}
}
internal override void ProcessInputObject(PSObject input)
{
// Find out if the input has matching types in the this.appliesTo collection.
foreach (TypeOrGroupReference typeOrGroupRef in _appliesTo.referenceList)
{
if (typeOrGroupRef is TypeReference)
{
// Add deserialization prefix.
string deserializedTypeName = typeOrGroupRef.name;
Deserializer.AddDeserializationPrefix(ref deserializedTypeName);
for (int i = 0; i < input.TypeNames.Count; i++)
{
if (typeOrGroupRef.name.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase)
|| deserializedTypeName.Equals(input.TypeNames[i], StringComparison.OrdinalIgnoreCase))
{
// Current view supports the input's Type;
// Add the input PSObject as an item to the underlying Management List.
base.parentCmd._windowProxy.AddItem(input);
return;
}
}
}
else
{
// Find out if the input's Type belongs to the current TypeGroup.
// TypeGroupReference has only a group's name, so use the database to get through all actual TypeGroup's.
List<TypeGroupDefinition> typeGroupList = base.parentCmd._typeInfoDataBase.typeGroupSection.typeGroupDefinitionList;
foreach (TypeGroupDefinition typeGroup in typeGroupList)
{
if (typeGroup.name.Equals(typeOrGroupRef.name, StringComparison.OrdinalIgnoreCase))
{
// A matching TypeGroup is found in the database.
// Find out if the input's Type belongs to this TypeGroup.
foreach (TypeReference typeRef in typeGroup.typeReferenceList)
{
// Add deserialization prefix.
string deserializedTypeName = typeRef.name;
Deserializer.AddDeserializationPrefix(ref deserializedTypeName);
if (input.TypeNames.Count > 0
&& (typeRef.name.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase)
|| deserializedTypeName.Equals(input.TypeNames[0], StringComparison.OrdinalIgnoreCase)))
{
// Current view supports the input's Type;
// Add the input PSObject as an item to the underlying Management List.
base.parentCmd._windowProxy.AddItem(input);
return;
}
}
}
}
}
}
// The input's Type is not supported by the current view;
// Switch to the Hetero Type view.
parentCmd._gridHeader = new HeteroTypeHeader(base.parentCmd, input);
}
}
internal class HeteroTypeHeader : GridHeader
{
internal HeteroTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd)
{
// Clear all existed columns and add Type and Value columns.
this.parentCmd._windowProxy.AddHeteroViewColumnsAndItem(input);
}
internal override void ProcessInputObject(PSObject input)
{
this.parentCmd._windowProxy.AddHeteroViewItem(input);
}
}
/// <summary>
/// Implements IDisposable logic.
/// </summary>
/// <param name="isDisposing">True if being called from Dispose.</param>
private void Dispose(bool isDisposing)
{
if (isDisposing)
{
if (_windowProxy != null)
{
_windowProxy.Dispose();
_windowProxy = null;
}
}
}
/// <summary>
/// Dispose method in IDisposable.
/// </summary>
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion LGPL License
#region Using Directives
using System;
using System.Collections;
using System.Diagnostics;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Collections;
using Axiom.Media;
using Axiom.SceneManagers.PagingLandscape.Collections;
using Axiom.SceneManagers.PagingLandscape.Tile;
using Axiom.SceneManagers.PagingLandscape.Data2D;
using Axiom.SceneManagers.PagingLandscape.Renderable;
#endregion Using Directives
namespace Axiom.SceneManagers.PagingLandscape.Page
{
public enum CameraPageState
{
Inside = 1,
Outside = 2,
Change = 4
}
/// <summary>
/// Summary description for PageManager.
/// </summary>
public class PageManager
{
#region Fields
/// Root scene node
protected SceneNode sceneRoot;
/** LandScape pages for the terrain.
*/
protected Pages pages;
/** Queues to batch the process of loading and unloading Pages.
This avoid the plugin to load a lot of Pages in a single Frame, droping the FPS.
*/
protected PageQueue pageLoadQueue;
protected PageQueue pageUnloadQueue;
protected PageQueue pagePreloadQueue;
protected PageQueue pagePostunloadQueue;
/** LandScapePage index where the camera is.
*/
protected long currentCameraPageX, currentCameraPageZ;
protected long currentCameraTileX, currentCameraTileZ;
/** The last estate for the camera.
*/
protected CameraPageState lastCameraPageState;
protected long width ;
protected long heigth;
protected int pause;
protected Vector3 lastCameraPos;
#endregion Fields
#region Singleton Implementation
/// <summary>
/// Constructor
/// </summary>
public PageManager(SceneNode rootNode)
{
if (instance != null)
{
throw new ApplicationException("PageManager.Constructor() called twice!");
}
instance = this;
sceneRoot = rootNode;
currentCameraPageX = 0;
currentCameraPageZ = 0;
currentCameraTileX = 0;
currentCameraTileZ = 0;
lastCameraPageState = CameraPageState.Change;
lastCameraPos = new Vector3(-999999,9999999,-999999);
pause = 99;
width = Options.Instance.World_Width;
heigth = Options.Instance.World_Height;
pageLoadQueue = new PageQueue();
pageUnloadQueue = new PageQueue();
pagePreloadQueue = new PageQueue();
pagePostunloadQueue = new PageQueue();
//setup the page array.
// mPages.reserve (mWidth);
// mPages.resize (mWidth);
pages = new Pages( width );
for (long i = 0; i < width; i++ )
{
PageRow pr = new PageRow( heigth );
// mPages[ i ].reserve (mHeigth);
// mPages[ i ].resize (mHeigth);
for (long j = 0; j < heigth; j++ )
{
pr.Add( new Page( i, j ) );
}
pages.Add( pr );
}
for (long j = 0; j < heigth; j++ )
{
for (long i = 0; i < width; i++ )
{
if ( j != heigth - 1)
{
pages[ i ][ j ].SetNeighbor( Neighbor.South, pages[ i ][ j + 1 ] );
pages[ i ][ j + 1 ].SetNeighbor( Neighbor.North, pages[ i ][ j ] );
}
if ( i != width - 1)
{
pages[ i ][ j ].SetNeighbor( Neighbor.East, pages[ i + 1 ][ j ] );
pages[ i + 1 ][ j ].SetNeighbor( Neighbor.West, pages[ i ][ j ] );
}
}
}
}
private static PageManager instance = null;
public static PageManager Instance
{
get
{
return instance;
}
}
#endregion Singleton Implementation
#region IDisposable Implementation
public void Dispose()
{
if (instance == this)
{
instance = null;
}
}
#endregion IDisposable Implementation
public void Update( Camera cam )
{
// Here we have to look if we have to load, unload any of the LandScape Pages
//Vector3 pos = cam.getPosition();
// Fix from Praetor, so the camera used gives you "world-relative" coordinates
Vector3 pos = cam.DerivedPosition;
//updateStats( pos );
// Update only if the camera was moved
// make sure in the bounding box of landscape
pos.y = 127.0f;
if ( Options.Instance.CameraThreshold <= (lastCameraPos - pos).LengthSquared )
{
// Check for the camera position in the LandScape Pages list, we check if we are in the inside the security zone
// if not, launch the change routine and update the camera position currentCameraX, currentCameraY.
if ( pages[ currentCameraPageX ][ currentCameraPageZ ] != null &&
(
pages[ currentCameraPageX ][ currentCameraPageZ ].IsLoaded == false ||
pages[ currentCameraPageX ][ currentCameraPageZ ].IsCameraIn( pos ) != CameraPageState.Inside
)
)
{
// JEFF
// convert camera pos to page index
long i, j;
Data2DManager.Instance.GetPageIndices(pos, out i, out j);
//if (((currentCameraPageX != i) || (currentCameraPageZ != j)) &&
Debug.Assert( i < width && j < heigth , "Page Indices out of bounds" );
if ((pages[ i ] [ j ] == null) ||
(pages[ i ][ j ].IsCameraIn ( pos ) != CameraPageState.Outside)
)
{
long adjpages = Options.Instance.Max_Adjacent_Pages;
long prepages = Options.Instance.Max_Preload_Pages;
long w = width;
long h = heigth;
// We must load the next visible landscape pages,
// and unload the last visibles
// check the landscape boundaries
long iniX = ((int)(i - adjpages) > 0)? i - adjpages: 0;
long iniZ = ((int)(j - adjpages) > 0)? j - adjpages: 0;
long finX = (i + adjpages >= w )? w - 1: i + adjpages;
long finZ = (j + adjpages >= h )? h - 1: j + adjpages;
long preIniX = ((int)(i - prepages) > 0)? i - prepages: 0;
long preIniZ = ((int)(j - prepages) > 0)? j - prepages: 0;
long preFinX = (i + prepages >= w)? w - 1: i + prepages;
long preFinZ = (j + prepages >= h )? h - 1: j + prepages;
// update the camera page position
currentCameraPageX = i;
currentCameraPageZ = j;
// Have the current page be loaded now
if ( pages[ currentCameraPageX ][ currentCameraPageZ ].IsPreLoaded == false )
{
pages[ currentCameraPageX ][ currentCameraPageZ ].Preload();
}
if ( pages[ currentCameraPageX ][ currentCameraPageZ ].IsLoaded == false )
{
pages[ currentCameraPageX ][ currentCameraPageZ ].Load(ref sceneRoot );
}
// Queue the rest
// Loading and unloading must be done one by one to avoid FPS drop, so they are queued.
// No need to queue for preload since _ProcessLoading will do it in Load if required.
// post unload as required
for( j = 0; j < preIniZ; j++)
{
for( i = 0 ; i < preIniX; i++)
{
pageUnloadQueue.Push( pages[ i ][ j ] );
}
}
for( j = preFinZ + 1; j < h; j++)
{
for( i = preFinX + 1; i < w; i++)
{
pageUnloadQueue.Push( pages[ i ][ j ] );
}
}
// Preload as required
for ( j = preIniZ; j < iniZ; j++ )
{
for ( i = preIniX; i < iniX; i++ )
{
pagePreloadQueue.Push( pages[ i ][ j ] );
}
}
for ( j = finZ; j <= preFinZ; j++ )
{
for ( i = finX; i <= preFinX; i++ )
{
pagePreloadQueue.Push( pages[ i ][ j ] );
}
}
// load as required
for ( j = iniZ; j <= finZ; j++ )
{
for ( i = iniX; i <= finX; i++ )
{
if ( !pages[ i ][ j ].IsLoaded )
pageLoadQueue.Push( pages[ i ][ j ] );
}
}
}
}
// Update the last camera position
lastCameraPos = pos;
Tile.Tile t = GetTile (pos,(long)currentCameraPageX, (long)currentCameraPageZ);
if (t != null)
{
Tile.TileInfo CurrentTileInfo = t.Info;
if (CurrentTileInfo != null)
{
currentCameraTileX = CurrentTileInfo.TileX;
currentCameraTileZ = CurrentTileInfo.TileZ;
}
}
}
// Check for visibility
Camera plsmCam = (cam);
for ( long j = 0; j < heigth; j++ )
{
for ( long i = 0; i < width; i++ )
{
pages[ i ][ j ].Notify (pos, plsmCam);
}
}
// Preload, load, unload and post unload as required
this.processLoading();
}
public long GetCurrentCameraPageX() { return this.currentCameraPageX; }
public long GetCurrentCameraPageZ() { return this.currentCameraPageZ; }
public long GetCurrentCameraTileX() { return this.currentCameraTileX; }
public long GetCurrentCameraTileZ() { return this.currentCameraTileZ; }
public int GetPagePreloadQueueSize() { return this.pagePreloadQueue.Size; }
public int GetPageLoadQueueSize() { return this.pageLoadQueue.Size; }
public int GetPageUnloadQueueSize() { return this.pageUnloadQueue.Size; }
public int GetPagePostUnloadQueueSize() { return this.pagePostunloadQueue.Size; }
public Page GetPage ( long i , long j)
{
return pages[i][j];
}
public Tile.Tile GetTile ( Vector3 pos)
{
int pSize = (int)Options.Instance.PageSize - 1;
Vector3 scale = Options.Instance.Scale;
int w = (int) (Options.Instance.World_Width * 0.5f);
int h = (int) (Options.Instance.World_Height * 0.5f);
Vector3 TileRefPos = new Vector3 (pos.x / scale.x,
pos.y,
pos.z / scale.z);
int pagex = (int) (TileRefPos.x / pSize + w);
int pagez = (int) (TileRefPos.z / pSize + h );
// make sure indices are not negative or outside range of number of pages
if (pagex < 0 || pagex >= w*2 || pagez >= h*2 || pagez < 0)
return null;
else
{
int tSize = (int)Options.Instance.TileSize;
int tilex = (int) ((TileRefPos.x - ((pagex - w) * pSize)) / tSize);
int tilez = (int) ((TileRefPos.z - ((pagez - h) * pSize)) / tSize);
pSize = (pSize / tSize) - 1;
if (tilex > pSize || tilex < 0 ||
tilez > pSize || tilez < 0)
return null;
return pages[pagex][pagez].GetTile ((long)tilex, (long)tilez);
}
}
public Tile.Tile GetTile(Vector3 pos, long pagex, long pagez)
{
int pageSize = (int) Options.Instance.PageSize - 1;
Vector3 scale = Options.Instance.Scale;
int w = (int)(Options.Instance.World_Width * 0.5F);
int h = (int)(Options.Instance.World_Height * 0.5F);
Vector3 TileRefPos = new Vector3 ( pos.x / scale.x , pos.y, pos.z / scale.z );
int pageX = (int) (TileRefPos.x / pageSize + w );
int pageZ = (int) (TileRefPos.z / pageSize + h );
// make sure indices are not negative or outside range of number of pages
if ( pageX < 0 || pageX >= w * 2 || pageZ >= h * 2 || pageZ < 0 )
return null;
else
{
int tileSize = (int) Options.Instance.TileSize;
int tilex = (int) ( ( TileRefPos.x - ( ( pageX - w ) * pageSize ) ) / tileSize );
int tilez = (int) ( ( TileRefPos.z - ( ( pageZ - h ) * pageSize ) ) / tileSize );
pageSize = ( pageSize / tileSize ) -1;
if ( tilex > pageSize || tilex < 0 || tilez > pageSize || tilez < 0 )
return null;
return pages[pageX][pageZ].GetTile(tilex, tilez);
}
}
public Tile.Tile GetTileUnscaled(Vector3 pos)
{
long pSize = Options.Instance.PageSize;
long w = (long) ((float)Options.Instance.World_Width * 0.5f);
long h = (long) ((float)Options.Instance.World_Height * 0.5f);
Vector3 TileRefPos = pos;
long pagex = (long)(TileRefPos.x / pSize + w);
long pagez = (long)(TileRefPos.z / pSize + h);
// make sure indices are not negative or outside range of number of pages
if (pagex < 0 || pagex >= w*2 || pagez >= h*2 || pagez < 0)
return null;
else
{
long tSize = Options.Instance.TileSize;
long tilex = (long)((TileRefPos.x - ((pagex - w) * pSize)) / tSize);
long tilez = (long)((TileRefPos.z - ((pagez - h) * pSize)) / tSize);
pSize = (pSize / tSize) - 1;
if (tilex > pSize)
tilex = pSize;
else if (tilex < 0)
tilex = 0;
if (tilez > pSize)
tilez = pSize;
else if (tilez < 0)
tilez = 0;
return pages[pagex][pagez].GetTile( tilex, tilez );
}
}
protected void processLoading( )
{
// Preload, load, unload and post unload as required
/* We try to PreLoad
If no preload is required, then try to Load
If no load is required, then try to UnLoad
If no unload is required, then try to PostUnLoad.
*/
Page e;
e = pagePreloadQueue.Pop();
if ( e != null )
{
e.Preload();
}
else
{
e = pageLoadQueue.Pop();
if ( e != null )
{
e.Load( ref sceneRoot );
if ( e.IsLoaded == false )
{
if ( e.IsPreLoaded == false )
{
// If we are not PreLoaded, then we must preload
pagePreloadQueue.Push( e );
}
// If we are not loaded then queue again, since maybe we are not preloaded.
pageLoadQueue.Push( e );
}
}
else
{
e = pageUnloadQueue.Pop();
if ( e != null )
{
e.Unload();
}
else
{
e = pagePostunloadQueue.Pop();
if ( e != null )
{
e.PostUnload();
if ( e.IsPreLoaded)
{
// If we are not post unloaded the queue again
pagePostunloadQueue.Push( e );
}
}
}
}
}
// load some renderables
RenderableManager.Instance.ExecuteRenderableLoading();
}
}
}
| |
#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
#if !(NET20 || NET35)
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
using System.Linq.Expressions;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Utilities
{
internal class ExpressionReflectionDelegateFactory : ReflectionDelegateFactory
{
private static readonly ExpressionReflectionDelegateFactory _instance = new ExpressionReflectionDelegateFactory();
internal static ReflectionDelegateFactory Instance => _instance;
public override ObjectConstructor<object> CreateParameterizedConstructor(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, nameof(method));
Type type = typeof(object);
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, null, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(ObjectConstructor<object>), callExpression, argsParameterExpression);
ObjectConstructor<object> compiled = (ObjectConstructor<object>)lambdaExpression.Compile();
return compiled;
}
public override MethodCall<T, object> CreateMethodCall<T>(MethodBase method)
{
ValidationUtils.ArgumentNotNull(method, nameof(method));
Type type = typeof(object);
ParameterExpression targetParameterExpression = Expression.Parameter(type, "target");
ParameterExpression argsParameterExpression = Expression.Parameter(typeof(object[]), "args");
Expression callExpression = BuildMethodCall(method, type, targetParameterExpression, argsParameterExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(MethodCall<T, object>), callExpression, targetParameterExpression, argsParameterExpression);
MethodCall<T, object> compiled = (MethodCall<T, object>)lambdaExpression.Compile();
return compiled;
}
private class ByRefParameter
{
public Expression Value;
public ParameterExpression Variable;
public bool IsOut;
}
private Expression BuildMethodCall(MethodBase method, Type type, ParameterExpression targetParameterExpression, ParameterExpression argsParameterExpression)
{
ParameterInfo[] parametersInfo = method.GetParameters();
Expression[] argsExpression;
IList<ByRefParameter> refParameterMap;
if (parametersInfo.Length == 0)
{
argsExpression = CollectionUtils.ArrayEmpty<Expression>();
refParameterMap = CollectionUtils.ArrayEmpty<ByRefParameter>();
}
else
{
argsExpression = new Expression[parametersInfo.Length];
refParameterMap = new List<ByRefParameter>();
for (int i = 0; i < parametersInfo.Length; i++)
{
ParameterInfo parameter = parametersInfo[i];
Type parameterType = parameter.ParameterType;
bool isByRef = false;
if (parameterType.IsByRef)
{
parameterType = parameterType.GetElementType();
isByRef = true;
}
Expression indexExpression = Expression.Constant(i);
Expression paramAccessorExpression = Expression.ArrayIndex(argsParameterExpression, indexExpression);
Expression argExpression = EnsureCastExpression(paramAccessorExpression, parameterType, !isByRef);
if (isByRef)
{
ParameterExpression variable = Expression.Variable(parameterType);
refParameterMap.Add(new ByRefParameter {Value = argExpression, Variable = variable, IsOut = parameter.IsOut});
argExpression = variable;
}
argsExpression[i] = argExpression;
}
}
Expression callExpression;
if (method.IsConstructor)
{
callExpression = Expression.New((ConstructorInfo)method, argsExpression);
}
else if (method.IsStatic)
{
callExpression = Expression.Call((MethodInfo)method, argsExpression);
}
else
{
Expression readParameter = EnsureCastExpression(targetParameterExpression, method.DeclaringType);
callExpression = Expression.Call(readParameter, (MethodInfo)method, argsExpression);
}
if (method is MethodInfo m)
{
if (m.ReturnType != typeof(void))
{
callExpression = EnsureCastExpression(callExpression, type);
}
else
{
callExpression = Expression.Block(callExpression, Expression.Constant(null));
}
}
else
{
callExpression = EnsureCastExpression(callExpression, type);
}
if (refParameterMap.Count > 0)
{
IList<ParameterExpression> variableExpressions = new List<ParameterExpression>();
IList<Expression> bodyExpressions = new List<Expression>();
foreach (ByRefParameter p in refParameterMap)
{
if (!p.IsOut)
{
bodyExpressions.Add(Expression.Assign(p.Variable, p.Value));
}
variableExpressions.Add(p.Variable);
}
bodyExpressions.Add(callExpression);
callExpression = Expression.Block(variableExpressions, bodyExpressions);
}
return callExpression;
}
public override Func<T> CreateDefaultConstructor<T>(Type type)
{
ValidationUtils.ArgumentNotNull(type, "type");
// avoid error from expressions compiler because of abstract class
if (type.IsAbstract())
{
return () => (T)Activator.CreateInstance(type);
}
try
{
Type resultType = typeof(T);
Expression expression = Expression.New(type);
expression = EnsureCastExpression(expression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T>), expression);
Func<T> compiled = (Func<T>)lambdaExpression.Compile();
return compiled;
}
catch
{
// an error can be thrown if constructor is not valid on Win8
// will have INVOCATION_FLAGS_NON_W8P_FX_API invocation flag
return () => (T)Activator.CreateInstance(type);
}
}
public override Func<T, object> CreateGet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
Type instanceType = typeof(T);
Type resultType = typeof(object);
ParameterExpression parameterExpression = Expression.Parameter(instanceType, "instance");
Expression resultExpression;
MethodInfo getMethod = propertyInfo.GetGetMethod(true);
if (getMethod.IsStatic)
{
resultExpression = Expression.MakeMemberAccess(null, propertyInfo);
}
else
{
Expression readParameter = EnsureCastExpression(parameterExpression, propertyInfo.DeclaringType);
resultExpression = Expression.MakeMemberAccess(readParameter, propertyInfo);
}
resultExpression = EnsureCastExpression(resultExpression, resultType);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Func<T, object>), resultExpression, parameterExpression);
Func<T, object> compiled = (Func<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Func<T, object> CreateGet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
ParameterExpression sourceParameter = Expression.Parameter(typeof(T), "source");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameter, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
fieldExpression = EnsureCastExpression(fieldExpression, typeof(object));
Func<T, object> compiled = Expression.Lambda<Func<T, object>>(fieldExpression, sourceParameter).Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(FieldInfo fieldInfo)
{
ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo));
// use reflection for structs
// expression doesn't correctly set value
if (fieldInfo.DeclaringType.IsValueType() || fieldInfo.IsInitOnly)
{
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(fieldInfo);
}
ParameterExpression sourceParameterExpression = Expression.Parameter(typeof(T), "source");
ParameterExpression valueParameterExpression = Expression.Parameter(typeof(object), "value");
Expression fieldExpression;
if (fieldInfo.IsStatic)
{
fieldExpression = Expression.Field(null, fieldInfo);
}
else
{
Expression sourceExpression = EnsureCastExpression(sourceParameterExpression, fieldInfo.DeclaringType);
fieldExpression = Expression.Field(sourceExpression, fieldInfo);
}
Expression valueExpression = EnsureCastExpression(valueParameterExpression, fieldExpression.Type);
BinaryExpression assignExpression = Expression.Assign(fieldExpression, valueExpression);
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), assignExpression, sourceParameterExpression, valueParameterExpression);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
public override Action<T, object> CreateSet<T>(PropertyInfo propertyInfo)
{
ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo));
// use reflection for structs
// expression doesn't correctly set value
if (propertyInfo.DeclaringType.IsValueType())
{
return LateBoundReflectionDelegateFactory.Instance.CreateSet<T>(propertyInfo);
}
Type instanceType = typeof(T);
Type valueType = typeof(object);
ParameterExpression instanceParameter = Expression.Parameter(instanceType, "instance");
ParameterExpression valueParameter = Expression.Parameter(valueType, "value");
Expression readValueParameter = EnsureCastExpression(valueParameter, propertyInfo.PropertyType);
MethodInfo setMethod = propertyInfo.GetSetMethod(true);
Expression setExpression;
if (setMethod.IsStatic)
{
setExpression = Expression.Call(setMethod, readValueParameter);
}
else
{
Expression readInstanceParameter = EnsureCastExpression(instanceParameter, propertyInfo.DeclaringType);
setExpression = Expression.Call(readInstanceParameter, setMethod, readValueParameter);
}
LambdaExpression lambdaExpression = Expression.Lambda(typeof(Action<T, object>), setExpression, instanceParameter, valueParameter);
Action<T, object> compiled = (Action<T, object>)lambdaExpression.Compile();
return compiled;
}
private Expression EnsureCastExpression(Expression expression, Type targetType, bool allowWidening = false)
{
Type expressionType = expression.Type;
// check if a cast or conversion is required
if (expressionType == targetType || (!expressionType.IsValueType() && targetType.IsAssignableFrom(expressionType)))
{
return expression;
}
if (targetType.IsValueType())
{
Expression convert = Expression.Unbox(expression, targetType);
if (allowWidening && targetType.IsPrimitive())
{
MethodInfo toTargetTypeMethod = typeof(Convert)
.GetMethod("To" + targetType.Name, new[] { typeof(object) });
if (toTargetTypeMethod != null)
{
convert = Expression.Condition(
Expression.TypeIs(expression, targetType),
convert,
Expression.Call(toTargetTypeMethod, expression));
}
}
return Expression.Condition(
Expression.Equal(expression, Expression.Constant(null, typeof(object))),
Expression.Default(targetType),
convert);
}
return Expression.Convert(expression, targetType);
}
}
}
#endif
| |
using System;
using System.Collections.Generic;
using Android.Content;
using Android.Util;
using Android.Views;
using Android.Widget;
namespace MonoDroid.Dialog
{
public static class DroidResources
{
public enum ElementLayout: int
{
dialog_boolfieldleft,
dialog_boolfieldright,
dialog_boolfieldsubleft,
dialog_boolfieldsubright,
dialog_button,
dialog_datefield,
dialog_fieldsetlabel,
dialog_labelfieldbelow,
dialog_labelfieldright,
dialog_onofffieldright,
dialog_panel,
dialog_root,
dialog_selectlist,
dialog_selectlistfield,
dialog_textarea,
dialog_floatimage,
dialog_textfieldbelow,
dialog_textfieldright,
}
public static View LoadFloatElementLayout(Context context, View convertView, ViewGroup parent, int layoutId, out TextView label, out SeekBar slider, out ImageView left, out ImageView right)
{
View layout = convertView ?? LoadLayout(context, parent, layoutId);
if (layout != null)
{
label = layout.FindViewById<TextView>(context.Resources.GetIdentifier("dialog_LabelField", "id", context.PackageName));
slider = layout.FindViewById<SeekBar>(context.Resources.GetIdentifier("dialog_SliderField", "id", context.PackageName));
left = layout.FindViewById<ImageView>(context.Resources.GetIdentifier("dialog_ImageLeft", "id", context.PackageName));
right = layout.FindViewById<ImageView>(context.Resources.GetIdentifier("dialog_ImageRight", "id", context.PackageName));
}
else
{
label = null;
slider = null;
left = right = null;
}
return layout;
}
private static View LoadLayout(Context context, ViewGroup parent, int layoutId)
{
try
{
LayoutInflater inflater = LayoutInflater.FromContext(context);
if (_resourceMap.ContainsKey((ElementLayout)layoutId))
{
string layoutName = _resourceMap[(ElementLayout)layoutId];
int layoutIndex = context.Resources.GetIdentifier(layoutName, "layout", context.PackageName);
return inflater.Inflate(layoutIndex, parent, false);
}
else
{
// TODO: figure out what context to use to get this right, currently doesn't inflate application resources
return inflater.Inflate(layoutId, parent, false);
}
}
catch (InflateException ex)
{
Log.Error("MDD", "Inflate failed: " + ex.Cause.Message);
}
catch (Exception ex)
{
Log.Error("MDD", "LoadLayout failed: " + ex.Message);
}
return null;
}
public static View LoadStringElementLayout(Context context, View convertView, ViewGroup parent, int layoutId, out TextView label, out TextView value)
{
View layout = convertView ?? LoadLayout(context, parent, layoutId);
if (layout != null)
{
label = layout.FindViewById<TextView>(context.Resources.GetIdentifier("dialog_LabelField", "id", context.PackageName));
value = layout.FindViewById<TextView>(context.Resources.GetIdentifier("dialog_ValueField", "id", context.PackageName));
if(label == null || value == null)
{
layout = LoadLayout(context, parent, layoutId);
label = layout.FindViewById<TextView>(context.Resources.GetIdentifier("dialog_LabelField", "id", context.PackageName));
value = layout.FindViewById<TextView>(context.Resources.GetIdentifier("dialog_ValueField", "id", context.PackageName));
}
}
else
{
label = null;
value = null;
}
return layout;
}
public static View LoadButtonLayout(Context context, View convertView, ViewGroup parent, int layoutId, out Button button)
{
View layout = LoadLayout(context, parent, layoutId);
if (layout != null)
{
button = layout.FindViewById<Button>(context.Resources.GetIdentifier("dialog_Button", "id", context.PackageName));
}
else
{
button = null;
}
return layout;
}
public static View LoadMultilineElementLayout(Context context, View convertView, ViewGroup parent, int layoutId, out EditText value)
{
View layout = convertView ?? LoadLayout(context, parent, layoutId);
if (layout != null)
{
value = layout.FindViewById<EditText>(context.Resources.GetIdentifier("dialog_ValueField", "id", context.PackageName));
}
else
{
value = null;
}
return layout;
}
public static View LoadBooleanElementLayout(Context context, View convertView, ViewGroup parent, int layoutId, out TextView label, out TextView subLabel, out View value)
{
View layout = convertView ?? LoadLayout(context, parent, layoutId);
if (layout != null)
{
label = layout.FindViewById<TextView>(context.Resources.GetIdentifier("dialog_LabelField", "id", context.PackageName));
value = layout.FindViewById<View>(context.Resources.GetIdentifier("dialog_BoolField", "id", context.PackageName));
int id = context.Resources.GetIdentifier("dialog_LabelSubtextField", "id", context.PackageName);
subLabel = (id >= 0) ? layout.FindViewById<TextView>(id): null;
}
else
{
label = null;
value = null;
subLabel = null;
}
return layout;
}
public static View LoadStringEntryLayout(Context context, View convertView, ViewGroup parent, int layoutId, out TextView label, out EditText value)
{
View layout = LoadLayout(context, parent, layoutId);
if (layout != null)
{
label = layout.FindViewById<TextView>(context.Resources.GetIdentifier("dialog_LabelField", "id", context.PackageName));
value = layout.FindViewById<EditText>(context.Resources.GetIdentifier("dialog_ValueField", "id", context.PackageName));
}
else
{
label = null;
value = null;
}
return layout;
}
private static Dictionary<ElementLayout, string> _resourceMap;
static DroidResources()
{
_resourceMap = new Dictionary<ElementLayout, string>()
{
// Label templates
{ ElementLayout.dialog_labelfieldbelow, "dialog_labelfieldbelow"},
{ ElementLayout.dialog_labelfieldright, "dialog_labelfieldright"},
// Boolean and Checkbox templates
{ ElementLayout.dialog_boolfieldleft, "dialog_boolfieldleft"},
{ ElementLayout.dialog_boolfieldright, "dialog_boolfieldright"},
{ ElementLayout.dialog_boolfieldsubleft, "dialog_boolfieldsubleft"},
{ ElementLayout.dialog_boolfieldsubright, "dialog_boolfieldsubright"},
{ ElementLayout.dialog_onofffieldright, "dialog_onofffieldright"},
// Root templates
{ ElementLayout.dialog_root, "dialog_root"},
// Entry templates
{ ElementLayout.dialog_textfieldbelow, "dialog_textfieldbelow"},
{ ElementLayout.dialog_textfieldright, "dialog_textfieldright"},
// Slider
{ ElementLayout.dialog_floatimage, "dialog_floatimage"},
// Button templates
{ ElementLayout.dialog_button, "dialog_button"},
// Date
{ ElementLayout.dialog_datefield, "dialog_datefield"},
//
{ ElementLayout.dialog_fieldsetlabel, "dialog_fieldsetlabel"},
{ ElementLayout.dialog_panel, "dialog_panel"},
//
{ ElementLayout.dialog_selectlist, "dialog_selectlist"},
{ ElementLayout.dialog_selectlistfield, "dialog_selectlistfield"},
{ ElementLayout.dialog_textarea, "dialog_textarea"},
};
}
}
}
| |
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Linq.Expressions;
namespace OrchardCore.DisplayManagement.Shapes
{
public class Composite : DynamicObject
{
protected readonly Dictionary<object, object> _props = new Dictionary<object, object>();
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return TryGetMemberImpl(binder.Name, out result);
}
protected virtual bool TryGetMemberImpl(string name, out object result)
{
if (_props.TryGetValue(name, out result))
{
return true;
}
result = null;
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
return TrySetMemberImpl(binder.Name, value);
}
protected virtual bool TrySetMemberImpl(string name, object value)
{
_props[name] = value;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (args.Length == 0)
{
return TryGetMemberImpl(binder.Name, out result);
}
// method call with one argument will assign the property
if (args.Length == 1)
{
result = this;
return TrySetMemberImpl(binder.Name, args.First());
}
if (!base.TryInvokeMember(binder, args, out result))
{
if (binder.Name == "ToString")
{
result = string.Empty;
return true;
}
return false;
}
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes.Length != 1)
{
return base.TryGetIndex(binder, indexes, out result);
}
var index = indexes.First();
if (_props.TryGetValue(index, out result))
{
return true;
}
// try to access an existing member
var strinIndex = index as string;
if (strinIndex != null && TryGetMemberImpl(strinIndex, out result))
{
return true;
}
return base.TryGetIndex(binder, indexes, out result);
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (indexes.Length != 1)
{
return base.TrySetIndex(binder, indexes, value);
}
var index = indexes[0];
// try to access an existing member
var strinIndex = index as string;
if (strinIndex != null && TrySetMemberImpl(strinIndex, value))
{
return true;
}
_props[indexes[0]] = value;
return true;
}
public IDictionary<object, object> Properties
{
get { return _props; }
}
public static bool operator ==(Composite a, Nil b)
{
return null == a;
}
public static bool operator !=(Composite a, Nil b)
{
return !(a == b);
}
protected bool Equals(Composite other)
{
return Equals(_props, other._props);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return Equals((Composite)obj);
}
public override int GetHashCode()
{
return (_props != null ? _props.GetHashCode() : 0);
}
}
public class Nil : DynamicObject
{
static readonly Nil Singleton = new Nil();
public static Nil Instance { get { return Singleton; } }
private Nil()
{
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = Instance;
return true;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
result = Instance;
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = Nil.Instance;
return true;
}
public override bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
{
switch (binder.Operation)
{
case ExpressionType.Equal:
result = ReferenceEquals(arg, Nil.Instance) || (object)arg == null;
return true;
case ExpressionType.NotEqual:
result = !ReferenceEquals(arg, Nil.Instance) && (object)arg != null;
return true;
}
return base.TryBinaryOperation(binder, arg, out result);
}
public static bool operator ==(Nil a, Nil b)
{
return true;
}
public static bool operator !=(Nil a, Nil b)
{
return false;
}
public static bool operator ==(Nil a, object b)
{
return ReferenceEquals(a, b) || (object)b == null;
}
public static bool operator !=(Nil a, object b)
{
return !(a == b);
}
public override bool Equals(object obj)
{
if (obj == null)
{
return true;
}
return ReferenceEquals(obj, Nil.Instance);
}
public override int GetHashCode()
{
return 0;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
return true;
}
public override string ToString()
{
return string.Empty;
}
}
}
| |
#if !UseMapBoxAsMapImage
// Copyright 2005, 2006 - Morten Nielsen (www.iter.dk)
//
// This file is part of SharpMap.
// SharpMap 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 of the License, or
// (at your option) any later version.
//
// SharpMap 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 SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;
using NetTopologySuite.Geometries;
using SharpMap.Data;
using SharpMap.Layers;
using Point = NetTopologySuite.Geometries.Coordinate;
using Common.Logging;
namespace SharpMap.Forms
{
/// <summary>
/// MapImage Class - MapImage control for Windows forms
/// </summary>
/// <remarks>
/// The MapImage control adds basic functionality to a Windows Form, such as dynamic pan, zoom and data query.
/// </remarks>
[DesignTimeVisible(true)]
[Obsolete("Use MapBox instead, MapImage will be removed after 1.0 release")]
public class MapImage : PictureBox
{
static ILog logger = LogManager.GetLogger(typeof(MapImage));
#region Tools enum
/// <summary>
/// Map tools enumeration
/// </summary>
public enum Tools
{
/// <summary>
/// Pan
/// </summary>
Pan,
/// <summary>
/// Zoom in
/// </summary>
ZoomIn,
/// <summary>
/// Zoom out
/// </summary>
ZoomOut,
/// <summary>
/// Query tool
/// </summary>
Query,
/// <summary>
/// Pan on drag, Query on click
/// </summary>
PanOrQuery,
/// <summary>
/// No active tool
/// </summary>
None
}
#endregion
private Tools _activetool;
private double _fineZoomFactor = 10;
private bool _isCtrlPressed;
private Map _map;
private int _queryLayerIndex;
private double _wheelZoomMagnitude = 2;
private System.Drawing.Point _mousedrag;
private bool _mousedragging;
private Image _mousedragImg;
private bool _panOnClick;
private bool _zoomOnDblClick;
private Image _dragImg1, _dragImg2, _dragImgSupp;
private Bitmap _staticMap;
private Bitmap _variableMap;
private bool _panOrQueryIsPan;
private bool _zoomToPointer = false;
/// <summary>
/// Initializes a new map
/// </summary>
public MapImage()
{
_map = new Map(Size);
_activetool = Tools.None;
base.MouseMove += new System.Windows.Forms.MouseEventHandler(MapImage_MouseMove);
base.MouseUp += new System.Windows.Forms.MouseEventHandler(MapImage_MouseUp);
base.MouseDown += new System.Windows.Forms.MouseEventHandler(MapImage_MouseDown);
base.MouseWheel += new System.Windows.Forms.MouseEventHandler(MapImage_Wheel);
base.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(MapImage_DblClick);
_map.VariableLayers.VariableLayerCollectionRequery += this.VariableLayersRequery;
Cursor = Cursors.Cross;
DoubleBuffered = true;
}
protected override void Dispose(bool disposing)
{
if (_map != null)
{
// special handling to prevent spurious VariableLayers events
_map.VariableLayers.Interval = 0;
_map.VariableLayers.VariableLayerCollectionRequery -= this.VariableLayersRequery;
}
base.Dispose(disposing);
}
[Description("The amount which a single movement of the mouse wheel zooms by.")]
[DefaultValue(-2)]
[Category("Behavior")]
public double WheelZoomMagnitude
{
get { return _wheelZoomMagnitude; }
set { _wheelZoomMagnitude = value; }
}
[Description("The amount which the WheelZoomMagnitude is divided by " +
"when the Control key is pressed. A number greater than 1 decreases " +
"the zoom, and less than 1 increases it. A negative number reverses it.")]
[DefaultValue(10)]
[Category("Behavior")]
public double FineZoomFactor
{
get { return _fineZoomFactor; }
set { _fineZoomFactor = value; }
}
/// <summary>
/// Sets whether the mouse wheel should zoom to the pointer location
/// </summary>
[Description("Sets whether the mouse wheel should zoom to the pointer location")]
[DefaultValue(false)]
[Category("Behavior")]
public bool ZoomToPointer
{
get { return _zoomToPointer; }
set { _zoomToPointer = value; }
}
/// <summary>
/// Map reference
/// </summary>
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public Map Map
{
get { return _map; }
set
{
_map = value;
if (_map != null)
{
_map.VariableLayers.VariableLayerCollectionRequery += new VariableLayerCollectionRequeryHandler(VariableLayersRequery);
Refresh();
}
}
}
/// <summary>
/// Handles need to requery of variable layers
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void VariableLayersRequery(object sender, EventArgs e)
{
lock (_map)
{
if (_mousedragging) return;
_variableMap = GetMap(_map.VariableLayers, LayerCollectionType.Variable);
}
UpdateImage();
}
/// <summary>
/// Gets or sets the index of the active query layer
/// </summary>
public int QueryLayerIndex
{
get { return _queryLayerIndex; }
set { _queryLayerIndex = value; }
}
/// <summary>
/// Sets the active map tool
/// </summary>
public Tools ActiveTool
{
get { return _activetool; }
set
{
bool fireevent = (value != _activetool);
_activetool = value;
if (value == Tools.Pan)
Cursor = Cursors.Hand;
else
Cursor = Cursors.Cross;
if (fireevent)
if (ActiveToolChanged != null)
ActiveToolChanged(value);
// Check if settings collide
if (value != Tools.None && ZoomOnDblClick)
ZoomOnDblClick = false;
if (value != Tools.Pan && PanOnClick)
PanOnClick = false;
}
}
///// <summary>
///// Sets the direction of wheel for zoom-in operation
///// </summary>
//public bool WheelZoomForward
//{
// get { return _wheelZoomDirection==-1; }
// set { _wheelZoomDirection = (value == true) ? -1 : 1; }
//}
/// <summary>
/// Sets whether the "go-to-cursor-on-click" feature is enabled or not (even if enabled it works only if the active tool is Pan)
/// </summary>
[Description("Sets whether the \"go-to-cursor-on-click\" feature is enabled or not (even if enabled it works only if the active tool is Pan)")]
[DefaultValue(true)]
[Category("Behavior")]
public bool PanOnClick
{
get { return _panOnClick; }
set
{
ActiveTool = Tools.Pan;
_panOnClick = value;
}
}
/// <summary>
/// Sets whether the "go-to-cursor-and-zoom-in-on-double-click" feature is enable or not
/// </summary>
[Description("Sets whether the \"go-to-cursor-and-zoom-in-on-double-click\" feature is enable or not. This only works if no tool is currently active.")]
[DefaultValue(true)]
[Category("Behavior")]
public bool ZoomOnDblClick
{
get { return _zoomOnDblClick; }
set {
if (value)
ActiveTool = Tools.None;
_zoomOnDblClick = value;
}
}
/// <summary>
/// Refreshes the map
/// </summary>
public override void Refresh()
{
if (_map != null)
{
_map.Size = Size;
_staticMap = GetMap(_map.Layers, LayerCollectionType.Static);
_variableMap = GetMap(_map.VariableLayers, LayerCollectionType.Variable);
UpdateImage();
base.Refresh();
if (MapRefreshed != null)
MapRefreshed(this, null);
}
}
private Bitmap GetMap(LayerCollection layers, LayerCollectionType layerCollectionType)
{
if ((layers == null || layers.Count == 0))
return null;
Bitmap retval = new Bitmap(Width, Height);
Graphics g = Graphics.FromImage(retval);
_map.RenderMap(g, layerCollectionType);
g.Dispose();
if (layerCollectionType == LayerCollectionType.Variable)
retval.MakeTransparent(_map.BackColor);
return retval;
}
private void UpdateImage()
{
if (!(_staticMap == null && _variableMap == null))
{
Bitmap bmp = new Bitmap(Width, Height);
Graphics g = Graphics.FromImage(bmp);
if (_staticMap != null)
g.DrawImageUnscaled(_staticMap, 0, 0);
if (_variableMap != null)
g.DrawImageUnscaled(_variableMap, 0, 0);
g.Dispose();
Image = bmp;
}
}
protected override void OnKeyDown(KeyEventArgs e)
{
_isCtrlPressed = e.Control;
if (logger.IsDebugEnabled)
logger.DebugFormat("Ctrl: {0}", _isCtrlPressed);
base.OnKeyDown(e);
}
protected override void OnKeyUp(KeyEventArgs e)
{
_isCtrlPressed = e.Control;
if (logger.IsDebugEnabled)
logger.DebugFormat("Ctrl: {0}", _isCtrlPressed);
base.OnKeyUp(e);
}
protected override void OnMouseHover(EventArgs e)
{
if (!Focused)
{
bool isFocused = Focus();
if (logger.IsDebugEnabled)
logger.Debug(isFocused);
}
base.OnMouseHover(e);
}
private void MapImage_Wheel(object sender, MouseEventArgs e)
{
if (_map != null)
{
if (_zoomToPointer)
_map.Center = _map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true);
double scale = (e.Delta / 120.0);
double scaleBase = 1 + (_wheelZoomMagnitude / (10 * (_isCtrlPressed ? _fineZoomFactor : 1)));
_map.Zoom *= Math.Pow(scaleBase, scale);
if (MapZoomChanged != null)
MapZoomChanged(_map.Zoom);
if (_zoomToPointer)
{
int NewCenterX = (this.Width / 2) + ((this.Width / 2) - e.X);
int NewCenterY = (this.Height / 2) + ((this.Height / 2) - e.Y);
_map.Center = _map.ImageToWorld(new System.Drawing.Point(NewCenterX, NewCenterY), true);
if (MapCenterChanged != null)
MapCenterChanged(_map.Center);
}
Refresh();
}
}
private void MapImage_MouseDown(object sender, MouseEventArgs e)
{
_panOrQueryIsPan = false;
if (_map != null)
{
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle) //dragging
_mousedrag = e.Location;
if (MouseDown != null)
MouseDown(_map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true), e);
}
}
private void MapImage_DblClick(object sender, MouseEventArgs e)
{
if (_map != null && ActiveTool == Tools.None)
{
double scaleBase = 1d + (Math.Abs(_wheelZoomMagnitude) / 10d);
if (_zoomOnDblClick && e.Button == MouseButtons.Left)
{
_map.Center = _map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true);
if (MapCenterChanged != null) { MapCenterChanged(_map.Center); }
_map.Zoom /= scaleBase;
if (MapZoomChanged != null) { MapZoomChanged(_map.Zoom); }
Refresh();
}
else if (_zoomOnDblClick && e.Button == MouseButtons.Right)
{
_map.Zoom *= scaleBase;
if (MapZoomChanged != null) { MapZoomChanged(_map.Zoom); }
Refresh();
}
}
}
private void MapImage_MouseMove(object sender, MouseEventArgs e)
{
if (_map != null)
{
Point p = _map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true);
if (MouseMove != null)
MouseMove(p, e);
if (Image != null && e.Location != _mousedrag && !_mousedragging && (e.Button == MouseButtons.Left|| e.Button == MouseButtons.Middle))
{
_mousedragImg = Image.Clone() as Image;
_mousedragging = true;
_dragImg1 = new Bitmap(Size.Width, Size.Height);
_dragImg2 = new Bitmap(Size.Width, Size.Height);
}
if (_mousedragging)
{
if (MouseDrag != null)
MouseDrag(p, e);
if (ActiveTool == Tools.Pan || ActiveTool == Tools.PanOrQuery)
{
Graphics g = Graphics.FromImage(_dragImg1);
g.Clear(Color.Transparent);
g.DrawImageUnscaled(_mousedragImg,
new System.Drawing.Point(e.Location.X - _mousedrag.X,
e.Location.Y - _mousedrag.Y));
g.Dispose();
_dragImgSupp = _dragImg2;
_dragImg2 = _dragImg1;
_dragImg1 = _dragImgSupp;
Image = _dragImg2;
_panOrQueryIsPan = true;
base.Refresh();
}
else if (ActiveTool == Tools.ZoomIn || ActiveTool == Tools.ZoomOut)
{
Image img = new Bitmap(Size.Width, Size.Height);
Graphics g = Graphics.FromImage(img);
g.Clear(Color.Transparent);
float scale;
if (e.Y - _mousedrag.Y < 0) //Zoom out
scale = (float)Math.Pow(1 / (float)(_mousedrag.Y - e.Y), 0.5);
else //Zoom in
scale = 1 + (e.Y - _mousedrag.Y) * 0.1f;
RectangleF rect = new RectangleF(0, 0, Width, Height);
if (_map.Zoom / scale < _map.MinimumZoom)
scale = (float)Math.Round(_map.Zoom / _map.MinimumZoom, 4);
rect.Width *= scale;
rect.Height *= scale;
rect.Offset(Width / 2f - rect.Width / 2f, Height / 2f - rect.Height / 2);
g.DrawImage(_mousedragImg, rect);
g.Dispose();
Image = img;
if (MapZooming != null)
MapZooming(scale);
}
}
}
}
private void MapImage_MouseUp(object sender, MouseEventArgs e)
{
if (_map != null)
{
if (MouseUp != null)
MouseUp(_map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true), e);
if (e.Button == MouseButtons.Left || e.Button == MouseButtons.Middle)
{
if (ActiveTool == Tools.ZoomOut)
{
double scale = 0.5;
if (!_mousedragging)
{
_map.Center = _map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true);
if (MapCenterChanged != null)
MapCenterChanged(_map.Center);
}
else
{
if (e.Y - _mousedrag.Y < 0) //Zoom out
scale = (float)Math.Pow(1 / (float)(_mousedrag.Y - e.Y), 0.5);
else //Zoom in
scale = 1 + (e.Y - _mousedrag.Y) * 0.1;
}
_map.Zoom *= 1 / scale;
if (MapZoomChanged != null)
MapZoomChanged(_map.Zoom);
Refresh();
}
else if (ActiveTool == Tools.ZoomIn)
{
double scale = 2;
if (!_mousedragging)
{
_map.Center = _map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true);
if (MapCenterChanged != null)
MapCenterChanged(_map.Center);
}
else
{
if (e.Y - _mousedrag.Y < 0) //Zoom out
scale = (float)Math.Pow(1 / (float)(_mousedrag.Y - e.Y), 0.5);
else //Zoom in
scale = 1 + (e.Y - _mousedrag.Y) * 0.1;
}
_map.Zoom *= 1 / scale;
if (MapZoomChanged != null)
MapZoomChanged(_map.Zoom);
Refresh();
}
else if (ActiveTool == Tools.Pan || (ActiveTool == Tools.PanOrQuery && _panOrQueryIsPan))
{
if (_mousedragging)
{
System.Drawing.Point pnt = new System.Drawing.Point(Width / 2 + (_mousedrag.X - e.Location.X),
Height / 2 + (_mousedrag.Y - e.Location.Y));
_map.Center = _map.ImageToWorld(pnt, true);
if (MapCenterChanged != null)
MapCenterChanged(_map.Center);
}
else if(_panOnClick && !_zoomOnDblClick)
{
_map.Center = _map.ImageToWorld(new System.Drawing.Point(e.X, e.Y), true);
if (MapCenterChanged != null)
MapCenterChanged(_map.Center);
}
Refresh();
}
else if (ActiveTool == Tools.Query || (ActiveTool == Tools.PanOrQuery && !_panOrQueryIsPan))
{
if (_queryLayerIndex < 0)
MessageBox.Show("No active layer to query");
else if (_queryLayerIndex < _map.Layers.Count)
QueryLayer(_map.Layers[_queryLayerIndex], new PointF(e.X, e.Y));
else if(_queryLayerIndex - Map.Layers.Count < _map.VariableLayers.Count)
QueryLayer(_map.VariableLayers[_queryLayerIndex - Map.Layers.Count], new PointF(e.X, e.Y));
else
MessageBox.Show("No active layer to query");
}
}
if (_mousedragImg != null)
{
_mousedragImg.Dispose();
_mousedragImg = null;
}
_mousedragging = false;
}
}
/// <summary>
/// Performs query on layer if it is of <see cref="ICanQueryLayer"/>
/// </summary>
/// <param name="layer">The layer to query</param>
/// <param name="pt">The point to perform the query on</param>
private void QueryLayer(ILayer layer, PointF pt)
{
if (layer is ICanQueryLayer)
{
ICanQueryLayer queryLayer = layer as ICanQueryLayer;
Envelope bbox = new Envelope(
_map.ImageToWorld(pt, true)).Grow(_map.PixelSize*5);
FeatureDataSet ds = new FeatureDataSet();
queryLayer.ExecuteIntersectionQuery(bbox, ds);
if (MapQueried != null)
{
if (ds.Tables.Count > 0)
MapQueried(ds.Tables[0]);
else
MapQueried(new FeatureDataTable());
}
if (MapQueriedDataSet != null)
MapQueriedDataSet(ds);
}
}
#region Events
#region Delegates
/// <summary>
/// Eventtype fired when the map tool is changed
/// </summary>
/// <param name="tool"></param>
public delegate void ActiveToolChangedHandler(Tools tool);
/// <summary>
/// Eventtype fired when the center has changed
/// </summary>
/// <param name="center"></param>
public delegate void MapCenterChangedHandler(Point center);
/// <summary>
/// Eventtype fired when the map is queried
/// </summary>
/// <param name="data"></param>
[Obsolete]
public delegate void MapQueryHandler(FeatureDataTable data);
/// <summary>
/// Eventtype fired when the map is queried
/// </summary>
/// <param name="data"></param>
public delegate void MapQueryDataSetHandler(FeatureDataSet data);
/// <summary>
/// Eventtype fired when the zoom was or are being changed
/// </summary>
/// <param name="zoom"></param>
public delegate void MapZoomHandler(double zoom);
/// <summary>
/// MouseEventtype fired from the MapImage control
/// </summary>
/// <param name="WorldPos"></param>
/// <param name="ImagePos"></param>
public delegate void MouseEventHandler(Point WorldPos, MouseEventArgs ImagePos);
#endregion
/// <summary>
/// Fires when mouse moves over the map
/// </summary>
public new event MouseEventHandler MouseMove;
/// <summary>
/// Fires when map received a mouseclick
/// </summary>
public new event MouseEventHandler MouseDown;
/// <summary>
/// Fires when mouse is released
/// </summary>
public new event MouseEventHandler MouseUp;
/// <summary>
/// Fired when mouse is dragging
/// </summary>
public event MouseEventHandler MouseDrag;
/// <summary>
/// Fired when the map has been refreshed
/// </summary>
public event EventHandler MapRefreshed;
/// <summary>
/// Fired when the zoom value has changed
/// </summary>
public event MapZoomHandler MapZoomChanged;
/// <summary>
/// Fired when the map is being zoomed
/// </summary>
public event MapZoomHandler MapZooming;
/// <summary>
/// Fired when the map is queried
/// </summary>
public event MapQueryHandler MapQueried;
public event MapQueryDataSetHandler MapQueriedDataSet;
/// <summary>
/// Fired when the center of the map has changed
/// </summary>
public event MapCenterChangedHandler MapCenterChanged;
/// <summary>
/// Fired when the active map tool has changed
/// </summary>
public event ActiveToolChangedHandler ActiveToolChanged;
#endregion
}
}
#endif
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//
// Remoting Infrastructure Sink for making calls across context
// boundaries.
//
namespace System.Runtime.Remoting.Channels {
using System;
using System.Collections;
using System.IO;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security;
using System.Security.Permissions;
using System.Security.Policy;
using System.Security.Principal;
using System.Text;
using System.Threading;
using System.Runtime.ConstrainedExecution;
[Serializable]
internal class CrossAppDomainChannel : IChannel, IChannelSender, IChannelReceiver
{
private const String _channelName = "XAPPDMN";
private const String _channelURI = "XAPPDMN_URI";
private static CrossAppDomainChannel gAppDomainChannel
{
get { return Thread.GetDomain().RemotingData.ChannelServicesData.xadmessageSink; }
set { Thread.GetDomain().RemotingData.ChannelServicesData.xadmessageSink = value; }
}
private static Object staticSyncObject = new Object();
private static PermissionSet s_fullTrust = new PermissionSet(PermissionState.Unrestricted);
internal static CrossAppDomainChannel AppDomainChannel
{
get
{
if (gAppDomainChannel == null)
{
CrossAppDomainChannel tmpChnl = new CrossAppDomainChannel();
lock (staticSyncObject)
{
if (gAppDomainChannel == null)
{
gAppDomainChannel = tmpChnl;
}
}
}
return gAppDomainChannel;
}
}
[System.Security.SecurityCritical] // auto-generated
internal static void RegisterChannel()
{
CrossAppDomainChannel adc = CrossAppDomainChannel.AppDomainChannel;
ChannelServices.RegisterChannelInternal((IChannel)adc, false /*ensureSecurity*/);
}
//
// IChannel Methods
//
public virtual String ChannelName
{
[System.Security.SecurityCritical] // auto-generated
get{ return _channelName; }
}
public virtual String ChannelURI
{
get{ return _channelURI; }
}
public virtual int ChannelPriority
{
[System.Security.SecurityCritical] // auto-generated
get{ return 100;}
}
[System.Security.SecurityCritical] // auto-generated
public String Parse(String url, out String objectURI)
{
objectURI = url;
return null;
}
public virtual Object ChannelData
{
[System.Security.SecurityCritical] // auto-generated
get
{
return new CrossAppDomainData(
Context.DefaultContext.InternalContextID,
Thread.GetDomain().GetId(),
Identity.ProcessGuid);
}
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessageSink CreateMessageSink(String url, Object data,
out String objectURI)
{
// Set the out parameters
objectURI = null;
IMessageSink sink = null;
// <
if ((null != url) && (data == null))
{
if(url.StartsWith(_channelName, StringComparison.Ordinal))
{
throw new RemotingException(
Environment.GetResourceString(
"Remoting_AppDomains_NYI"));
}
}
else
{
Message.DebugOut("XAPPDOMAIN::Creating sink for data \n");
CrossAppDomainData xadData = data as CrossAppDomainData;
if (null != xadData)
{
if (xadData.ProcessGuid.Equals(Identity.ProcessGuid))
{
sink = CrossAppDomainSink.FindOrCreateSink(xadData);
}
}
}
return sink;
}
[System.Security.SecurityCritical] // auto-generated
public virtual String[] GetUrlsForUri(String objectURI)
{
throw new NotSupportedException(
Environment.GetResourceString(
"NotSupported_Method"));
//<
}
[System.Security.SecurityCritical] // auto-generated
public virtual void StartListening(Object data)
{
}
[System.Security.SecurityCritical] // auto-generated
public virtual void StopListening(Object data)
{
}
}
[Serializable]
internal class CrossAppDomainData
{
Object _ContextID = 0; // This is for backward compatibility
int _DomainID; // server appDomain ID
String _processGuid; // idGuid for the process (shared static)
internal virtual IntPtr ContextID {
get {
#if WIN32
return new IntPtr((int)_ContextID);
#else
return new IntPtr((long)_ContextID);
#endif
}
}
internal virtual int DomainID {
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
get {return _DomainID;}
}
internal virtual String ProcessGuid { get {return _processGuid;}}
internal CrossAppDomainData(IntPtr ctxId, int domainID, String processGuid)
{
_DomainID = domainID;
_processGuid = processGuid;
#if WIN32
_ContextID = ctxId.ToInt32();
#else
_ContextID = ctxId.ToInt64(); // This would have never worked anyway
#endif
}
internal bool IsFromThisProcess()
{
return Identity.ProcessGuid.Equals(_processGuid);
}
[System.Security.SecurityCritical] // auto-generated
internal bool IsFromThisAppDomain()
{
return IsFromThisProcess()
&&
(Thread.GetDomain().GetId() == _DomainID);
}
}
// Implements the Message Sink provided by the X-AppDomain channel.
// We try to use one instance of the sink to make calls to all remote
// objects in another AppDomain from one AppDomain.
internal class CrossAppDomainSink
: InternalSink, IMessageSink
{
internal const int GROW_BY = 0x8;
internal static volatile int[] _sinkKeys;
internal static volatile CrossAppDomainSink[] _sinks;
internal const string LCC_DATA_KEY = "__xADCall";
private static Object staticSyncObject = new Object();
private static InternalCrossContextDelegate s_xctxDel = new InternalCrossContextDelegate(DoTransitionDispatchCallback);
// each sink stores the default ContextID of the server side domain
// and the domain ID for the domain
internal CrossAppDomainData _xadData;
[System.Security.SecuritySafeCritical] // auto-generated
static CrossAppDomainSink()
{
}
internal CrossAppDomainSink(CrossAppDomainData xadData)
{
//
// WARNING: xadData.ContextID may not be valid at this point. Because
// CrossAppDomainData._ContextID is an IntPtr and IntPtrs are
// value types, the deserializer has to wait until the very
// end of deserialization to fixup value types. However, when
// we unmarshal objects, we need to setup the x-AD sink and
// initialize it with this data. Fortunately, that data won't
// be consumed until deserialization is complete, so we just
// need to take care not to read _ContextID in the constructor.
// The xadData object ref will be finalized by the time we need
// to consume its contents and everything should work properly.
//
_xadData = xadData;
}
// Note: this should be called from within a synch-block
internal static void GrowArrays(int oldSize)
{
if (_sinks == null)
{
_sinks = new CrossAppDomainSink[GROW_BY];
_sinkKeys = new int[GROW_BY];
}
else
{
CrossAppDomainSink[] tmpSinks = new CrossAppDomainSink[_sinks.Length + GROW_BY];
int[] tmpKeys = new int[_sinkKeys.Length + GROW_BY];
Array.Copy(_sinks, tmpSinks, _sinks.Length);
Array.Copy(_sinkKeys, tmpKeys, _sinkKeys.Length);
_sinks = tmpSinks;
_sinkKeys = tmpKeys;
}
}
internal static CrossAppDomainSink FindOrCreateSink(CrossAppDomainData xadData)
{
//
// WARNING: Do not read any value type member of xadData in this method!!
// xadData is not completely deserialized at this point. See
// warning in CrossAppDomainSink::.ctor above
//
lock(staticSyncObject) {
// Note: keep this in [....] with DomainUnloaded below
int key = xadData.DomainID;
if (_sinks == null)
{
GrowArrays(0);
}
int i=0;
while (_sinks[i] != null)
{
if (_sinkKeys[i] == key)
{
return _sinks[i];
}
i++;
if (i == _sinks.Length)
{
// could not find a sink, also need to Grow the array.
GrowArrays(i);
break;
}
}
// At this point we need to create a new sink and cache
// it at location "i"
_sinks[i] = new CrossAppDomainSink(xadData);
_sinkKeys[i] = key;
return _sinks[i];
}
}
internal static void DomainUnloaded(Int32 domainID)
{
int key = domainID;
lock(staticSyncObject) {
if (_sinks == null)
{
return;
}
// Note: keep this in [....] with FindOrCreateSink
int i = 0;
int remove = -1;
while (_sinks[i] != null)
{
if (_sinkKeys[i] == key)
{
BCLDebug.Assert(remove == -1, "multiple sinks?");
remove = i;
}
i++;
if (i == _sinks.Length)
{
break;
}
}
if (remove ==-1) //hasn't been initialized yet
return;
// The sink to remove is at index 'remove'
// We will move the last non-null entry to this location
BCLDebug.Assert(remove != -1, "Bad domainId for unload?");
_sinkKeys[remove] = _sinkKeys[i-1];
_sinks[remove] = _sinks[i-1];
_sinkKeys[i-1] = 0;
_sinks[i-1] = null;
}
}
[System.Security.SecurityCritical] // auto-generated
internal static byte[] DoDispatch(byte[] reqStmBuff,
SmuggledMethodCallMessage smuggledMcm,
out SmuggledMethodReturnMessage smuggledMrm)
{
//*********************** DE-SERIALIZE REQ-MSG ********************
IMessage desReqMsg = null;
if (smuggledMcm != null)
{
ArrayList deserializedArgs = smuggledMcm.FixupForNewAppDomain();
desReqMsg = new MethodCall(smuggledMcm, deserializedArgs);
}
else
{
MemoryStream reqStm = new MemoryStream(reqStmBuff);
desReqMsg = CrossAppDomainSerializer.DeserializeMessage(reqStm);
}
LogicalCallContext lcc = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
lcc.SetData(LCC_DATA_KEY, true);
// now we can delegate to the DispatchMessage to do the rest
IMessage retMsg = ChannelServices.SyncDispatchMessage(desReqMsg);
lcc.FreeNamedDataSlot(LCC_DATA_KEY);
smuggledMrm = SmuggledMethodReturnMessage.SmuggleIfPossible(retMsg);
if (smuggledMrm != null)
{
return null;
}
else
{
if (retMsg != null)
{
// Null out the principal since we won't use it on the other side.
// This is handled inside of SmuggleIfPossible for method call
// messages.
LogicalCallContext callCtx = (LogicalCallContext)
retMsg.Properties[Message.CallContextKey];
if (callCtx != null)
{
if (callCtx.Principal != null)
callCtx.Principal = null;
}
return CrossAppDomainSerializer.SerializeMessage(retMsg).GetBuffer();
}
//*********************** SERIALIZE RET-MSG ********************
return null;
}
} // DoDispatch
[System.Security.SecurityCritical] // auto-generated
internal static Object DoTransitionDispatchCallback(Object[] args)
{
byte[] reqStmBuff = (byte[])args[0];
SmuggledMethodCallMessage smuggledMcm = (SmuggledMethodCallMessage)args[1];
SmuggledMethodReturnMessage smuggledMrm = null;
byte[] retBuff = null;
try
{
#if !FEATURE_CORECLR
Message.DebugOut("#### : changed to Server Domain :: "+ (Thread.CurrentContext.InternalContextID).ToString("X") );
#endif
retBuff = DoDispatch(reqStmBuff, smuggledMcm, out smuggledMrm);
}
catch (Exception e)
{
// This will catch exceptions thrown by the infrastructure,
// Serialization/Deserialization etc
// Those thrown by the server are already taken care of
// and encoded in the retMsg .. so we don't come here for
// that case.
// We are in another appDomain, so we can't simply throw
// the exception object across. The following marshals it
// into a serialized return message.
IMessage retMsg =
new ReturnMessage(e, new ErrorMessage());
//*********************** SERIALIZE RET-MSG ******************
retBuff = CrossAppDomainSerializer.SerializeMessage(retMsg).GetBuffer();
retMsg = null;
}
args[2] = smuggledMrm;
return retBuff;
}
[System.Security.SecurityCritical] // auto-generated
internal byte[] DoTransitionDispatch(
byte[] reqStmBuff,
SmuggledMethodCallMessage smuggledMcm,
out SmuggledMethodReturnMessage smuggledMrm)
{
byte[] retBuff = null;
Object[] args = new Object[] { reqStmBuff, smuggledMcm, null };
retBuff = (byte[]) Thread.CurrentThread.InternalCrossContextCallback(null,
_xadData.ContextID,
_xadData.DomainID,
s_xctxDel,
args);
#if !FEATURE_CORECLR
Message.DebugOut("#### : changed back to Client Domain " + (Thread.CurrentContext.InternalContextID).ToString("X"));
#endif
smuggledMrm = (SmuggledMethodReturnMessage) args[2];
// System.Diagnostics.Debugger.Break();
return retBuff;
} // DoTransitionDispatch
[System.Security.SecurityCritical] // auto-generated
public virtual IMessage SyncProcessMessage(IMessage reqMsg)
{
Message.DebugOut("\n::::::::::::::::::::::::: CrossAppDomain Channel: [....] call starting");
IMessage errMsg = InternalSink.ValidateMessage(reqMsg);
if (errMsg != null)
{
return errMsg;
}
// currentPrincipal is used to save the current principal. It should be
// restored on the reply message.
IPrincipal currentPrincipal = null;
IMessage desRetMsg = null;
try
{
IMethodCallMessage mcmReqMsg = reqMsg as IMethodCallMessage;
if (mcmReqMsg != null)
{
LogicalCallContext lcc = mcmReqMsg.LogicalCallContext;
if (lcc != null)
{
// Special case Principal since if might not be serializable
currentPrincipal = lcc.RemovePrincipalIfNotSerializable();
}
}
MemoryStream reqStm = null;
SmuggledMethodCallMessage smuggledMcm = SmuggledMethodCallMessage.SmuggleIfPossible(reqMsg);
if (smuggledMcm == null)
{
//*********************** SERIALIZE REQ-MSG ****************
// Deserialization of objects requires permissions that users
// of remoting are not guaranteed to possess. Since remoting
// can guarantee that it's users can't abuse deserialization
// (since it won't allow them to pass in raw blobs of
// serialized data), it should assert the permissions
// necessary before calling the deserialization code. This
// will terminate the security stackwalk caused when
// serialization checks for the correct permissions at the
// remoting stack frame so the check won't continue on to
// the user and fail. <EMAIL>[from [....]]</EMAIL>
// We will hold off from doing this for x-process channels
// until the big picture of distributed security is finalized.
reqStm = CrossAppDomainSerializer.SerializeMessage(reqMsg);
}
// Retrieve calling caller context here, where it is safe from the view
// of app domain checking code
LogicalCallContext oldCallCtx = CallContext.SetLogicalCallContext(null);
// Call helper method here, to avoid confusion with stack frames & app domains
MemoryStream retStm = null;
byte[] responseBytes = null;
SmuggledMethodReturnMessage smuggledMrm;
try
{
if (smuggledMcm != null)
responseBytes = DoTransitionDispatch(null, smuggledMcm, out smuggledMrm);
else
responseBytes = DoTransitionDispatch(reqStm.GetBuffer(), null, out smuggledMrm);
}
finally
{
CallContext.SetLogicalCallContext(oldCallCtx);
}
if (smuggledMrm != null)
{
ArrayList deserializedArgs = smuggledMrm.FixupForNewAppDomain();
desRetMsg = new MethodResponse((IMethodCallMessage)reqMsg,
smuggledMrm,
deserializedArgs);
}
else
{
if (responseBytes != null) {
retStm = new MemoryStream(responseBytes);
Message.DebugOut("::::::::::::::::::::::::::: CrossAppDomain Channel: [....] call returning!!\n");
//*********************** DESERIALIZE RET-MSG **************
desRetMsg = CrossAppDomainSerializer.DeserializeMessage(retStm, reqMsg as IMethodCallMessage);
}
}
}
catch(Exception e)
{
Message.DebugOut("Arrgh.. XAppDomainSink::throwing exception " + e + "\n");
try
{
desRetMsg = new ReturnMessage(e, (reqMsg as IMethodCallMessage));
}
catch(Exception )
{
// Fatal Error .. can't do much here
}
}
// restore the principal if necessary.
if (currentPrincipal != null)
{
IMethodReturnMessage mrmRetMsg = desRetMsg as IMethodReturnMessage;
if (mrmRetMsg != null)
{
LogicalCallContext lcc = mrmRetMsg.LogicalCallContext;
lcc.Principal = currentPrincipal;
}
}
return desRetMsg;
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessageCtrl AsyncProcessMessage(IMessage reqMsg, IMessageSink replySink)
{
// This is the case where we take care of returning the calling
// thread asap by using the ThreadPool for completing the call.
// we use a more elaborate WorkItem and delegate the work to the thread pool
ADAsyncWorkItem workItem = new ADAsyncWorkItem(reqMsg,
(IMessageSink)this, /* nextSink */
replySink);
WaitCallback threadFunc = new WaitCallback(workItem.FinishAsyncWork);
ThreadPool.QueueUserWorkItem(threadFunc);
return null;
}
public IMessageSink NextSink
{
[System.Security.SecurityCritical] // auto-generated
get
{
// We are a terminating sink for this chain
return null;
}
}
}
/* package */
internal class ADAsyncWorkItem
{
// the replySink passed in to us in AsyncProcessMsg
private IMessageSink _replySink;
// the nextSink we have to call
private IMessageSink _nextSink;
[System.Security.SecurityCritical] // auto-generated
private LogicalCallContext _callCtx;
// the request msg passed in
private IMessage _reqMsg;
[System.Security.SecurityCritical] // auto-generated
internal ADAsyncWorkItem(IMessage reqMsg, IMessageSink nextSink, IMessageSink replySink)
{
_reqMsg = reqMsg;
_nextSink = nextSink;
_replySink = replySink;
_callCtx = Thread.CurrentThread.GetMutableExecutionContext().LogicalCallContext;
}
/* package */
[System.Security.SecurityCritical] // auto-generated
internal virtual void FinishAsyncWork(Object stateIgnored)
{
// install the call context that the calling thread actually had onto
// the threadPool thread.
LogicalCallContext threadPoolCallCtx = CallContext.SetLogicalCallContext(_callCtx);
IMessage retMsg = _nextSink.SyncProcessMessage(_reqMsg);
// send the reply back to the replySink we were provided with
// note: replySink may be null for one-way calls.
if (_replySink != null)
{
_replySink.SyncProcessMessage(retMsg);
}
CallContext.SetLogicalCallContext(threadPoolCallCtx);
}
}
internal static class CrossAppDomainSerializer
{
[System.Security.SecurityCritical] // auto-generated
internal static MemoryStream SerializeMessage(IMessage msg)
{
MemoryStream stm = new MemoryStream();
RemotingSurrogateSelector ss = new RemotingSurrogateSelector();
BinaryFormatter fmt = new BinaryFormatter();
fmt.SurrogateSelector = ss;
fmt.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
fmt.Serialize(stm, msg, null, false /* No Security check */);
// Reset the stream so that Deserialize happens correctly
stm.Position = 0;
return stm;
}
#if false
// called from MessageSmuggler classes
internal static MemoryStream SerializeMessageParts(ArrayList argsToSerialize, out Object[] smuggledArgs)
{
MemoryStream stm = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
RemotingSurrogateSelector ss = new RemotingSurrogateSelector();
fmt.SurrogateSelector = ss;
fmt.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
fmt.Serialize(stm, argsToSerialize, null, false ); // No Security check
smuggledArgs = fmt.CrossAppDomainArray;
stm.Position = 0;
return stm;
} // SerializeMessageParts
#endif
[System.Security.SecurityCritical] // auto-generated
internal static MemoryStream SerializeMessageParts(ArrayList argsToSerialize)
{
MemoryStream stm = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
RemotingSurrogateSelector ss = new RemotingSurrogateSelector();
fmt.SurrogateSelector = ss;
fmt.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
fmt.Serialize(stm, argsToSerialize, null, false /* No Security check */);
stm.Position = 0;
return stm;
} // SerializeMessageParts
// called from MessageSmuggler classes
[System.Security.SecurityCritical] // auto-generated
internal static void SerializeObject(Object obj, MemoryStream stm)
{
BinaryFormatter fmt = new BinaryFormatter();
RemotingSurrogateSelector ss = new RemotingSurrogateSelector();
fmt.SurrogateSelector = ss;
fmt.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
fmt.Serialize(stm, obj, null, false /* No Security check */);
} // SerializeMessageParts
// called from MessageSmuggler classes
[System.Security.SecurityCritical] // auto-generated
internal static MemoryStream SerializeObject(Object obj)
{
MemoryStream stm = new MemoryStream();
SerializeObject( obj, stm );
stm.Position = 0;
return stm;
} // SerializeMessageParts
[System.Security.SecurityCritical] // auto-generated
internal static IMessage DeserializeMessage(MemoryStream stm)
{
return DeserializeMessage(stm, null);
}
[System.Security.SecurityCritical] // auto-generated
internal static IMessage DeserializeMessage(
MemoryStream stm, IMethodCallMessage reqMsg)
{
if (stm == null)
throw new ArgumentNullException("stm");
stm.Position = 0;
BinaryFormatter fmt = new BinaryFormatter();
fmt.SurrogateSelector = null;
fmt.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
return (IMessage) fmt.Deserialize(stm, null, false /* No Security check */, true/*isCrossAppDomain*/, reqMsg);
}
#if false
// called from MessageSmuggler classes
internal static ArrayList DeserializeMessageParts(MemoryStream stm, Object[] args)
{
stm.Position = 0;
BinaryFormatter fmt = new BinaryFormatter();
fmt.CrossAppDomainArray = args;
fmt.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
return (ArrayList) fmt.Deserialize(stm, null, false/*checkSEcurity*/, true/*isCrossAppDomain*/, null);
} // DeserializeMessageParts
#endif
[System.Security.SecurityCritical] // auto-generated
internal static ArrayList DeserializeMessageParts(MemoryStream stm)
{
return (ArrayList) DeserializeObject(stm);
} // DeserializeMessageParts
[System.Security.SecurityCritical] // auto-generated
internal static Object DeserializeObject(MemoryStream stm)
{
stm.Position = 0;
BinaryFormatter fmt = new BinaryFormatter();
fmt.Context = new StreamingContext(StreamingContextStates.CrossAppDomain);
return fmt.Deserialize(stm, null, false /* No Security check */, true/*isCrossAppDomain*/, null);
} // DeserializeMessageParts
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Text.Formatting;
using Microsoft.VisualStudio.Text.Operations;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.InteractiveWindow
{
/// <summary>
/// Provides implementation of a Repl Window built on top of the VS editor using projection buffers.
/// </summary>
internal partial class InteractiveWindow
{
private readonly UIThreadOnly _dangerous_uiOnly;
#region Initialization
public InteractiveWindow(
IInteractiveWindowEditorFactoryService host,
IContentTypeRegistryService contentTypeRegistry,
ITextBufferFactoryService bufferFactory,
IProjectionBufferFactoryService projectionBufferFactory,
IEditorOperationsFactoryService editorOperationsFactory,
ITextEditorFactoryService editorFactory,
IRtfBuilderService rtfBuilderService,
IIntellisenseSessionStackMapService intellisenseSessionStackMap,
ISmartIndentationService smartIndenterService,
IInteractiveEvaluator evaluator)
{
if (evaluator == null)
{
throw new ArgumentNullException(nameof(evaluator));
}
_dangerous_uiOnly = new UIThreadOnly(this, host);
this.Properties = new PropertyCollection();
_history = new History();
_intellisenseSessionStackMap = intellisenseSessionStackMap;
_smartIndenterService = smartIndenterService;
var replContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveContentTypeName);
var replOutputContentType = contentTypeRegistry.GetContentType(PredefinedInteractiveContentTypes.InteractiveOutputContentTypeName);
_outputBuffer = bufferFactory.CreateTextBuffer(replOutputContentType);
_standardInputBuffer = bufferFactory.CreateTextBuffer();
_inertType = bufferFactory.InertContentType;
var projBuffer = projectionBufferFactory.CreateProjectionBuffer(
new EditResolver(this),
Array.Empty<object>(),
ProjectionBufferOptions.None,
replContentType);
projBuffer.Properties.AddProperty(typeof(InteractiveWindow), this);
_projectionBuffer = projBuffer;
_dangerous_uiOnly.AppendNewOutputProjectionBuffer(); // Constructor runs on UI thread.
projBuffer.Changed += new EventHandler<TextContentChangedEventArgs>(ProjectionBufferChanged);
var roleSet = editorFactory.CreateTextViewRoleSet(
PredefinedTextViewRoles.Analyzable,
PredefinedTextViewRoles.Editable,
PredefinedTextViewRoles.Interactive,
PredefinedTextViewRoles.Zoomable,
PredefinedInteractiveTextViewRoles.InteractiveTextViewRole);
_textView = host.CreateTextView(this, projBuffer, roleSet);
_textView.Caret.PositionChanged += CaretPositionChanged;
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.HorizontalScrollBarId, true);
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.LineNumberMarginId, false);
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.OutliningMarginId, false);
_textView.Options.SetOptionValue(DefaultTextViewHostOptions.GlyphMarginId, false);
_textView.Options.SetOptionValue(DefaultTextViewOptions.WordWrapStyleId, WordWrapStyles.None);
_lineBreakString = _textView.Options.GetNewLineCharacter();
_dangerous_uiOnly.EditorOperations = editorOperationsFactory.GetEditorOperations(_textView); // Constructor runs on UI thread.
_buffer = new OutputBuffer(this);
_outputWriter = new InteractiveWindowWriter(this, spans: null);
SortedSpans errorSpans = new SortedSpans();
_errorOutputWriter = new InteractiveWindowWriter(this, errorSpans);
OutputClassifierProvider.AttachToBuffer(_outputBuffer, errorSpans);
_rtfBuilderService = rtfBuilderService;
RequiresUIThread();
evaluator.CurrentWindow = this;
_evaluator = evaluator;
}
async Task<ExecutionResult> IInteractiveWindow.InitializeAsync()
{
try
{
RequiresUIThread();
var uiOnly = _dangerous_uiOnly; // Verified above.
if (uiOnly.State != State.Starting)
{
throw new InvalidOperationException(InteractiveWindowResources.AlreadyInitialized);
}
uiOnly.State = State.Initializing;
// Anything that reads options should wait until after this call so the evaluator can set the options first
ExecutionResult result = await _evaluator.InitializeAsync().ConfigureAwait(continueOnCapturedContext: true);
Debug.Assert(OnUIThread()); // ConfigureAwait should bring us back to the UI thread.
if (result.IsSuccessful)
{
uiOnly.PrepareForInput();
}
return result;
}
catch (Exception e) when (ReportAndPropagateException(e))
{
throw ExceptionUtilities.Unreachable;
}
}
#endregion
private sealed class UIThreadOnly
{
private readonly InteractiveWindow _window;
private readonly IInteractiveWindowEditorFactoryService _host;
private readonly IReadOnlyRegion[] _outputProtection;
// Pending submissions to be processed whenever the REPL is ready to accept submissions.
private readonly Queue<PendingSubmission> _pendingSubmissions;
private DispatcherTimer _executionTimer;
private Cursor _oldCursor;
private int _currentOutputProjectionSpan;
private int _outputTrackingCaretPosition;
// Read-only regions protecting initial span of the corresponding buffers:
public readonly IReadOnlyRegion[] StandardInputProtection;
public string UncommittedInput;
private IEditorOperations _editorOperations;
public IEditorOperations EditorOperations
{
get
{
return _editorOperations;
}
set
{
Debug.Assert(_editorOperations == null, "Assignment only happens once.");
Debug.Assert(value != null);
_editorOperations = value;
}
}
public State _state;
public State State
{
get
{
return _state;
}
set
{
_window.StateChanged?.Invoke(value);
_state = value;
}
}
public UIThreadOnly(InteractiveWindow window, IInteractiveWindowEditorFactoryService host)
{
_window = window;
_host = host;
StandardInputProtection = new IReadOnlyRegion[2];
_outputProtection = new IReadOnlyRegion[2];
_pendingSubmissions = new Queue<PendingSubmission>();
_outputTrackingCaretPosition = -1;
}
public async Task<ExecutionResult> ResetAsync(bool initialize)
{
try
{
Debug.Assert(State != State.Resetting, "The button should have been disabled.");
if (_window._stdInputStart != null)
{
CancelStandardInput();
}
_window._buffer.Flush();
if (State == State.WaitingForInput)
{
var snapshot = _window._projectionBuffer.CurrentSnapshot;
var spanCount = snapshot.SpanCount;
Debug.Assert(_window.GetSpanKind(snapshot.GetSourceSpan(spanCount - 1)) == ReplSpanKind.Language);
StoreUncommittedInput();
RemoveProjectionSpans(spanCount - 2, 2);
_window._currentLanguageBuffer = null;
}
State = State.Resetting;
var executionResult = await _window._evaluator.ResetAsync(initialize).ConfigureAwait(true);
Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread.
Debug.Assert(State == State.Resetting, $"Unexpected state {State}");
FinishExecute(executionResult.IsSuccessful);
return executionResult;
}
catch (Exception e) when (_window.ReportAndPropagateException(e))
{
throw ExceptionUtilities.Unreachable;
}
}
public void ClearView()
{
if (_window._stdInputStart != null)
{
CancelStandardInput();
}
_window._adornmentToMinimize = false;
InlineAdornmentProvider.RemoveAllAdornments(_window._textView);
// remove all the spans except our initial span from the projection buffer
UncommittedInput = null;
// Clear the projection and buffers last as this might trigger events that might access other state of the REPL window:
RemoveProtection(_window._outputBuffer, _outputProtection);
RemoveProtection(_window._standardInputBuffer, StandardInputProtection);
using (var edit = _window._outputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
edit.Delete(0, _window._outputBuffer.CurrentSnapshot.Length);
edit.Apply();
}
_window._buffer.Reset();
OutputClassifierProvider.ClearSpans(_window._outputBuffer);
_outputTrackingCaretPosition = 0;
using (var edit = _window._standardInputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
edit.Delete(0, _window._standardInputBuffer.CurrentSnapshot.Length);
edit.Apply();
}
RemoveProjectionSpans(0, _window._projectionBuffer.CurrentSnapshot.SpanCount);
// Insert an empty output buffer.
// We do it for two reasons:
// 1) When output is written to asynchronously we need a buffer to store it.
// This may happen when clearing screen while background thread is writing to the console.
// 2) We need at least one non-inert span due to bugs in projection buffer.
AppendNewOutputProjectionBuffer();
_window._history.ForgetOriginalBuffers();
// If we were waiting for input, we need to restore the prompt that we just cleared.
// If we are in any other state, then we'll let normal transitions trigger the next prompt.
if (State == State.WaitingForInput)
{
PrepareForInput();
}
}
private void CancelStandardInput()
{
_window.AppendLineNoPromptInjection(_window._standardInputBuffer);
_window._inputValue = null;
_window._inputEvent.Set();
}
public void InsertCode(string text)
{
if (_window._stdInputStart != null)
{
return;
}
if (State == State.ExecutingInput)
{
AppendUncommittedInput(text);
}
else
{
if (!_window._textView.Selection.IsEmpty)
{
_window.CutOrDeleteSelection(isCut: false);
}
EditorOperations.InsertText(text);
}
}
public void Submit(PendingSubmission[] pendingSubmissions)
{
if (_window._stdInputStart == null)
{
if (State == State.WaitingForInput && _window._currentLanguageBuffer != null)
{
StoreUncommittedInput();
PendSubmissions(pendingSubmissions);
ProcessPendingSubmissions();
}
else
{
PendSubmissions(pendingSubmissions);
}
}
}
private void StoreUncommittedInput()
{
if (UncommittedInput == null)
{
string activeCode = _window.GetActiveCode();
if (!string.IsNullOrEmpty(activeCode))
{
UncommittedInput = activeCode;
}
}
}
private void PendSubmissions(IEnumerable<PendingSubmission> inputs)
{
foreach (var input in inputs)
{
_pendingSubmissions.Enqueue(input);
}
}
public void AddInput(string command)
{
// If the language buffer is readonly then input can not be added. Return immediately.
// The language buffer gets marked as readonly in SubmitAsync method when input on the prompt
// gets submitted. So it would be readonly when the user types #reset on the prompt. In that
// case it is the right thing to bail out of this method.
if (_window._currentLanguageBuffer != null && _window._currentLanguageBuffer.IsReadOnly(0))
{
return;
}
if (State == State.ExecutingInput || _window._currentLanguageBuffer == null)
{
AddLanguageBuffer();
_window._currentLanguageBuffer.Insert(0, command);
}
else
{
StoreUncommittedInput();
_window.SetActiveCode(command);
}
// Add command to history before calling FinishCurrentSubmissionInput as it adds newline
// to the end of the command.
_window._history.Add(_window._currentLanguageBuffer.CurrentSnapshot.GetExtent());
FinishCurrentSubmissionInput();
}
private void AppendUncommittedInput(string text)
{
if (string.IsNullOrEmpty(text))
{
// Do nothing.
}
else if (string.IsNullOrEmpty(UncommittedInput))
{
UncommittedInput = text;
}
else
{
UncommittedInput += text;
}
}
private void RestoreUncommittedInput()
{
if (UncommittedInput != null)
{
_window.SetActiveCode(UncommittedInput);
UncommittedInput = null;
}
}
/// <summary>
/// Pastes from the clipboard into the text view
/// </summary>
public bool Paste()
{
_window.MoveCaretToClosestEditableBuffer();
string format = _window._evaluator.FormatClipboard();
if (format != null)
{
InsertCode(format);
}
else if (Clipboard.ContainsText())
{
InsertCode(Clipboard.GetText());
}
else
{
return false;
}
return true;
}
/// <summary>
/// Appends given text to the last input span (standard input or active code input).
/// </summary>
private void AppendInput(string text)
{
var snapshot = _window._projectionBuffer.CurrentSnapshot;
var spanCount = snapshot.SpanCount;
var inputSpan = snapshot.GetSourceSpan(spanCount - 1);
Debug.Assert(_window.GetSpanKind(inputSpan) == ReplSpanKind.Language ||
_window.GetSpanKind(inputSpan) == ReplSpanKind.StandardInput);
var buffer = inputSpan.Snapshot.TextBuffer;
var span = inputSpan.Span;
using (var edit = buffer.CreateEdit())
{
edit.Insert(edit.Snapshot.Length, text);
edit.Apply();
}
var replSpan = new CustomTrackingSpan(
buffer.CurrentSnapshot,
new Span(span.Start, span.Length + text.Length),
PointTrackingMode.Negative,
PointTrackingMode.Positive);
ReplaceProjectionSpan(spanCount - 1, replSpan);
_window.Caret.EnsureVisible();
}
public void PrepareForInput()
{
_window._buffer.Flush();
AddLanguageBuffer();
// we are prepared for processing any postponed submissions there might have been:
ProcessPendingSubmissions();
}
private void ProcessPendingSubmissions()
{
Debug.Assert(_window._currentLanguageBuffer != null);
if (_pendingSubmissions.Count == 0)
{
RestoreUncommittedInput();
// move to the end (it might have been in virtual space):
_window.Caret.MoveTo(GetLastLine(_window.TextBuffer.CurrentSnapshot).End);
_window.Caret.EnsureVisible();
State = State.WaitingForInput;
var ready = _window.ReadyForInput;
if (ready != null)
{
ready();
}
return;
}
var submission = _pendingSubmissions.Dequeue();
_window.SetActiveCode(submission.Input);
Debug.Assert(submission.Task == null, "Someone set PendingSubmission.Task before it was dequeued.");
submission.Task = SubmitAsync();
if (submission.Completion != null)
{
// ContinueWith is safe since TaskCompletionSource.SetResult should not throw.
// Therefore, we don't need to await the task (which we would normally do to
// propagate any exceptions it might throw). We also don't need an NFW
// exception filter around the continuation.
submission.Task.ContinueWith(_ => submission.Completion.SetResult(null), TaskScheduler.Current);
}
}
public async Task SubmitAsync()
{
try
{
RequiresLanguageBuffer();
// TODO: queue submission
// Ensure that the REPL doesn't try to execute if it is already
// executing. If this invariant can no longer be maintained more of
// the code in this method will need to be bullet-proofed
if (State == State.ExecutingInput)
{
return;
}
// get command to save to history before calling FinishCurrentSubmissionInput
// as it adds newline at the end
var historySpan = _window._currentLanguageBuffer.CurrentSnapshot.GetExtent();
FinishCurrentSubmissionInput();
_window._history.UncommittedInput = null;
var snapshotSpan = _window._currentLanguageBuffer.CurrentSnapshot.GetExtent();
var trimmedSpan = snapshotSpan.TrimEnd();
if (trimmedSpan.Length == 0)
{
// TODO: reuse the current language buffer
PrepareForInput();
return;
}
else
{
_window._history.Add(historySpan);
State = State.ExecutingInput;
StartCursorTimer();
var executionResult = await _window._evaluator.ExecuteCodeAsync(snapshotSpan.GetText()).ConfigureAwait(true);
Debug.Assert(_window.OnUIThread()); // ConfigureAwait should bring us back to the UI thread.
Debug.Assert(State == State.ExecutingInput || State == State.Resetting, $"Unexpected state {State}");
if (State == State.ExecutingInput)
{
FinishExecute(executionResult.IsSuccessful);
}
}
}
catch (Exception e) when (_window.ReportAndPropagateException(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private void RequiresLanguageBuffer()
{
if (_window._currentLanguageBuffer == null)
{
Environment.FailFast("Language buffer not available");
}
}
private void FinishCurrentSubmissionInput()
{
_window.AppendLineNoPromptInjection(_window._currentLanguageBuffer);
ApplyProtection(_window._currentLanguageBuffer, regions: null);
if (_window._adornmentToMinimize)
{
// TODO (tomat): remember the index of the adornment(s) in the current output and minimize those instead of the last one
InlineAdornmentProvider.MinimizeLastInlineAdornment(_window._textView);
_window._adornmentToMinimize = false;
}
NewOutputBuffer();
}
/// <summary>
/// Marks the entire buffer as read-only.
/// </summary>
public void ApplyProtection(ITextBuffer buffer, IReadOnlyRegion[] regions, bool allowAppend = false)
{
using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit())
{
int end = buffer.CurrentSnapshot.Length;
Span span = new Span(0, end);
var region0 = allowAppend ?
readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Allow) :
readonlyEdit.CreateReadOnlyRegion(span, SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny);
// Create a second read-only region to prevent insert at start of buffer.
var region1 = (end > 0) ? readonlyEdit.CreateReadOnlyRegion(new Span(0, 0), SpanTrackingMode.EdgeExclusive, EdgeInsertionMode.Deny) : null;
readonlyEdit.Apply();
if (regions != null)
{
regions[0] = region0;
regions[1] = region1;
}
}
}
/// <summary>
/// Removes read-only region from buffer.
/// </summary>
public void RemoveProtection(ITextBuffer buffer, IReadOnlyRegion[] regions)
{
if (regions[0] != null)
{
Debug.Assert(regions[1] != null);
foreach (var region in regions)
{
using (var readonlyEdit = buffer.CreateReadOnlyRegionEdit())
{
readonlyEdit.RemoveReadOnlyRegion(region);
readonlyEdit.Apply();
}
}
}
}
public void NewOutputBuffer()
{
// Stop growing the current output projection span.
var sourceSpan = _window._projectionBuffer.CurrentSnapshot.GetSourceSpan(_currentOutputProjectionSpan);
Debug.Assert(_window.GetSpanKind(sourceSpan) == ReplSpanKind.Output);
var nonGrowingSpan = new CustomTrackingSpan(
sourceSpan.Snapshot,
sourceSpan.Span,
PointTrackingMode.Negative,
PointTrackingMode.Negative);
ReplaceProjectionSpan(_currentOutputProjectionSpan, nonGrowingSpan);
AppendNewOutputProjectionBuffer();
_outputTrackingCaretPosition = _window._textView.Caret.Position.BufferPosition;
}
public void AppendNewOutputProjectionBuffer()
{
var currentSnapshot = _window._outputBuffer.CurrentSnapshot;
var trackingSpan = new CustomTrackingSpan(
currentSnapshot,
new Span(currentSnapshot.Length, 0),
PointTrackingMode.Negative,
PointTrackingMode.Positive);
_currentOutputProjectionSpan = AppendProjectionSpan(trackingSpan);
}
private int AppendProjectionSpan(ITrackingSpan span)
{
int index = _window._projectionBuffer.CurrentSnapshot.SpanCount;
InsertProjectionSpan(index, span);
return index;
}
private void InsertProjectionSpan(int index, object span)
{
_window._projectionBuffer.ReplaceSpans(index, 0, new[] { span }, EditOptions.None, editTag: s_suppressPromptInjectionTag);
}
public void ReplaceProjectionSpan(int spanToReplace, ITrackingSpan newSpan)
{
_window._projectionBuffer.ReplaceSpans(spanToReplace, 1, new[] { newSpan }, EditOptions.None, editTag: s_suppressPromptInjectionTag);
}
private void RemoveProjectionSpans(int index, int count)
{
_window._projectionBuffer.ReplaceSpans(index, count, Array.Empty<object>(), EditOptions.None, s_suppressPromptInjectionTag);
}
/// <summary>
/// Appends text to the output buffer and updates projection buffer to include it.
/// WARNING: this has to be the only method that writes to the output buffer so that
/// the output buffering counters are kept in sync.
/// </summary>
internal void AppendOutput(IEnumerable<string> output)
{
Debug.Assert(output.Any());
// we maintain this invariant so that projections don't split "\r\n" in half:
Debug.Assert(!_window._outputBuffer.CurrentSnapshot.EndsWith('\r'));
var projectionSpans = _window._projectionBuffer.CurrentSnapshot.GetSourceSpans();
Debug.Assert(_window.GetSpanKind(projectionSpans[_currentOutputProjectionSpan]) == ReplSpanKind.Output);
int lineBreakProjectionSpanIndex = _currentOutputProjectionSpan + 1;
// insert line break projection span if there is none and the output doesn't end with a line break:
bool hasLineBreakProjection = false;
if (lineBreakProjectionSpanIndex < projectionSpans.Count)
{
var oldSpan = projectionSpans[lineBreakProjectionSpanIndex];
hasLineBreakProjection = _window.GetSpanKind(oldSpan) == ReplSpanKind.LineBreak;
}
Debug.Assert(output.Last().Last() != '\r');
bool endsWithLineBreak = output.Last().Last() == '\n';
// insert text to the subject buffer.
int oldBufferLength = _window._outputBuffer.CurrentSnapshot.Length;
InsertOutput(output, oldBufferLength);
if (endsWithLineBreak && hasLineBreakProjection)
{
// Remove line break.
RemoveProjectionSpans(lineBreakProjectionSpanIndex, 1);
}
else if (!endsWithLineBreak && !hasLineBreakProjection)
{
// Insert line break.
InsertProjectionSpan(lineBreakProjectionSpanIndex, _window._lineBreakString);
}
// caret didn't move since last time we moved it to track output:
if (_outputTrackingCaretPosition == _window._textView.Caret.Position.BufferPosition)
{
_window._textView.Caret.EnsureVisible();
_outputTrackingCaretPosition = _window._textView.Caret.Position.BufferPosition;
}
}
private void InsertOutput(IEnumerable<string> output, int position)
{
RemoveProtection(_window._outputBuffer, _outputProtection);
// append the text to output buffer and make sure it ends with a line break:
using (var edit = _window._outputBuffer.CreateEdit(EditOptions.None, null, s_suppressPromptInjectionTag))
{
foreach (string text in output)
{
edit.Insert(position, text);
}
edit.Apply();
}
ApplyProtection(_window._outputBuffer, _outputProtection);
}
private void FinishExecute(bool succeeded)
{
ResetCursor();
if (!succeeded && _window._history.Last != null)
{
_window._history.Last.Failed = true;
}
PrepareForInput();
}
public async Task ExecuteInputAsync()
{
try
{
ITextBuffer languageBuffer = GetLanguageBuffer(_window.Caret.Position.BufferPosition);
if (languageBuffer == null)
{
return;
}
if (languageBuffer == _window._currentLanguageBuffer)
{
// TODO (tomat): this should rather send an abstract "finish" command that various features
// can implement as needed (IntelliSense, inline rename would commit, etc.).
// For now, commit IntelliSense:
var completionSession = _window.SessionStack.TopSession as ICompletionSession;
if (completionSession != null)
{
completionSession.Commit();
}
await SubmitAsync().ConfigureAwait(true);
}
else
{
// append text of the target buffer to the current language buffer:
string text = TrimTrailingEmptyLines(languageBuffer.CurrentSnapshot);
_window._currentLanguageBuffer.Replace(new Span(_window._currentLanguageBuffer.CurrentSnapshot.Length, 0), text);
EditorOperations.MoveToEndOfDocument(false);
}
}
catch (Exception e) when (_window.ReportAndPropagateException(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private static string TrimTrailingEmptyLines(ITextSnapshot snapshot)
{
var line = GetLastLine(snapshot);
while (line != null && line.Length == 0)
{
line = GetPreviousLine(line);
}
if (line == null)
{
return string.Empty;
}
return line.Snapshot.GetText(0, line.Extent.End.Position);
}
private static ITextSnapshotLine GetPreviousLine(ITextSnapshotLine line)
{
return line.LineNumber > 0 ? line.Snapshot.GetLineFromLineNumber(line.LineNumber - 1) : null;
}
/// <summary>
/// Returns the language or command text buffer that the specified point belongs to.
/// If the point lays in a prompt returns the buffer corresponding to the prompt.
/// </summary>
/// <returns>The language or command buffer or null if the point doesn't belong to any.</returns>
private ITextBuffer GetLanguageBuffer(SnapshotPoint point)
{
var sourceSpans = GetSourceSpans(point.Snapshot);
int promptIndex = _window.GetPromptIndexForPoint(sourceSpans, point);
if (promptIndex < 0)
{
return null;
}
// Grab the span following the prompt (either language or standard input).
var projectionSpan = sourceSpans[promptIndex + 1];
var kind = _window.GetSpanKind(projectionSpan);
if (kind != ReplSpanKind.Language)
{
Debug.Assert(kind == ReplSpanKind.StandardInput);
return null;
}
var inputSnapshot = projectionSpan.Snapshot;
var inputBuffer = inputSnapshot.TextBuffer;
var projectedSpans = _window._textView.BufferGraph.MapUpToBuffer(
new SnapshotSpan(inputSnapshot, 0, inputSnapshot.Length),
SpanTrackingMode.EdgePositive,
_window._projectionBuffer);
Debug.Assert(projectedSpans.Count > 0);
var projectedSpansStart = projectedSpans.First().Start;
var projectedSpansEnd = projectedSpans.Last().End;
if (point < projectedSpansStart.GetContainingLine().Start)
{
return null;
}
// If the buffer is the current buffer, the cursor might be in a virtual space behind the buffer
// but logically it belongs to the current submission. Since the current language buffer is the last buffer in the
// projection we don't need to check for its end.
if (inputBuffer == _window._currentLanguageBuffer)
{
return inputBuffer;
}
// if the point is at the end of the buffer it might be on the next line that doesn't logically belong to the input region:
if (point > projectedSpansEnd || (point == projectedSpansEnd && projectedSpansEnd.GetContainingLine().LineBreakLength != 0))
{
return null;
}
return inputBuffer;
}
public void ResetCursor()
{
if (_executionTimer != null)
{
_executionTimer.Stop();
}
if (_oldCursor != null)
{
((ContentControl)_window._textView).Cursor = _oldCursor;
}
_oldCursor = null;
_executionTimer = null;
}
private void StartCursorTimer()
{
var timer = new DispatcherTimer();
timer.Tick += SetRunningCursor;
timer.Interval = TimeSpan.FromMilliseconds(250);
_executionTimer = timer;
timer.Start();
}
private void SetRunningCursor(object sender, EventArgs e)
{
var view = (ContentControl)_window._textView;
// Save the old value of the cursor so it can be restored
// after execution has finished
_oldCursor = view.Cursor;
// TODO: Design work to come up with the correct cursor to use
// Set the repl's cursor to the "executing" cursor
view.Cursor = Cursors.Wait;
// Stop the timer so it doesn't fire again
if (_executionTimer != null)
{
_executionTimer.Stop();
}
}
public int IndexOfLastStandardInputSpan(ReadOnlyCollection<SnapshotSpan> sourceSpans)
{
for (int i = sourceSpans.Count - 1; i >= 0; i--)
{
if (_window.GetSpanKind(sourceSpans[i]) == ReplSpanKind.StandardInput)
{
return i;
}
}
return -1;
}
public void RemoveLastInputPrompt()
{
var snapshot = _window._projectionBuffer.CurrentSnapshot;
var spanCount = snapshot.SpanCount;
Debug.Assert(_window.IsPrompt(snapshot.GetSourceSpan(spanCount - SpansPerLineOfInput)));
// projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping:
RemoveProjectionSpans(spanCount - SpansPerLineOfInput, SpansPerLineOfInput);
}
/// <summary>
/// Creates and adds a new language buffer to the projection buffer.
/// </summary>
private void AddLanguageBuffer()
{
ITextBuffer buffer = _host.CreateAndActivateBuffer(_window);
buffer.Properties.AddProperty(typeof(IInteractiveEvaluator), _window._evaluator);
buffer.Properties.AddProperty(typeof(InteractiveWindow), _window);
_window._currentLanguageBuffer = buffer;
var bufferAdded = _window.SubmissionBufferAdded;
if (bufferAdded != null)
{
bufferAdded(_window, new SubmissionBufferAddedEventArgs(buffer));
}
// add the whole buffer to the projection buffer and set it up to expand to the right as text is appended
var promptSpan = _window.CreatePrimaryPrompt();
var languageSpan = new CustomTrackingSpan(
_window._currentLanguageBuffer.CurrentSnapshot,
new Span(0, 0),
PointTrackingMode.Negative,
PointTrackingMode.Positive);
// projection buffer update must be the last operation as it might trigger event that accesses prompt line mapping:
_window.AppendProjectionSpans(promptSpan, languageSpan);
}
public void ScrollToCaret()
{
var textView = _window._textView;
var caretPosition = textView.Caret.Position.BufferPosition;
var caretSpan = new SnapshotSpan(caretPosition.Snapshot, caretPosition, 0);
textView.ViewScroller.EnsureSpanVisible(caretSpan);
}
}
internal enum State
{
/// <summary>
/// Initial state. <see cref="IInteractiveWindow.InitializeAsync"/> hasn't been called.
/// Transition to <see cref="Initializing"/> when <see cref="IInteractiveWindow.InitializeAsync"/> is called.
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
Starting,
/// <summary>
/// In the process of calling <see cref="IInteractiveWindow.InitializeAsync"/>.
/// Transition to <see cref="WaitingForInput"/> when finished (in <see cref="UIThreadOnly.ProcessPendingSubmissions"/>).
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
Initializing,
/// <summary>
/// In the process of calling <see cref="IInteractiveWindowOperations.ResetAsync"/>.
/// Transition to <see cref="WaitingForInput"/> when finished (in <see cref="UIThreadOnly.ProcessPendingSubmissions"/>).
/// Note: Should not see <see cref="IInteractiveWindowOperations.ResetAsync"/> calls while in this state.
/// </summary>
Resetting,
/// <summary>
/// Prompt has been displayed - waiting for the user to make the next submission.
/// Transition to <see cref="ExecutingInput"/> when <see cref="IInteractiveWindowOperations.ExecuteInput"/> is called.
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
WaitingForInput,
/// <summary>
/// Executing the user's submission.
/// Transition to <see cref="WaitingForInput"/> when finished (in <see cref="UIThreadOnly.ProcessPendingSubmissions"/>).
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
ExecutingInput,
/// <summary>
/// In the process of calling <see cref="IInteractiveWindow.ReadStandardInput"/>.
/// Return to preceding state when finished.
/// Transition to <see cref="Resetting"/> when <see cref="IInteractiveWindowOperations.ResetAsync"/> is called.
/// </summary>
/// <remarks>
/// TODO: When we clean up <see cref="IInteractiveWindow.ReadStandardInput"/> (https://github.com/dotnet/roslyn/issues/3984)
/// we should try to eliminate the "preceding state", since it substantially
/// increases the complexity of the state machine.
/// </remarks>
ReadingStandardInput,
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed partial class IncrementalAnalyzerProcessor
{
private sealed class LowPriorityProcessor : AbstractPriorityProcessor
{
private readonly AsyncProjectWorkItemQueue _workItemQueue;
public LowPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
IGlobalOperationNotificationService globalOperationNotificationService,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, processor, lazyAnalyzers, globalOperationNotificationService, backOffTimeSpanInMs, shutdownToken)
{
_workItemQueue = new AsyncProjectWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
Start();
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _workItemQueue.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
try
{
// we wait for global operation, higher and normal priority processor to finish its working
await WaitForHigherPriorityOperationsAsync().ConfigureAwait(false);
// process any available project work, preferring the active project.
if (_workItemQueue.TryTakeAnyWork(
this.Processor.GetActiveProject(), this.Processor.DependencyGraph, this.Processor.DiagnosticAnalyzerService,
out var workItem, out var projectCancellation))
{
await ProcessProjectAsync(this.Analyzers, workItem, projectCancellation).ConfigureAwait(false);
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
protected override Task HigherQueueOperationTask
{
get
{
return Task.WhenAll(this.Processor._highPriorityProcessor.Running, this.Processor._normalPriorityProcessor.Running);
}
}
protected override bool HigherQueueHasWorkItem
{
get
{
return this.Processor._highPriorityProcessor.HasAnyWork || this.Processor._normalPriorityProcessor.HasAnyWork;
}
}
protected override void PauseOnGlobalOperation()
{
base.PauseOnGlobalOperation();
_workItemQueue.RequestCancellationOnRunningTasks();
}
public void Enqueue(WorkItem item)
{
this.UpdateLastAccessTime();
// Project work
item = item.With(documentId: null, projectId: item.ProjectId, asyncToken: this.Processor._listener.BeginAsyncOperation("WorkItem"));
var added = _workItemQueue.AddOrReplace(item);
// lower priority queue gets lowest time slot possible. if there is any activity going on in higher queue, it drop whatever it has
// and let higher work item run
CancelRunningTaskIfHigherQueueHasWorkItem();
Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, item.ProjectId, !added);
SolutionCrawlerLogger.LogWorkItemEnqueue(this.Processor._logAggregator, item.ProjectId);
}
private void CancelRunningTaskIfHigherQueueHasWorkItem()
{
if (!HigherQueueHasWorkItem)
{
return;
}
_workItemQueue.RequestCancellationOnRunningTasks();
}
private async Task ProcessProjectAsync(ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
// we do have work item for this project
var projectId = workItem.ProjectId;
var processedEverything = false;
var processingSolution = this.Processor.CurrentSolution;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessProjectAsync, source.Token))
{
var cancellationToken = source.Token;
var project = processingSolution.GetProject(projectId);
if (project != null)
{
var reasons = workItem.InvocationReasons;
var semanticsChanged = reasons.Contains(PredefinedInvocationReasons.SemanticChanged) ||
reasons.Contains(PredefinedInvocationReasons.SolutionRemoved);
using (Processor.EnableCaching(project.Id))
{
await RunAnalyzersAsync(analyzers, project, (a, p, c) => a.AnalyzeProjectAsync(p, semanticsChanged, reasons, c), cancellationToken).ConfigureAwait(false);
}
}
else
{
SolutionCrawlerLogger.LogProcessProjectNotExist(this.Processor._logAggregator);
RemoveProject(projectId);
}
if (!cancellationToken.IsCancellationRequested)
{
processedEverything = true;
}
}
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// we got cancelled in the middle of processing the project.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessProject(this.Processor._logAggregator, projectId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(projectId);
}
}
private void RemoveProject(ProjectId projectId)
{
foreach (var analyzer in this.Analyzers)
{
analyzer.RemoveProject(projectId);
}
}
public override void Shutdown()
{
base.Shutdown();
_workItemQueue.Dispose();
}
internal void WaitUntilCompletion_ForTestingPurposesOnly(ImmutableArray<IIncrementalAnalyzer> analyzers, List<WorkItem> items)
{
CancellationTokenSource source = new CancellationTokenSource();
var uniqueIds = new HashSet<ProjectId>();
foreach (var item in items)
{
if (uniqueIds.Add(item.ProjectId))
{
ProcessProjectAsync(analyzers, item, source).Wait();
}
}
}
internal void WaitUntilCompletion_ForTestingPurposesOnly()
{
// this shouldn't happen. would like to get some diagnostic
while (_workItemQueue.HasAnyWork)
{
Environment.FailFast("How?");
}
}
}
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CategoryAttribute.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
*/
namespace System.ComponentModel {
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Security.Permissions;
/// <devdoc>
/// <para>Specifies the category in which the property or event will be displayed in a
/// visual designer.</para>
/// </devdoc>
[AttributeUsage(AttributeTargets.All)]
public class CategoryAttribute : Attribute {
private static volatile CategoryAttribute appearance;
private static volatile CategoryAttribute asynchronous;
private static volatile CategoryAttribute behavior;
private static volatile CategoryAttribute data;
private static volatile CategoryAttribute design;
private static volatile CategoryAttribute action;
private static volatile CategoryAttribute format;
private static volatile CategoryAttribute layout;
private static volatile CategoryAttribute mouse;
private static volatile CategoryAttribute key;
private static volatile CategoryAttribute focus;
private static volatile CategoryAttribute windowStyle;
private static volatile CategoryAttribute dragDrop;
private static volatile CategoryAttribute defAttr;
private bool localized;
/// <devdoc>
/// <para>
/// Provides the actual category name.
/// </para>
/// </devdoc>
private string categoryValue;
/// <devdoc>
/// <para>Gets the action category attribute.</para>
/// </devdoc>
public static CategoryAttribute Action {
get {
if (action == null) {
action = new CategoryAttribute("Action");
}
return action;
}
}
/// <devdoc>
/// <para>Gets the appearance category attribute.</para>
/// </devdoc>
public static CategoryAttribute Appearance {
get {
if (appearance == null) {
appearance = new CategoryAttribute("Appearance");
}
return appearance;
}
}
/// <devdoc>
/// <para>Gets the asynchronous category attribute.</para>
/// </devdoc>
public static CategoryAttribute Asynchronous {
get {
if (asynchronous == null) {
asynchronous = new CategoryAttribute("Asynchronous");
}
return asynchronous;
}
}
/// <devdoc>
/// <para>Gets the behavior category attribute.</para>
/// </devdoc>
public static CategoryAttribute Behavior {
get {
if (behavior == null) {
behavior = new CategoryAttribute("Behavior");
}
return behavior;
}
}
/// <devdoc>
/// <para>Gets the data category attribute.</para>
/// </devdoc>
public static CategoryAttribute Data {
get {
if (data == null) {
data = new CategoryAttribute("Data");
}
return data;
}
}
/// <devdoc>
/// <para>Gets the default category attribute.</para>
/// </devdoc>
public static CategoryAttribute Default {
get {
if (defAttr == null) {
defAttr = new CategoryAttribute();
}
return defAttr;
}
}
/// <devdoc>
/// <para>Gets the design category attribute.</para>
/// </devdoc>
public static CategoryAttribute Design {
get {
if (design == null) {
design = new CategoryAttribute("Design");
}
return design;
}
}
/// <devdoc>
/// <para>Gets the drag and drop category attribute.</para>
/// </devdoc>
public static CategoryAttribute DragDrop {
get {
if (dragDrop == null) {
dragDrop = new CategoryAttribute("DragDrop");
}
return dragDrop;
}
}
/// <devdoc>
/// <para>Gets the focus category attribute.</para>
/// </devdoc>
public static CategoryAttribute Focus {
get {
if (focus == null) {
focus = new CategoryAttribute("Focus");
}
return focus;
}
}
/// <devdoc>
/// <para>Gets the format category attribute.</para>
/// </devdoc>
public static CategoryAttribute Format {
get {
if (format == null) {
format = new CategoryAttribute("Format");
}
return format;
}
}
/// <devdoc>
/// <para>Gets the keyboard category attribute.</para>
/// </devdoc>
public static CategoryAttribute Key {
get {
if (key == null) {
key = new CategoryAttribute("Key");
}
return key;
}
}
/// <devdoc>
/// <para>Gets the layout category attribute.</para>
/// </devdoc>
public static CategoryAttribute Layout {
get {
if (layout == null) {
layout = new CategoryAttribute("Layout");
}
return layout;
}
}
/// <devdoc>
/// <para>Gets the mouse category attribute.</para>
/// </devdoc>
public static CategoryAttribute Mouse {
get {
if (mouse == null) {
mouse = new CategoryAttribute("Mouse");
}
return mouse;
}
}
/// <devdoc>
/// <para> Gets the window style category
/// attribute.</para>
/// </devdoc>
public static CategoryAttribute WindowStyle {
get {
if (windowStyle == null) {
windowStyle = new CategoryAttribute("WindowStyle");
}
return windowStyle;
}
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/>
/// class with the default category.</para>
/// </devdoc>
public CategoryAttribute() : this("Default") {
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.CategoryAttribute'/> class with
/// the specified category name.</para>
/// </devdoc>
public CategoryAttribute(string category) {
this.categoryValue = category;
this.localized = false;
}
/// <devdoc>
/// <para>Gets the name of the category for the property or event
/// that this attribute is bound to.</para>
/// </devdoc>
public string Category {
get {
if (!localized) {
localized = true;
string localizedValue = GetLocalizedString(categoryValue);
if (localizedValue != null) {
categoryValue = localizedValue;
}
}
return categoryValue;
}
}
/// <devdoc>
/// </devdoc>
/// <devdoc>
/// </devdoc>
/// <internalonly/>
/// <internalonly/>
public override bool Equals(object obj){
if (obj == this) {
return true;
}
if (obj is CategoryAttribute){
return Category.Equals(((CategoryAttribute)obj).Category);
}
return false;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode() {
return Category.GetHashCode();
}
/// <devdoc>
/// <para>Looks up the localized name of a given category.</para>
/// </devdoc>
protected virtual string GetLocalizedString(string value) {
#if !SILVERLIGHT
#if MONO
switch (value) {
case "Action":
return SR.PropertyCategoryAction;
case "Appearance":
return SR.PropertyCategoryAppearance;
case "Behavior":
return SR.PropertyCategoryBehavior;
case "Data":
return SR.PropertyCategoryData;
case "DDE":
return SR.PropertyCategoryDDE;
case "Design":
return SR.PropertyCategoryDesign;
case "Focus":
return SR.PropertyCategoryFocus;
case "Font":
return SR.PropertyCategoryFont;
case "Key":
return SR.PropertyCategoryKey;
case "List":
return SR.PropertyCategoryList;
case "Layout":
return SR.PropertyCategoryLayout;
case "Mouse":
return SR.PropertyCategoryMouse;
case "Position":
return SR.PropertyCategoryPosition;
case "Text":
return SR.PropertyCategoryText;
case "Scale":
return SR.PropertyCategoryScale;
case "Config":
return SR.PropertyCategoryConfig;
#if !MOBILE
case "Default":
return SR.PropertyCategoryDefault;
case "DragDrop":
return SR.PropertyCategoryDragDrop;
case "WindowStyle":
return SR.PropertyCategoryWindowStyle;
#endif
}
return value;
#else
return (string)SR.GetObject("PropertyCategory" + value);
#endif
#else
bool usedFallback;
string localizedString = SR.GetString("PropertyCategory" + value, out usedFallback);
if (usedFallback) {
return null;
}
return localizedString;
#endif
}
#if !SILVERLIGHT
/// <devdoc>
/// </devdoc>
/// <devdoc>
/// </devdoc>
/// <internalonly/>
/// <internalonly/>
public override bool IsDefaultAttribute() {
return Category.Equals(Default.Category);
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
namespace ServiceStack.Text
{
public static class StreamExtensions
{
public static void WriteTo(this Stream inStream, Stream outStream)
{
var memoryStream = inStream as MemoryStream;
if (memoryStream != null)
{
memoryStream.WriteTo(outStream);
return;
}
var data = new byte[4096];
int bytesRead;
while ((bytesRead = inStream.Read(data, 0, data.Length)) > 0)
{
outStream.Write(data, 0, bytesRead);
}
}
public static IEnumerable<string> ReadLines(this StreamReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
string line;
while ((line = reader.ReadLine()) != null)
{
yield return line;
}
}
/// <summary>
/// @jonskeet: Collection of utility methods which operate on streams.
/// r285, February 26th 2009: http://www.yoda.arachsys.com/csharp/miscutil/
/// </summary>
const int DefaultBufferSize = 8 * 1024;
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array.
/// </summary>
public static byte[] ReadFully(this Stream input)
{
return ReadFully(input, DefaultBufferSize);
}
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array, using the given buffer size.
/// </summary>
public static byte[] ReadFully(this Stream input, int bufferSize)
{
if (bufferSize < 1)
{
throw new ArgumentOutOfRangeException("bufferSize");
}
return ReadFully(input, new byte[bufferSize]);
}
/// <summary>
/// Reads the given stream up to the end, returning the data as a byte
/// array, using the given buffer for transferring data. Note that the
/// current contents of the buffer is ignored, so the buffer needn't
/// be cleared beforehand.
/// </summary>
public static byte[] ReadFully(this Stream input, byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (input == null)
{
throw new ArgumentNullException("input");
}
if (buffer.Length == 0)
{
throw new ArgumentException("Buffer has length of 0");
}
// We could do all our own work here, but using MemoryStream is easier
// and likely to be just as efficient.
using (var tempStream = new MemoryStream())
{
CopyTo(input, tempStream, buffer);
// No need to copy the buffer if it's the right size
#if !NETFX_CORE
if (tempStream.Length == tempStream.GetBuffer().Length)
{
return tempStream.GetBuffer();
}
#endif
// Okay, make a copy that's the right size
return tempStream.ToArray();
}
}
/// <summary>
/// Copies all the data from one stream into another.
/// </summary>
public static void CopyTo(this Stream input, Stream output)
{
CopyTo(input, output, DefaultBufferSize);
}
/// <summary>
/// Copies all the data from one stream into another, using a buffer
/// of the given size.
/// </summary>
public static void CopyTo(this Stream input, Stream output, int bufferSize)
{
if (bufferSize < 1)
{
throw new ArgumentOutOfRangeException("bufferSize");
}
CopyTo(input, output, new byte[bufferSize]);
}
/// <summary>
/// Copies all the data from one stream into another, using the given
/// buffer for transferring data. Note that the current contents of
/// the buffer is ignored, so the buffer needn't be cleared beforehand.
/// </summary>
public static void CopyTo(this Stream input, Stream output, byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (input == null)
{
throw new ArgumentNullException("input");
}
if (output == null)
{
throw new ArgumentNullException("output");
}
if (buffer.Length == 0)
{
throw new ArgumentException("Buffer has length of 0");
}
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, read);
}
}
/// <summary>
/// Reads exactly the given number of bytes from the specified stream.
/// If the end of the stream is reached before the specified amount
/// of data is read, an exception is thrown.
/// </summary>
public static byte[] ReadExactly(this Stream input, int bytesToRead)
{
return ReadExactly(input, new byte[bytesToRead]);
}
/// <summary>
/// Reads into a buffer, filling it completely.
/// </summary>
public static byte[] ReadExactly(this Stream input, byte[] buffer)
{
return ReadExactly(input, buffer, buffer.Length);
}
/// <summary>
/// Reads exactly the given number of bytes from the specified stream,
/// into the given buffer, starting at position 0 of the array.
/// </summary>
public static byte[] ReadExactly(this Stream input, byte[] buffer, int bytesToRead)
{
return ReadExactly(input, buffer, 0, bytesToRead);
}
/// <summary>
/// Reads exactly the given number of bytes from the specified stream,
/// into the given buffer, starting at position 0 of the array.
/// </summary>
public static byte[] ReadExactly(this Stream input, byte[] buffer, int startIndex, int bytesToRead)
{
if (input == null)
{
throw new ArgumentNullException("input");
}
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (startIndex < 0 || startIndex >= buffer.Length)
{
throw new ArgumentOutOfRangeException("startIndex");
}
if (bytesToRead < 1 || startIndex + bytesToRead > buffer.Length)
{
throw new ArgumentOutOfRangeException("bytesToRead");
}
return ReadExactlyFast(input, buffer, startIndex, bytesToRead);
}
/// <summary>
/// Same as ReadExactly, but without the argument checks.
/// </summary>
private static byte[] ReadExactlyFast(Stream fromStream, byte[] intoBuffer, int startAtIndex, int bytesToRead)
{
var index = 0;
while (index < bytesToRead)
{
var read = fromStream.Read(intoBuffer, startAtIndex + index, bytesToRead - index);
if (read == 0)
{
throw new EndOfStreamException
(String.Format("End of stream reached with {0} byte{1} left to read.",
bytesToRead - index,
bytesToRead - index == 1 ? "s" : ""));
}
index += read;
}
return intoBuffer;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Pathoschild.Stardew.Common;
using Pathoschild.Stardew.Common.DataParsers;
using Pathoschild.Stardew.Common.Items.ItemData;
using Pathoschild.Stardew.LookupAnything.Framework.Constants;
using Pathoschild.Stardew.LookupAnything.Framework.Data;
using Pathoschild.Stardew.LookupAnything.Framework.DebugFields;
using Pathoschild.Stardew.LookupAnything.Framework.Fields;
using Pathoschild.Stardew.LookupAnything.Framework.Models;
using StardewModdingAPI.Utilities;
using StardewValley;
using StardewValley.Buildings;
using StardewValley.GameData.FishPond;
using StardewValley.GameData.Movies;
using StardewValley.Locations;
using StardewValley.Objects;
using StardewValley.TerrainFeatures;
using SObject = StardewValley.Object;
namespace Pathoschild.Stardew.LookupAnything.Framework.Lookups.Items
{
/// <summary>Describes a Stardew Valley item.</summary>
internal class ItemSubject : BaseSubject
{
/*********
** Fields
*********/
/// <summary>The lookup target.</summary>
private readonly Item Target;
/// <summary>The menu item to render, which may be different from the item that was looked up (e.g. for fences).</summary>
private readonly Item DisplayItem;
/// <summary>The crop which will drop the item (if applicable).</summary>
private readonly Crop FromCrop;
/// <summary>The dirt containing the crop (if applicable).</summary>
private readonly HoeDirt FromDirt;
/// <summary>The crop grown by this seed item (if applicable).</summary>
private readonly Crop SeedForCrop;
/// <summary>The context of the object being looked up.</summary>
private readonly ObjectContext Context;
/// <summary>Whether the item quality is known. This is <c>true</c> for an inventory item, <c>false</c> for a map object.</summary>
private readonly bool KnownQuality;
/// <summary>The location containing the item, if applicable.</summary>
private readonly GameLocation Location;
/// <summary>Whether to only show content once the player discovers it.</summary>
private readonly bool ProgressionMode;
/// <summary>Whether to highlight item gift tastes which haven't been revealed in the NPC profile.</summary>
private readonly bool HighlightUnrevealedGiftTastes;
/// <summary>Whether to show all NPC gift tastes.</summary>
private readonly bool ShowAllGiftTastes;
/// <summary>Provides subject entries.</summary>
private readonly ISubjectRegistry Codex;
/// <summary>Get a lookup subject for a crop.</summary>
private readonly Func<Crop, ObjectContext, HoeDirt, ISubject> GetCropSubject;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="codex">Provides subject entries</param>
/// <param name="gameHelper">Provides utility methods for interacting with the game code.</param>
/// <param name="progressionMode">Whether to only show content once the player discovers it.</param>
/// <param name="highlightUnrevealedGiftTastes">Whether to highlight item gift tastes which haven't been revealed in the NPC profile.</param>
/// <param name="showAllGiftTastes">Whether to show all NPC gift tastes.</param>
/// <param name="item">The underlying target.</param>
/// <param name="context">The context of the object being looked up.</param>
/// <param name="knownQuality">Whether the item quality is known. This is <c>true</c> for an inventory item, <c>false</c> for a map object.</param>
/// <param name="location">The location containing the item, if applicable.</param>
/// <param name="getCropSubject">Get a lookup subject for a crop.</param>
/// <param name="fromCrop">The crop associated with the item (if applicable).</param>
/// <param name="fromDirt">The dirt containing the crop (if applicable).</param>
public ItemSubject(ISubjectRegistry codex, GameHelper gameHelper, bool progressionMode, bool highlightUnrevealedGiftTastes, bool showAllGiftTastes, Item item, ObjectContext context, bool knownQuality, GameLocation location, Func<Crop, ObjectContext, HoeDirt, ISubject> getCropSubject, Crop fromCrop = null, HoeDirt fromDirt = null)
: base(gameHelper)
{
this.Codex = codex;
this.ProgressionMode = progressionMode;
this.HighlightUnrevealedGiftTastes = highlightUnrevealedGiftTastes;
this.ShowAllGiftTastes = showAllGiftTastes;
this.Target = item;
this.DisplayItem = this.GetMenuItem(item);
this.FromCrop = fromCrop ?? fromDirt?.crop;
this.FromDirt = fromDirt;
this.Context = context;
this.Location = location;
this.KnownQuality = knownQuality;
this.GetCropSubject = getCropSubject;
this.SeedForCrop = item.ParentSheetIndex != 433 || this.FromCrop == null // ignore unplanted coffee beans (to avoid "see also: coffee beans" loop)
? this.TryGetCropForSeed(item)
: null;
this.Initialize(this.DisplayItem.DisplayName, this.GetDescription(this.DisplayItem), this.GetTypeValue(this.DisplayItem));
}
/// <summary>Get the data to display for this subject.</summary>
public override IEnumerable<ICustomField> GetData()
{
// get data
Item item = this.Target;
SObject obj = item as SObject;
bool isCrop = this.FromCrop != null;
bool isSeed = this.SeedForCrop != null;
bool isDeadCrop = this.FromCrop?.dead.Value == true;
bool canSell = obj?.canBeShipped() == true || this.Metadata.Shops.Any(shop => shop.BuysCategories.Contains(item.Category));
bool isMovieTicket = obj?.ParentSheetIndex == 809 && !obj.bigCraftable.Value;
// get overrides
bool showInventoryFields = !this.IsSpawnedStoneNode();
{
ObjectData objData = this.Metadata.GetObject(item, this.Context);
if (objData != null)
{
this.Name = objData.NameKey != null ? I18n.GetByKey(objData.NameKey) : this.Name;
this.Description = objData.DescriptionKey != null ? I18n.GetByKey(objData.DescriptionKey) : this.Description;
this.Type = objData.TypeKey != null ? I18n.GetByKey(objData.TypeKey) : this.Type;
showInventoryFields = objData.ShowInventoryFields ?? showInventoryFields;
}
}
// don't show data for dead crop
if (isDeadCrop)
{
yield return new GenericField(I18n.Crop_Summary(), I18n.Crop_Summary_Dead());
yield break;
}
// crop fields
foreach (ICustomField field in this.GetCropFields(this.FromDirt, this.FromCrop ?? this.SeedForCrop, isSeed))
yield return field;
// indoor pot crop
if (obj is IndoorPot pot)
{
Crop potCrop = pot.hoeDirt.Value.crop;
Bush potBush = pot.bush.Value;
if (potCrop != null)
{
Item drop = this.GameHelper.GetObjectBySpriteIndex(potCrop.indexOfHarvest.Value);
yield return new LinkField(I18n.Item_Contents(), drop.DisplayName, () => this.GetCropSubject(potCrop, ObjectContext.World, pot.hoeDirt.Value));
}
if (potBush != null)
{
ISubject subject = this.Codex.GetByEntity(potBush, this.Location ?? potBush.currentLocation);
if (subject != null)
yield return new LinkField(I18n.Item_Contents(), subject.Name, () => subject);
}
}
// machine output
foreach (ICustomField field in this.GetMachineOutputFields(obj))
yield return field;
// music blocks
if (obj?.Name == "Flute Block")
yield return new GenericField(I18n.Item_MusicBlock_Pitch(), I18n.Generic_Ratio(value: obj.preservedParentSheetIndex.Value, max: 2300));
else if (obj?.Name == "Drum Block")
yield return new GenericField(I18n.Item_MusicBlock_DrumType(), I18n.Generic_Ratio(value: obj.preservedParentSheetIndex.Value, max: 6));
// item
if (showInventoryFields)
{
// needed for
foreach (ICustomField field in this.GetNeededForFields(obj))
yield return field;
// sale data
if (canSell && !isCrop)
{
// sale price
string saleValueSummary = GenericField.GetSaleValueString(this.GetSaleValue(item, this.KnownQuality), item.Stack);
yield return new GenericField(I18n.Item_SellsFor(), saleValueSummary);
// sell to
List<string> buyers = new List<string>();
if (obj?.canBeShipped() == true)
buyers.Add(I18n.Item_SellsTo_ShippingBox());
buyers.AddRange(
from shop in this.Metadata.Shops
where shop.BuysCategories.Contains(item.Category)
let name = I18n.GetByKey(shop.DisplayKey).ToString()
orderby name
select name
);
yield return new GenericField(I18n.Item_SellsTo(), string.Join(", ", buyers));
}
// clothing
if (item is Clothing clothing)
yield return new GenericField(I18n.Item_CanBeDyed(), this.Stringify(clothing.dyeable.Value));
// gift tastes
if (!isMovieTicket)
{
IDictionary<GiftTaste, GiftTasteModel[]> giftTastes = this.GetGiftTastes(item);
yield return new ItemGiftTastesField(I18n.Item_LovesThis(), giftTastes, GiftTaste.Love, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes);
yield return new ItemGiftTastesField(I18n.Item_LikesThis(), giftTastes, GiftTaste.Like, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes);
if (this.ProgressionMode || this.HighlightUnrevealedGiftTastes || this.ShowAllGiftTastes)
{
yield return new ItemGiftTastesField(I18n.Item_NeutralAboutThis(), giftTastes, GiftTaste.Neutral, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes);
yield return new ItemGiftTastesField(I18n.Item_DislikesThis(), giftTastes, GiftTaste.Dislike, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes);
yield return new ItemGiftTastesField(I18n.Item_HatesThis(), giftTastes, GiftTaste.Hate, onlyRevealed: this.ProgressionMode, highlightUnrevealed: this.HighlightUnrevealedGiftTastes);
}
}
}
// recipes
if (showInventoryFields)
{
RecipeModel[] recipes =
// recipes that take this item as ingredient
this.GameHelper.GetRecipesForIngredient(this.DisplayItem)
.Concat(this.GameHelper.GetRecipesForIngredient(item))
// recipes which produce this item
.Concat(this.GameHelper.GetRecipesForOutput(this.DisplayItem))
.Concat(this.GameHelper.GetRecipesForOutput(item))
// recipes for a machine
.Concat(this.GameHelper.GetRecipesForMachine(this.DisplayItem as SObject))
.Concat(this.GameHelper.GetRecipesForMachine(item as SObject))
.ToArray();
if (recipes.Any())
yield return new ItemRecipesField(this.GameHelper, I18n.Item_Recipes(), item, recipes.ToArray());
}
// fish spawn rules
if (item.Category == SObject.FishCategory)
yield return new FishSpawnRulesField(this.GameHelper, I18n.Item_FishSpawnRules(), item.ParentSheetIndex);
// fish pond data
// derived from FishPond::doAction and FishPond::isLegalFishForPonds
if (!item.HasContextTag("fish_legendary") && (item.Category == SObject.FishCategory || Utility.IsNormalObjectAtParentSheetIndex(item, 393/*coral*/) || Utility.IsNormalObjectAtParentSheetIndex(item, 397/*sea urchin*/)))
{
foreach (FishPondData fishPondData in Game1.content.Load<List<FishPondData>>("Data\\FishPondData"))
{
if (!fishPondData.RequiredTags.All(item.HasContextTag))
continue;
int minChanceOfAnyDrop = (int)Math.Round(Utility.Lerp(0.15f, 0.95f, 1 / 10f) * 100);
int maxChanceOfAnyDrop = (int)Math.Round(Utility.Lerp(0.15f, 0.95f, FishPond.MAXIMUM_OCCUPANCY / 10f) * 100);
string preface = I18n.Building_FishPond_Drops_Preface(chance: I18n.Generic_Range(min: minChanceOfAnyDrop, max: maxChanceOfAnyDrop));
yield return new FishPondDropsField(this.GameHelper, I18n.Item_FishPondDrops(), -1, fishPondData, preface);
break;
}
}
// fence
if (item is Fence fence)
{
string healthLabel = I18n.Item_FenceHealth();
// health
if (Game1.getFarm().isBuildingConstructed(Constant.BuildingNames.GoldClock))
yield return new GenericField(healthLabel, I18n.Item_FenceHealth_GoldClock());
else
{
float maxHealth = fence.isGate.Value ? fence.maxHealth.Value * 2 : fence.maxHealth.Value;
float health = fence.health.Value / maxHealth;
double daysLeft = Math.Round(fence.health.Value * this.Constants.FenceDecayRate / 60 / 24);
double percent = Math.Round(health * 100);
yield return new PercentageBarField(healthLabel, (int)fence.health.Value, (int)maxHealth, Color.Green, Color.Red, I18n.Item_FenceHealth_Summary(percent: (int)percent, count: (int)daysLeft));
}
}
// movie ticket
if (isMovieTicket)
{
MovieData movie = MovieTheater.GetMovieForDate(Game1.Date);
if (movie == null)
yield return new GenericField(I18n.Item_MovieTicket_MovieThisWeek(), I18n.Item_MovieTicket_MovieThisWeek_None());
else
{
// movie this week
yield return new GenericField(I18n.Item_MovieTicket_MovieThisWeek(), new IFormattedText[]
{
new FormattedText(movie.Title, bold: true),
new FormattedText(Environment.NewLine),
new FormattedText(movie.Description)
});
// movie tastes
const GiftTaste rejectKey = (GiftTaste)(-1);
IDictionary<GiftTaste, string[]> tastes = this.GameHelper.GetMovieTastes()
.GroupBy(entry => entry.Value ?? rejectKey)
.ToDictionary(group => group.Key, group => group.Select(p => p.Key.Name).OrderBy(p => p).ToArray());
yield return new MovieTastesField(I18n.Item_MovieTicket_LovesMovie(), tastes, GiftTaste.Love);
yield return new MovieTastesField(I18n.Item_MovieTicket_LikesMovie(), tastes, GiftTaste.Like);
yield return new MovieTastesField(I18n.Item_MovieTicket_DislikesMovie(), tastes, GiftTaste.Dislike);
yield return new MovieTastesField(I18n.Item_MovieTicket_RejectsMovie(), tastes, rejectKey);
}
}
// dyes
if (showInventoryFields)
yield return new ColorField(I18n.Item_ProducesDye(), item);
// owned and times cooked/crafted
if (showInventoryFields && !isCrop)
{
// owned
yield return new GenericField(I18n.Item_NumberOwned(), I18n.Item_NumberOwned_Summary(count: this.GameHelper.CountOwnedItems(item)));
// times crafted
RecipeModel[] recipes = this.GameHelper
.GetRecipes()
.Where(recipe => recipe.OutputItemIndex == this.Target.ParentSheetIndex && recipe.OutputItemType == this.Target.GetItemType())
.ToArray();
if (recipes.Any())
{
string label = recipes.First().Type == RecipeType.Cooking ? I18n.Item_NumberCooked() : I18n.Item_NumberCrafted();
int timesCrafted = recipes.Sum(recipe => recipe.GetTimesCrafted(Game1.player));
if (timesCrafted >= 0) // negative value means not available for this recipe type
yield return new GenericField(label, I18n.Item_NumberCrafted_Summary(count: timesCrafted));
}
}
// see also crop
bool seeAlsoCrop =
isSeed
&& item.ParentSheetIndex != this.SeedForCrop.indexOfHarvest.Value // skip seeds which produce themselves (e.g. coffee beans)
&& item.ParentSheetIndex is not (495 or 496 or 497) // skip random seasonal seeds
&& item.ParentSheetIndex != 770; // skip mixed seeds
if (seeAlsoCrop)
{
Item drop = this.GameHelper.GetObjectBySpriteIndex(this.SeedForCrop.indexOfHarvest.Value);
yield return new LinkField(I18n.Item_SeeAlso(), drop.DisplayName, () => this.GetCropSubject(this.SeedForCrop, ObjectContext.Inventory, null));
}
}
/// <summary>Get the data to display for this subject.</summary>
public override IEnumerable<IDebugField> GetDebugFields()
{
Item target = this.Target;
SObject obj = target as SObject;
Crop crop = this.FromCrop ?? this.SeedForCrop;
// pinned fields
yield return new GenericDebugField("item ID", target.ParentSheetIndex, pinned: true);
yield return new GenericDebugField("category", $"{target.Category} ({target.getCategoryName()})", pinned: true);
if (obj != null)
{
yield return new GenericDebugField("edibility", obj.Edibility, pinned: true);
yield return new GenericDebugField("item type", obj.Type, pinned: true);
}
if (crop != null)
{
yield return new GenericDebugField("crop fully grown", this.Stringify(crop.fullyGrown.Value), pinned: true);
yield return new GenericDebugField("crop phase", $"{crop.currentPhase} (day {crop.dayOfCurrentPhase} in phase)", pinned: true);
}
// raw fields
foreach (IDebugField field in this.GetDebugFieldsFrom(target))
yield return field;
if (crop != null)
{
foreach (IDebugField field in this.GetDebugFieldsFrom(crop))
yield return new GenericDebugField($"crop::{field.Label}", field.Value, field.HasValue, field.IsPinned);
}
}
/// <summary>Draw the subject portrait (if available).</summary>
/// <param name="spriteBatch">The sprite batch being drawn.</param>
/// <param name="position">The position at which to draw.</param>
/// <param name="size">The size of the portrait to draw.</param>
/// <returns>Returns <c>true</c> if a portrait was drawn, else <c>false</c>.</returns>
public override bool DrawPortrait(SpriteBatch spriteBatch, Vector2 position, Vector2 size)
{
this.DisplayItem.drawInMenu(spriteBatch, position, 1, 1f, 1f, StackDrawType.Hide, Color.White, false);
return true;
}
/*********
** Private methods
*********/
/// <summary>Get the equivalent menu item for the specified target. (For example, the inventory item matching a fence object.)</summary>
/// <param name="item">The target item.</param>
private Item GetMenuItem(Item item)
{
// fence
if (item is Fence fence)
{
int spriteID = fence.GetItemParentSheetIndex();
return this.GameHelper.GetObjectBySpriteIndex(spriteID);
}
return item;
}
/// <summary>Get the item description.</summary>
/// <param name="item">The item.</param>
[SuppressMessage("ReSharper", "AssignmentIsFullyDiscarded", Justification = "Discarding the value is deliberate. We need to call the property to trigger the data load, but we don't actually need the result.")]
private string GetDescription(Item item)
{
try
{
_ = item.DisplayName; // force display name to load, which is needed to get the description outside the inventory for some reason
return item.getDescription();
}
catch (KeyNotFoundException)
{
return null; // e.g. incubator
}
}
/// <summary>Get the item type.</summary>
/// <param name="item">The item.</param>
private string GetTypeValue(Item item)
{
string categoryName = item.getCategoryName();
return !string.IsNullOrWhiteSpace(categoryName)
? categoryName
: I18n.Type_Other();
}
/// <summary>Get the crop which grows from the given seed, if applicable.</summary>
/// <param name="seed">The potential seed item to check.</param>
private Crop TryGetCropForSeed(Item seed)
{
if (seed is not SObject obj || obj.bigCraftable.Value)
return null;
try
{
Crop crop = new Crop(seed.ParentSheetIndex, 0, 0);
return crop.netSeedIndex.Value > -1
? crop
: null;
}
catch
{
return null;
}
}
/// <summary>Get the custom fields for a crop.</summary>
/// <param name="dirt">The dirt the crop is planted in, if applicable.</param>
/// <param name="crop">The crop to represent.</param>
/// <param name="isSeed">Whether the crop being displayed is for an unplanted seed.</param>
private IEnumerable<ICustomField> GetCropFields(HoeDirt dirt, Crop crop, bool isSeed)
{
if (crop == null)
yield break;
var data = new CropDataParser(crop, isPlanted: !isSeed);
bool isForage = crop.whichForageCrop.Value > 0 && crop.fullyGrown.Value; // show crop fields for growing mixed seeds
// add next-harvest field
if (!isSeed)
{
// get next harvest
SDate nextHarvest = data.GetNextHarvest();
// generate field
string summary;
if (data.CanHarvestNow)
summary = I18n.Generic_Now();
else if (!Game1.currentLocation.SeedsIgnoreSeasonsHere() && !data.Seasons.Contains(nextHarvest.Season))
summary = I18n.Crop_Harvest_TooLate(date: this.Stringify(nextHarvest));
else
summary = $"{this.Stringify(nextHarvest)} ({this.GetRelativeDateStr(nextHarvest)})";
yield return new GenericField(I18n.Crop_Harvest(), summary);
}
// crop summary
if (!isForage)
{
List<string> summary = new List<string>();
// harvest
if (!crop.forageCrop.Value)
{
summary.Add(data.HasMultipleHarvests
? I18n.Crop_Summary_HarvestOnce(daysToFirstHarvest: data.DaysToFirstHarvest)
: I18n.Crop_Summary_HarvestMulti(daysToFirstHarvest: data.DaysToFirstHarvest, daysToNextHarvests: data.DaysToSubsequentHarvest)
);
}
// seasons
summary.Add(I18n.Crop_Summary_Seasons(seasons: string.Join(", ", I18n.GetSeasonNames(data.Seasons))));
// drops
if (crop.minHarvest != crop.maxHarvest && crop.chanceForExtraCrops.Value > 0)
summary.Add(I18n.Crop_Summary_DropsXToY(min: crop.minHarvest.Value, max: crop.maxHarvest.Value, percent: (int)Math.Round(crop.chanceForExtraCrops.Value * 100, 2)));
else if (crop.minHarvest.Value > 1)
summary.Add(I18n.Crop_Summary_DropsX(count: crop.minHarvest.Value));
// crop sale price
Item drop = data.GetSampleDrop();
summary.Add(I18n.Crop_Summary_SellsFor(price: GenericField.GetSaleValueString(this.GetSaleValue(drop, false), 1)));
// generate field
yield return new GenericField(I18n.Crop_Summary(), "-" + string.Join($"{Environment.NewLine}-", summary));
}
// dirt water/fertilizer state
if (dirt != null && !isForage)
{
// watered
yield return new GenericField(I18n.Crop_Watered(), this.Stringify(dirt.state.Value == HoeDirt.watered));
// fertilizer
string[] appliedFertilizers = this.GetAppliedFertilizers(dirt)
.Select(GameI18n.GetObjectName)
.Distinct()
.DefaultIfEmpty(this.Stringify(false))
.OrderBy(p => p)
.ToArray();
yield return new GenericField(I18n.Crop_Fertilized(), string.Join(", ", appliedFertilizers));
}
}
/// <summary>Get the fertilizer item IDs applied to a dirt tile.</summary>
/// <param name="dirt">The dirt tile to check.</param>
private IEnumerable<int> GetAppliedFertilizers(HoeDirt dirt)
{
if (this.GameHelper.MultiFertilizer.IsLoaded)
return this.GameHelper.MultiFertilizer.GetAppliedFertilizers(dirt);
if (dirt.fertilizer.Value > 0)
return new[] { dirt.fertilizer.Value };
return Enumerable.Empty<int>();
}
/// <summary>Get the custom fields for machine output.</summary>
/// <param name="machine">The machine whose output to represent.</param>
private IEnumerable<ICustomField> GetMachineOutputFields(SObject machine)
{
if (machine == null)
yield break;
SObject heldObj = machine.heldObject.Value;
int minutesLeft = machine.MinutesUntilReady;
// cask
if (machine is Cask cask)
{
// output item
if (heldObj != null)
{
ItemQuality curQuality = (ItemQuality)heldObj.Quality;
// calculate aging schedule
float effectiveAge = this.Constants.CaskAgeSchedule.Values.Max() - cask.daysToMature.Value;
var schedule =
(
from entry in this.Constants.CaskAgeSchedule
let quality = entry.Key
let baseDays = entry.Value
where baseDays > effectiveAge
orderby baseDays ascending
let daysLeft = (int)Math.Ceiling((baseDays - effectiveAge) / cask.agingRate.Value)
select new
{
Quality = quality,
DaysLeft = daysLeft,
HarvestDate = SDate.Now().AddDays(daysLeft)
}
)
.ToArray();
// display fields
yield return new ItemIconField(this.GameHelper, I18n.Item_Contents(), heldObj, this.Codex);
if (minutesLeft <= 0 || !schedule.Any())
yield return new GenericField(I18n.Item_CaskSchedule(), I18n.Item_CaskSchedule_Now(quality: I18n.For(curQuality)));
else
{
string scheduleStr = string.Join(Environment.NewLine, (
from entry in schedule
let str = I18n.GetPlural(entry.DaysLeft, I18n.Item_CaskSchedule_Tomorrow(quality: I18n.For(entry.Quality)), I18n.Item_CaskSchedule_InXDays(quality: I18n.For(entry.Quality), count: entry.DaysLeft, date: this.Stringify(entry.HarvestDate)))
select $"-{str}"
));
yield return new GenericField(I18n.Item_CaskSchedule(), $"{I18n.Item_CaskSchedule_NowPartial(quality: I18n.For(curQuality))}{Environment.NewLine}{scheduleStr}");
}
}
}
// crab pot
else if (machine is CrabPot pot)
{
// bait
if (heldObj == null)
{
if (pot.bait.Value != null)
yield return new ItemIconField(this.GameHelper, I18n.Item_CrabpotBait(), pot.bait.Value, this.Codex);
else if (Game1.player.professions.Contains(11)) // no bait needed if luremaster
yield return new GenericField(I18n.Item_CrabpotBait(), I18n.Item_CrabpotBaitNotNeeded());
else
yield return new GenericField(I18n.Item_CrabpotBait(), I18n.Item_CrabpotBaitNeeded());
}
// output item
if (heldObj != null)
{
string summary = I18n.Item_Contents_Ready(name: heldObj.DisplayName);
yield return new ItemIconField(this.GameHelper, I18n.Item_Contents(), heldObj, this.Codex, summary);
}
}
// furniture
else if (machine is Furniture)
{
// displayed item
if (heldObj != null)
{
string summary = I18n.Item_Contents_Placed(name: heldObj.DisplayName);
yield return new ItemIconField(this.GameHelper, I18n.Item_Contents(), heldObj, this.Codex, summary);
}
}
// auto-grabber
else if (machine.ParentSheetIndex == Constant.ObjectIndexes.AutoGrabber && machine.GetItemType() == ItemType.BigCraftable)
{
string readyText = I18n.Stringify(heldObj is Chest output && output.GetItemsForPlayer(Game1.player.UniqueMultiplayerID).Any());
yield return new GenericField(I18n.Item_Contents(), readyText);
}
// generic machine
else
{
// output item
if (heldObj != null)
{
string summary = minutesLeft <= 0
? I18n.Item_Contents_Ready(name: heldObj.DisplayName)
: I18n.Item_Contents_Partial(name: heldObj.DisplayName, time: this.Stringify(TimeSpan.FromMinutes(minutesLeft)));
yield return new ItemIconField(this.GameHelper, I18n.Item_Contents(), heldObj, this.Codex, summary);
}
}
}
/// <summary>Get the custom fields indicating what an item is needed for.</summary>
/// <param name="obj">The machine whose output to represent.</param>
private IEnumerable<ICustomField> GetNeededForFields(SObject obj)
{
if (obj == null || obj.GetItemType() != ItemType.Object)
yield break;
List<string> neededFor = new List<string>();
// bundles
{
string[] missingBundles =
(
from bundle in this.GetUnfinishedBundles(obj)
orderby bundle.Area, bundle.DisplayName
let countNeeded = this.GetIngredientCountNeeded(bundle, obj)
select countNeeded > 1
? $"{this.GetTranslatedBundleArea(bundle)}: {bundle.DisplayName} x {countNeeded}"
: $"{this.GetTranslatedBundleArea(bundle)}: {bundle.DisplayName}"
)
.ToArray();
if (missingBundles.Any())
neededFor.Add(I18n.Item_NeededFor_CommunityCenter(bundles: string.Join(", ", missingBundles)));
}
// polyculture achievement (ship 15 crops)
if (this.Constants.PolycultureCrops.Contains(obj.ParentSheetIndex))
{
int needed = this.Constants.PolycultureCount - this.GameHelper.GetShipped(obj.ParentSheetIndex);
if (needed > 0)
neededFor.Add(I18n.Item_NeededFor_Polyculture(count: needed));
}
// full shipment achievement (ship every item)
if (this.GameHelper.GetFullShipmentAchievementItems().Any(p => p.Key == obj.ParentSheetIndex && !p.Value))
neededFor.Add(I18n.Item_NeededFor_FullShipment());
// full collection achievement (donate every artifact)
if (obj.needsToBeDonated())
neededFor.Add(I18n.Item_NeededFor_FullCollection());
// recipe achievements
{
var recipes =
(
from recipe in this.GameHelper.GetRecipesForIngredient(this.DisplayItem)
let item = recipe.TryCreateItem(this.DisplayItem)
where item != null
orderby item.DisplayName
select new { recipe.Type, item.DisplayName, TimesCrafted = recipe.GetTimesCrafted(Game1.player) }
)
.ToArray();
// gourmet chef achievement (cook every recipe)
string[] uncookedNames = (from recipe in recipes where recipe.Type == RecipeType.Cooking && recipe.TimesCrafted <= 0 select recipe.DisplayName).ToArray();
if (uncookedNames.Any())
neededFor.Add(I18n.Item_NeededFor_GourmetChef(recipes: string.Join(", ", uncookedNames)));
// craft master achievement (craft every item)
string[] uncraftedNames = (from recipe in recipes where recipe.Type == RecipeType.Crafting && recipe.TimesCrafted <= 0 select recipe.DisplayName).ToArray();
if (uncraftedNames.Any())
neededFor.Add(I18n.Item_NeededFor_CraftMaster(recipes: string.Join(", ", uncraftedNames)));
}
// quests
{
string[] quests = this.GameHelper
.GetQuestsWhichNeedItem(obj)
.Select(p => p.DisplayText)
.OrderBy(p => p)
.ToArray();
if (quests.Any())
neededFor.Add(I18n.Item_NeededFor_Quests(quests: string.Join(", ", quests)));
}
// yield
if (neededFor.Any())
yield return new GenericField(I18n.Item_NeededFor(), string.Join(", ", neededFor));
}
/// <summary>Get unfinished bundles which require this item.</summary>
/// <param name="item">The item for which to find bundles.</param>
private IEnumerable<BundleModel> GetUnfinishedBundles(SObject item)
{
// no bundles for Joja members
if (Game1.player.hasOrWillReceiveMail(Constant.MailLetters.JojaMember))
yield break;
// avoid false positives
if (item.bigCraftable.Value || item is Cask or Fence or Furniture or IndoorPot or Sign or Torch or Wallpaper)
yield break; // avoid false positives
// get community center
CommunityCenter communityCenter = Game1.locations.OfType<CommunityCenter>().First();
bool IsBundleOpen(int id)
{
try
{
return !communityCenter.isBundleComplete(id);
}
catch
{
return false; // invalid bundle data
}
}
// get bundles
if (!communityCenter.areAllAreasComplete() || IsBundleOpen(36))
{
foreach (BundleModel bundle in this.GameHelper.GetBundleData())
{
if (!IsBundleOpen(bundle.ID))
continue;
bool isMissing = this.GetIngredientsFromBundle(bundle, item).Any(p => this.IsIngredientNeeded(bundle, p));
if (isMissing)
yield return bundle;
}
}
}
/// <summary>Get the translated name for a bundle's area.</summary>
/// <param name="bundle">The bundle.</param>
private string GetTranslatedBundleArea(BundleModel bundle)
{
return bundle.Area switch
{
"Pantry" => I18n.BundleArea_Pantry(),
"Crafts Room" => I18n.BundleArea_CraftsRoom(),
"Fish Tank" => I18n.BundleArea_FishTank(),
"Boiler Room" => I18n.BundleArea_BoilerRoom(),
"Vault" => I18n.BundleArea_Vault(),
"Bulletin Board" => I18n.BundleArea_BulletinBoard(),
"Abandoned Joja Mart" => I18n.BundleArea_AbandonedJojaMart(),
_ => bundle.Area
};
}
/// <summary>Get the possible sale values for an item.</summary>
/// <param name="item">The item.</param>
/// <param name="qualityIsKnown">Whether the item quality is known. This is <c>true</c> for an inventory item, <c>false</c> for a map object.</param>
private IDictionary<ItemQuality, int> GetSaleValue(Item item, bool qualityIsKnown)
{
SObject obj = item.getOne() as SObject;
// single quality
if (obj == null || !this.GameHelper.CanHaveQuality(item) || qualityIsKnown)
{
ItemQuality quality = qualityIsKnown && obj != null
? (ItemQuality)obj.Quality
: ItemQuality.Normal;
return new Dictionary<ItemQuality, int> { [quality] = this.GetRawSalePrice(item) };
}
// multiple qualities
{
int[] iridiumItems = this.Constants.ItemsWithIridiumQuality;
var prices = new Dictionary<ItemQuality, int>();
var sample = (SObject)item.getOne();
foreach (ItemQuality quality in CommonHelper.GetEnumValues<ItemQuality>())
{
if (quality == ItemQuality.Iridium && !iridiumItems.Contains(item.ParentSheetIndex) && !iridiumItems.Contains(item.Category))
continue;
sample.Quality = (int)quality;
prices[quality] = this.GetRawSalePrice(sample);
}
return prices;
}
}
/// <summary>Get the sale price for a specific item instance.</summary>
/// <param name="item">The item instance.</param>
/// <remarks>Derived from <see cref="Utility.getSellToStorePriceOfItem(Item, bool)"/>.</remarks>
private int GetRawSalePrice(Item item)
{
int price = item is SObject obj
? obj.sellToStorePrice()
: (item.salePrice() / 2);
return price > 0
? price
: 0;
}
/// <summary>Get how much each NPC likes receiving an item as a gift.</summary>
/// <param name="item">The potential gift item.</param>
private IDictionary<GiftTaste, GiftTasteModel[]> GetGiftTastes(Item item)
{
return this.GameHelper.GetGiftTastes(item)
.GroupBy(p => p.Taste)
.ToDictionary(p => p.Key, p => p.Distinct().ToArray());
}
/// <summary>Get bundle ingredients matching the given item.</summary>
/// <param name="bundle">The bundle to search.</param>
/// <param name="item">The item to match.</param>
private IEnumerable<BundleIngredientModel> GetIngredientsFromBundle(BundleModel bundle, SObject item)
{
return bundle.Ingredients
.Where(p => p.ItemID == item.ParentSheetIndex && p.Quality <= (ItemQuality)item.Quality); // get ingredients
}
/// <summary>Get whether an ingredient is still needed for a bundle.</summary>
/// <param name="bundle">The bundle to check.</param>
/// <param name="ingredient">The ingredient to check.</param>
private bool IsIngredientNeeded(BundleModel bundle, BundleIngredientModel ingredient)
{
CommunityCenter communityCenter = Game1.locations.OfType<CommunityCenter>().First();
// handle rare edge case where item is required in the bundle data, but it's not
// present in the community center data. This seems to be caused by some mods like
// Challenging Community Center Bundles in some cases.
if (!communityCenter.bundles.TryGetValue(bundle.ID, out bool[] items) || ingredient.Index >= items.Length)
return true;
return !items[ingredient.Index];
}
/// <summary>Get the number of an ingredient needed for a bundle.</summary>
/// <param name="bundle">The bundle to check.</param>
/// <param name="item">The ingredient to check.</param>
private int GetIngredientCountNeeded(BundleModel bundle, SObject item)
{
return this
.GetIngredientsFromBundle(bundle, item)
.Where(p => this.IsIngredientNeeded(bundle, p))
.Sum(p => p.Stack);
}
/// <summary>Get whether the target is a spawned stone or mining node on the ground.</summary>
private bool IsSpawnedStoneNode()
{
return
this.Context == ObjectContext.World
&& this.Target is (SObject and not Chest)
&& this.Name == "Stone";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace System.Data.SqlClient.SNI
{
/// <summary>
/// SNI MARS connection. Multiple MARS streams will be overlaid on this connection.
/// </summary>
internal class SNIMarsConnection
{
private readonly Guid _connectionId = Guid.NewGuid();
private readonly Dictionary<int, SNIMarsHandle> _sessions = new Dictionary<int, SNIMarsHandle>();
private readonly byte[] _headerBytes = new byte[SNISMUXHeader.HEADER_LENGTH];
private SNIHandle _lowerHandle;
private ushort _nextSessionId = 0;
private int _currentHeaderByteCount = 0;
private int _dataBytesLeft = 0;
private SNISMUXHeader _currentHeader;
private SNIPacket _currentPacket;
/// <summary>
/// Connection ID
/// </summary>
public Guid ConnectionId
{
get
{
return _connectionId;
}
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="lowerHandle">Lower handle</param>
public SNIMarsConnection(SNIHandle lowerHandle)
{
_lowerHandle = lowerHandle;
_lowerHandle.SetAsyncCallbacks(HandleReceiveComplete, HandleSendComplete);
}
public SNIMarsHandle CreateMarsSession(object callbackObject, bool async)
{
lock (this)
{
ushort sessionId = _nextSessionId++;
SNIMarsHandle handle = new SNIMarsHandle(this, sessionId, callbackObject, async);
_sessions.Add(sessionId, handle);
return handle;
}
}
/// <summary>
/// Start receiving
/// </summary>
/// <returns></returns>
public uint StartReceive()
{
SNIPacket packet = null;
if (ReceiveAsync(ref packet) == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return TdsEnums.SNI_SUCCESS_IO_PENDING;
}
return SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, 0, SNICommon.ConnNotUsableError, string.Empty);
}
/// <summary>
/// Send a packet synchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public uint Send(SNIPacket packet)
{
lock (this)
{
return _lowerHandle.Send(packet);
}
}
/// <summary>
/// Send a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="callback">Completion callback</param>
/// <returns>SNI error code</returns>
public uint SendAsync(SNIPacket packet, SNIAsyncCallback callback)
{
lock (this)
{
return _lowerHandle.SendAsync(packet, callback);
}
}
/// <summary>
/// Receive a packet asynchronously
/// </summary>
/// <param name="packet">SNI packet</param>
/// <returns>SNI error code</returns>
public uint ReceiveAsync(ref SNIPacket packet)
{
lock (this)
{
return _lowerHandle.ReceiveAsync(ref packet, isMars: true);
}
}
/// <summary>
/// Check SNI handle connection
/// </summary>
/// <param name="handle"></param>
/// <returns>SNI error status</returns>
public uint CheckConnection()
{
lock (this)
{
return _lowerHandle.CheckConnection();
}
}
/// <summary>
/// Process a receive error
/// </summary>
public void HandleReceiveError(SNIPacket packet)
{
Debug.Assert(Monitor.IsEntered(this), "HandleReceiveError was called without being locked.");
foreach (SNIMarsHandle handle in _sessions.Values)
{
handle.HandleReceiveError(packet);
}
}
/// <summary>
/// Process a send completion
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="sniErrorCode">SNI error code</param>
public void HandleSendComplete(SNIPacket packet, uint sniErrorCode)
{
packet.InvokeCompletionCallback(sniErrorCode);
}
/// <summary>
/// Process a receive completion
/// </summary>
/// <param name="packet">SNI packet</param>
/// <param name="sniErrorCode">SNI error code</param>
public void HandleReceiveComplete(SNIPacket packet, uint sniErrorCode)
{
SNISMUXHeader currentHeader = null;
SNIPacket currentPacket = null;
SNIMarsHandle currentSession = null;
if (sniErrorCode != TdsEnums.SNI_SUCCESS)
{
lock (this)
{
HandleReceiveError(packet);
return;
}
}
while (true)
{
lock (this)
{
if (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
{
currentHeader = null;
currentPacket = null;
currentSession = null;
while (_currentHeaderByteCount != SNISMUXHeader.HEADER_LENGTH)
{
int bytesTaken = packet.TakeData(_headerBytes, _currentHeaderByteCount, SNISMUXHeader.HEADER_LENGTH - _currentHeaderByteCount);
_currentHeaderByteCount += bytesTaken;
if (bytesTaken == 0)
{
sniErrorCode = ReceiveAsync(ref packet);
if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return;
}
HandleReceiveError(packet);
return;
}
}
_currentHeader = new SNISMUXHeader()
{
SMID = _headerBytes[0],
flags = _headerBytes[1],
sessionId = BitConverter.ToUInt16(_headerBytes, 2),
length = BitConverter.ToUInt32(_headerBytes, 4) - SNISMUXHeader.HEADER_LENGTH,
sequenceNumber = BitConverter.ToUInt32(_headerBytes, 8),
highwater = BitConverter.ToUInt32(_headerBytes, 12)
};
_dataBytesLeft = (int)_currentHeader.length;
_currentPacket = new SNIPacket();
_currentPacket.Allocate((int)_currentHeader.length);
}
currentHeader = _currentHeader;
currentPacket = _currentPacket;
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
{
if (_dataBytesLeft > 0)
{
int length = packet.TakeData(_currentPacket, _dataBytesLeft);
_dataBytesLeft -= length;
if (_dataBytesLeft > 0)
{
sniErrorCode = ReceiveAsync(ref packet);
if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return;
}
HandleReceiveError(packet);
return;
}
}
}
_currentHeaderByteCount = 0;
if (!_sessions.ContainsKey(_currentHeader.sessionId))
{
SNILoadHandle.SingletonInstance.LastError = new SNIError(SNIProviders.SMUX_PROV, 0, SNICommon.InvalidParameterError, string.Empty);
HandleReceiveError(packet);
_lowerHandle.Dispose();
_lowerHandle = null;
return;
}
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_FIN)
{
_sessions.Remove(_currentHeader.sessionId);
}
else
{
currentSession = _sessions[_currentHeader.sessionId];
}
}
if (currentHeader.flags == (byte)SNISMUXFlags.SMUX_DATA)
{
currentSession.HandleReceiveComplete(currentPacket, currentHeader);
}
if (_currentHeader.flags == (byte)SNISMUXFlags.SMUX_ACK)
{
try
{
currentSession.HandleAck(currentHeader.highwater);
}
catch (Exception e)
{
SNICommon.ReportSNIError(SNIProviders.SMUX_PROV, SNICommon.InternalExceptionError, e);
}
}
lock (this)
{
if (packet.DataLeft == 0)
{
sniErrorCode = ReceiveAsync(ref packet);
if (sniErrorCode == TdsEnums.SNI_SUCCESS_IO_PENDING)
{
return;
}
HandleReceiveError(packet);
return;
}
}
}
}
/// <summary>
/// Enable SSL
/// </summary>
public uint EnableSsl(uint options)
{
return _lowerHandle.EnableSsl(options);
}
/// <summary>
/// Disable SSL
/// </summary>
public void DisableSsl()
{
_lowerHandle.DisableSsl();
}
#if DEBUG
/// <summary>
/// Test handle for killing underlying connection
/// </summary>
public void KillConnection()
{
_lowerHandle.KillConnection();
}
#endif
}
}
| |
//
// TokenizerTests.cs
//
// Author:
// Aaron Bockover <abockover@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if ENABLE_TESTS
using System;
using System.Reflection;
using NUnit.Framework;
using Hyena.Json;
namespace Hyena.Json.Tests
{
[TestFixture]
public class TokenizerTests : Hyena.Tests.TestBase
{
private Tokenizer tokenizer;
[TestFixtureSetUp]
public void Setup ()
{
tokenizer = new Tokenizer ();
}
[Test]
public void Whitespace ()
{
AssertTokenStream ("");
AssertTokenStream (" ");
AssertTokenStream ("\f\n\r\t ");
}
[Test]
public void BoolNull ()
{
// Boolean/null tests
AssertTokenStream ("true", Token.Bool (true));
AssertTokenStream ("false", Token.Bool (false));
AssertTokenStream ("null", Token.Null);
}
[Test]
public void NumberInt ()
{
AssertTokenStream ("0", Token.Integer (0));
AssertTokenStream ("-0", Token.Integer (-0));
AssertTokenStream ("9", Token.Integer (9));
AssertTokenStream ("-9", Token.Integer (-9));
AssertTokenStream ("14", Token.Integer (14));
AssertTokenStream ("-14", Token.Integer (-14));
AssertTokenStream ("15309", Token.Integer (15309));
AssertTokenStream ("-15309", Token.Integer (-15309));
}
[Test]
public void NumberFloat ()
{
AssertTokenStream ("0.0", Token.Number (0.0));
AssertTokenStream ("-0.0", Token.Number (-0.0));
AssertTokenStream ("1.9", Token.Number (1.9));
AssertTokenStream ("-1.9", Token.Number (-1.9));
AssertTokenStream ("9.1", Token.Number (9.1));
AssertTokenStream ("-9.1", Token.Number (-9.1));
AssertTokenStream ("15309.0", Token.Number (15309.0));
AssertTokenStream ("15309.9", Token.Number (15309.9));
AssertTokenStream ("-15309.01", Token.Number (-15309.01));
AssertTokenStream ("-15309.9009", Token.Number (-15309.9009));
}
[Test]
public void NumberExponent ()
{
AssertTokenStream ("20.6e3", Token.Number (20.6e3));
AssertTokenStream ("20.6e+3", Token.Number (20.6e+3));
AssertTokenStream ("20.6e-3", Token.Number (20.6e-3));
AssertTokenStream ("-20.6e3", Token.Number (-20.6e3));
AssertTokenStream ("-20.6e+3", Token.Number (-20.6e+3));
AssertTokenStream ("-20.6e-3", Token.Number (-20.6e-3));
AssertTokenStream ("1e1", Token.Number (1e1));
AssertTokenStream ("1E2", Token.Number (1E2));
AssertTokenStream ("1.0e1", Token.Number (1.0e1));
AssertTokenStream ("1.0E1", Token.Number (1.0E1));
}
[Test]
public void Strings ()
{
AssertTokenStream (@"""""", Token.String (""));
AssertTokenStream (@"""a""", Token.String ("a"));
AssertTokenStream (@"""ab""", Token.String ("ab"));
AssertTokenStream (@" ""a b"" ", Token.String ("a b"));
AssertTokenStream (@"""\""\""""", Token.String ("\"\""));
AssertTokenStream (@" ""a \"" \"" b"" ", Token.String ("a \" \" b"));
AssertTokenStream (@"""\ubeef""", Token.String ("\ubeef"));
AssertTokenStream (@"""\u00a9""", Token.String ("\u00a9"));
AssertTokenStream (@"""\u0000\u0001\u0002""", Token.String ("\u0000\u0001\u0002"));
AssertTokenStream (@"""1\uabcdef0""", Token.String ("1\uabcdef0"));
AssertTokenStream (@"""\b\f\n\r\t""", Token.String ("\b\f\n\r\t"));
}
[Test]
public void Container ()
{
AssertTokenStream ("{}", Token.ObjectStart, Token.ObjectFinish);
AssertTokenStream ("[]", Token.ArrayStart, Token.ArrayFinish);
AssertTokenStream ("{ }", Token.ObjectStart, Token.ObjectFinish);
AssertTokenStream ("[ ]", Token.ArrayStart, Token.ArrayFinish);
AssertTokenStream ("[{}]", Token.ArrayStart, Token.ObjectStart, Token.ObjectFinish, Token.ArrayFinish);
AssertTokenStream ("[[[ { } ]]]",
Token.ArrayStart, Token.ArrayStart, Token.ArrayStart,
Token.ObjectStart, Token.ObjectFinish,
Token.ArrayFinish, Token.ArrayFinish, Token.ArrayFinish);
}
[Test]
public void Array ()
{
AssertTokenStream ("[1]", Token.ArrayStart, Token.Integer (1), Token.ArrayFinish);
AssertTokenStream ("[1,0]", Token.ArrayStart, Token.Integer (1), Token.Comma, Token.Integer (0), Token.ArrayFinish);
AssertTokenStream ("[\"a\",true,null]", Token.ArrayStart, Token.String ("a"), Token.Comma,
Token.Bool (true), Token.Comma, Token.Null, Token.ArrayFinish);
AssertTokenStream ("[0,1,[[2,[4]],5],6]", Token.ArrayStart, Token.Integer (0), Token.Comma, Token.Integer (1),
Token.Comma, Token.ArrayStart, Token.ArrayStart, Token.Integer (2), Token.Comma, Token.ArrayStart,
Token.Integer (4), Token.ArrayFinish, Token.ArrayFinish, Token.Comma, Token.Integer (5), Token.ArrayFinish,
Token.Comma, Token.Integer (6), Token.ArrayFinish);
}
[Test]
public void Object ()
{
AssertTokenStream ("{\"a\":{}}", Token.ObjectStart, Token.String ("a"), Token.Colon, Token.ObjectStart,
Token.ObjectFinish, Token.ObjectFinish);
AssertTokenStream ("{\"a\":{\"b\":[],\"c\":false}}", Token.ObjectStart, Token.String ("a"),
Token.Colon, Token.ObjectStart, Token.String ("b"), Token.Colon, Token.ArrayStart, Token.ArrayFinish,
Token.Comma, Token.String ("c"), Token.Colon, Token.Bool (false), Token.ObjectFinish, Token.ObjectFinish);
AssertTokenStream ("[{\"a\":{},{}]", Token.ArrayStart, Token.ObjectStart, Token.String ("a"), Token.Colon,
Token.ObjectStart, Token.ObjectFinish, Token.Comma, Token.ObjectStart, Token.ObjectFinish, Token.ArrayFinish);
}
private void AssertTokenStream (string input, params Token [] tokens)
{
int cmp_idx = 0;
tokenizer.SetInput (input);
while (true) {
Token token = tokenizer.Scan ();
if (token == null) {
if (cmp_idx != tokens.Length) {
throw new ApplicationException ("Unexpected EOF");
}
break;
}
Token compare = tokens[cmp_idx++];
if (compare.Type != token.Type) {
throw new ApplicationException (String.Format ("TokenTypes do not match (exp {0}, got {1}",
compare.Type, token.Type));
}
if (compare.Value == null && token.Value == null) {
continue;
}
if ((compare.Type == TokenType.Integer && (int)compare.Value != (int)token.Value) ||
(compare.Type == TokenType.Number && (double)compare.Value != (double)token.Value) ||
(compare.Type == TokenType.String && (string)compare.Value != (string)token.Value) ||
(compare.Type == TokenType.Boolean && (bool)compare.Value != (bool)token.Value)) {
throw new ApplicationException ("Token values do not match");
}
}
}
}
}
#endif
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* 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 XorByte()
{
var test = new SimpleBinaryOpTest__XorByte();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// 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();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[ElementCount];
private static Byte[] _data2 = new Byte[ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte> _dataTable;
static SimpleBinaryOpTest__XorByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__XorByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MaxValue)); _data2[i] = (byte)(random.Next(0, byte.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte>(_data1, _data2, new Byte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Xor(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Xor(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Xor(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorByte();
var result = Sse2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if ((byte)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((byte)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<Byte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the cloudformation-2010-05-15.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.CloudFormation
{
/// <summary>
/// Constants used for properties of type Capability.
/// </summary>
public class Capability : ConstantClass
{
/// <summary>
/// Constant CAPABILITY_IAM for Capability
/// </summary>
public static readonly Capability CAPABILITY_IAM = new Capability("CAPABILITY_IAM");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public Capability(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static Capability FindValue(string value)
{
return FindValue<Capability>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator Capability(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type OnFailure.
/// </summary>
public class OnFailure : ConstantClass
{
/// <summary>
/// Constant DELETE for OnFailure
/// </summary>
public static readonly OnFailure DELETE = new OnFailure("DELETE");
/// <summary>
/// Constant DO_NOTHING for OnFailure
/// </summary>
public static readonly OnFailure DO_NOTHING = new OnFailure("DO_NOTHING");
/// <summary>
/// Constant ROLLBACK for OnFailure
/// </summary>
public static readonly OnFailure ROLLBACK = new OnFailure("ROLLBACK");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public OnFailure(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static OnFailure FindValue(string value)
{
return FindValue<OnFailure>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator OnFailure(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceSignalStatus.
/// </summary>
public class ResourceSignalStatus : ConstantClass
{
/// <summary>
/// Constant FAILURE for ResourceSignalStatus
/// </summary>
public static readonly ResourceSignalStatus FAILURE = new ResourceSignalStatus("FAILURE");
/// <summary>
/// Constant SUCCESS for ResourceSignalStatus
/// </summary>
public static readonly ResourceSignalStatus SUCCESS = new ResourceSignalStatus("SUCCESS");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceSignalStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceSignalStatus FindValue(string value)
{
return FindValue<ResourceSignalStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceSignalStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ResourceStatus.
/// </summary>
public class ResourceStatus : ConstantClass
{
/// <summary>
/// Constant CREATE_COMPLETE for ResourceStatus
/// </summary>
public static readonly ResourceStatus CREATE_COMPLETE = new ResourceStatus("CREATE_COMPLETE");
/// <summary>
/// Constant CREATE_FAILED for ResourceStatus
/// </summary>
public static readonly ResourceStatus CREATE_FAILED = new ResourceStatus("CREATE_FAILED");
/// <summary>
/// Constant CREATE_IN_PROGRESS for ResourceStatus
/// </summary>
public static readonly ResourceStatus CREATE_IN_PROGRESS = new ResourceStatus("CREATE_IN_PROGRESS");
/// <summary>
/// Constant DELETE_COMPLETE for ResourceStatus
/// </summary>
public static readonly ResourceStatus DELETE_COMPLETE = new ResourceStatus("DELETE_COMPLETE");
/// <summary>
/// Constant DELETE_FAILED for ResourceStatus
/// </summary>
public static readonly ResourceStatus DELETE_FAILED = new ResourceStatus("DELETE_FAILED");
/// <summary>
/// Constant DELETE_IN_PROGRESS for ResourceStatus
/// </summary>
public static readonly ResourceStatus DELETE_IN_PROGRESS = new ResourceStatus("DELETE_IN_PROGRESS");
/// <summary>
/// Constant DELETE_SKIPPED for ResourceStatus
/// </summary>
public static readonly ResourceStatus DELETE_SKIPPED = new ResourceStatus("DELETE_SKIPPED");
/// <summary>
/// Constant UPDATE_COMPLETE for ResourceStatus
/// </summary>
public static readonly ResourceStatus UPDATE_COMPLETE = new ResourceStatus("UPDATE_COMPLETE");
/// <summary>
/// Constant UPDATE_FAILED for ResourceStatus
/// </summary>
public static readonly ResourceStatus UPDATE_FAILED = new ResourceStatus("UPDATE_FAILED");
/// <summary>
/// Constant UPDATE_IN_PROGRESS for ResourceStatus
/// </summary>
public static readonly ResourceStatus UPDATE_IN_PROGRESS = new ResourceStatus("UPDATE_IN_PROGRESS");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ResourceStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ResourceStatus FindValue(string value)
{
return FindValue<ResourceStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ResourceStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type StackStatus.
/// </summary>
public class StackStatus : ConstantClass
{
/// <summary>
/// Constant CREATE_COMPLETE for StackStatus
/// </summary>
public static readonly StackStatus CREATE_COMPLETE = new StackStatus("CREATE_COMPLETE");
/// <summary>
/// Constant CREATE_FAILED for StackStatus
/// </summary>
public static readonly StackStatus CREATE_FAILED = new StackStatus("CREATE_FAILED");
/// <summary>
/// Constant CREATE_IN_PROGRESS for StackStatus
/// </summary>
public static readonly StackStatus CREATE_IN_PROGRESS = new StackStatus("CREATE_IN_PROGRESS");
/// <summary>
/// Constant DELETE_COMPLETE for StackStatus
/// </summary>
public static readonly StackStatus DELETE_COMPLETE = new StackStatus("DELETE_COMPLETE");
/// <summary>
/// Constant DELETE_FAILED for StackStatus
/// </summary>
public static readonly StackStatus DELETE_FAILED = new StackStatus("DELETE_FAILED");
/// <summary>
/// Constant DELETE_IN_PROGRESS for StackStatus
/// </summary>
public static readonly StackStatus DELETE_IN_PROGRESS = new StackStatus("DELETE_IN_PROGRESS");
/// <summary>
/// Constant ROLLBACK_COMPLETE for StackStatus
/// </summary>
public static readonly StackStatus ROLLBACK_COMPLETE = new StackStatus("ROLLBACK_COMPLETE");
/// <summary>
/// Constant ROLLBACK_FAILED for StackStatus
/// </summary>
public static readonly StackStatus ROLLBACK_FAILED = new StackStatus("ROLLBACK_FAILED");
/// <summary>
/// Constant ROLLBACK_IN_PROGRESS for StackStatus
/// </summary>
public static readonly StackStatus ROLLBACK_IN_PROGRESS = new StackStatus("ROLLBACK_IN_PROGRESS");
/// <summary>
/// Constant UPDATE_COMPLETE for StackStatus
/// </summary>
public static readonly StackStatus UPDATE_COMPLETE = new StackStatus("UPDATE_COMPLETE");
/// <summary>
/// Constant UPDATE_COMPLETE_CLEANUP_IN_PROGRESS for StackStatus
/// </summary>
public static readonly StackStatus UPDATE_COMPLETE_CLEANUP_IN_PROGRESS = new StackStatus("UPDATE_COMPLETE_CLEANUP_IN_PROGRESS");
/// <summary>
/// Constant UPDATE_IN_PROGRESS for StackStatus
/// </summary>
public static readonly StackStatus UPDATE_IN_PROGRESS = new StackStatus("UPDATE_IN_PROGRESS");
/// <summary>
/// Constant UPDATE_ROLLBACK_COMPLETE for StackStatus
/// </summary>
public static readonly StackStatus UPDATE_ROLLBACK_COMPLETE = new StackStatus("UPDATE_ROLLBACK_COMPLETE");
/// <summary>
/// Constant UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS for StackStatus
/// </summary>
public static readonly StackStatus UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS = new StackStatus("UPDATE_ROLLBACK_COMPLETE_CLEANUP_IN_PROGRESS");
/// <summary>
/// Constant UPDATE_ROLLBACK_FAILED for StackStatus
/// </summary>
public static readonly StackStatus UPDATE_ROLLBACK_FAILED = new StackStatus("UPDATE_ROLLBACK_FAILED");
/// <summary>
/// Constant UPDATE_ROLLBACK_IN_PROGRESS for StackStatus
/// </summary>
public static readonly StackStatus UPDATE_ROLLBACK_IN_PROGRESS = new StackStatus("UPDATE_ROLLBACK_IN_PROGRESS");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public StackStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static StackStatus FindValue(string value)
{
return FindValue<StackStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator StackStatus(string value)
{
return FindValue(value);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
namespace Apache.Geode.DUnitFramework
{
public delegate object ClientResultAggregator(List<object> objList);
public class ClientGroup : ClientBase
{
#region Public accessors
public bool Managed
{
get
{
return m_managed;
}
set
{
m_managed = value;
}
}
public List<ClientBase> Clients
{
get
{
return m_clients;
}
}
#endregion
#region Public events
public event UnitFnMethod<ClientBase> ClientTaskStarted;
public event UnitFnMethod<ClientBase, Exception> ClientTaskDone;
#endregion
private List<ClientBase> m_clients;
private bool m_managed;
private ClientResultAggregator m_aggregator;
private const int ClientWaitLoopMillis = 100;
public ClientGroup(bool managed)
{
m_clients = new List<ClientBase>();
m_managed = managed;
m_aggregator = null;
}
public static ClientGroup Create(bool managed)
{
return new ClientGroup(managed);
}
public static ClientGroup Create(
UnitFnMethodR<ClientBase> clientCreateDeleg, int num)
{
ClientGroup group = new ClientGroup(true);
group.AddP(clientCreateDeleg, null, num);
return group;
}
public void Add(params ClientBase[] clients)
{
if (clients != null)
{
foreach (ClientBase client in clients)
{
m_clients.Add(client);
}
}
}
public void Add(List<ClientBase> clients)
{
if (clients != null)
{
m_clients.AddRange(clients);
}
}
public void Add(UnitFnMethodR<ClientBase> clientCreateDeleg, int num)
{
AddP(clientCreateDeleg, null, num);
}
public void Add<T1>(UnitFnMethodR<ClientBase, T1> clientCreateDeleg,
int num, T1 param1)
{
AddP(clientCreateDeleg, new object[] { param1 }, num);
}
public void Add<T1, T2>(UnitFnMethodR<ClientBase, T1, T2> clientCreateDeleg,
int num, T1 param1, T2 param2)
{
AddP(clientCreateDeleg, new object[] { param1, param2 }, num);
}
public void Add<T1, T2, T3>(UnitFnMethodR<ClientBase, T1, T2, T3> clientCreateDeleg,
int num, T1 param1, T2 param2, T3 param3)
{
AddP(clientCreateDeleg, new object[] { param1, param2, param3 }, num);
}
public void Add<T1, T2, T3, T4>(UnitFnMethodR<ClientBase, T1, T2, T3, T4> clientCreateDeleg,
int num, T1 param1, T2 param2, T3 param3, T4 param4)
{
AddP(clientCreateDeleg,
new object[] { param1, param2, param3, param4 }, num);
}
public void Add<T1, T2, T3, T4, T5>(UnitFnMethodR<ClientBase, T1, T2, T3, T4, T5> clientCreateDeleg,
int num, T1 param1, T2 param2, T3 param3, T4 param4, T5 param5)
{
AddP(clientCreateDeleg,
new object[] { param1, param2, param3, param4, param5 }, num);
}
public void AddTaskHandlers(UnitFnMethod<ClientBase> taskStartedHandler,
UnitFnMethod<ClientBase, Exception> taskDoneHandler)
{
ClientTaskStarted += taskStartedHandler;
ClientTaskDone += taskDoneHandler;
}
public void RemoveTaskHandlers(UnitFnMethod<ClientBase> taskStartedHandler,
UnitFnMethod<ClientBase, Exception> taskDoneHandler)
{
ClientTaskStarted -= taskStartedHandler;
ClientTaskDone -= taskDoneHandler;
}
public void SetAggregator(ClientResultAggregator aggregator)
{
m_aggregator = aggregator;
}
#region Private methods
private void AddP(Delegate clientCreateDeleg, object[] paramList, int num)
{
lock (((ICollection)m_clients).SyncRoot)
{
for (int i = 1; i <= num; i++)
{
m_clients.Add(
(ClientBase)clientCreateDeleg.DynamicInvoke(paramList));
}
}
}
#endregion
#region ClientBase Members
public override string ID
{
get
{
string baseId = base.ID;
if (baseId != null && baseId.Length > 0) {
return baseId;
}
StringBuilder sb = new StringBuilder();
foreach (ClientBase client in m_clients) {
if (sb.Length > 0) {
sb.Append(',');
}
sb.Append(client.ID);
}
return sb.ToString();
}
set
{
base.ID = value;
}
}
public override void RemoveObjectID(int objectID)
{
foreach (ClientBase client in m_clients)
{
client.RemoveObjectID(objectID);
}
}
public override void CallFn(Delegate deleg, object[] paramList)
{
if (m_clients.Count > 1)
{
UnitFnMethod<Delegate, object[]> invokeDeleg;
IAsyncResult asyncResult;
List<IAsyncResult> invokeList = new List<IAsyncResult>();
List<UnitFnMethod<Delegate, object[]>> invokeDelegList =
new List<UnitFnMethod<Delegate, object[]>>();
foreach (ClientBase client in m_clients)
{
invokeDeleg = client.CallFn;
asyncResult = invokeDeleg.BeginInvoke(deleg, paramList, null, null);
client.IncrementTasksRunning();
if (ClientTaskStarted != null)
{
ClientTaskStarted.Invoke(client);
}
invokeDelegList.Add(invokeDeleg);
invokeList.Add(asyncResult);
}
bool clientsRunning = true;
Dictionary<ClientBase, bool> doneTasks =
new Dictionary<ClientBase, bool>();
while (clientsRunning)
{
clientsRunning = false;
for (int i = 0; i < m_clients.Count; i++)
{
ClientBase client = m_clients[i];
if (!doneTasks.ContainsKey(client))
{
clientsRunning = true;
invokeDeleg = invokeDelegList[i];
asyncResult = invokeList[i];
try
{
if (asyncResult.AsyncWaitHandle.WaitOne(
ClientWaitLoopMillis, false))
{
doneTasks.Add(client, true);
client.DecrementTasksRunning();
invokeDeleg.EndInvoke(asyncResult);
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, null);
}
}
}
catch (Exception ex)
{
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, ex);
}
}
}
}
}
}
else if (m_clients.Count == 1)
{
ClientBase client = m_clients[0];
try
{
client.IncrementTasksRunning();
if (ClientTaskStarted != null)
{
ClientTaskStarted.Invoke(client);
}
client.CallFn(deleg, paramList);
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, null);
}
}
catch (Exception ex)
{
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, ex);
}
}
client.DecrementTasksRunning();
}
}
public override object CallFnR(Delegate deleg, object[] paramList)
{
List<object> resultList = new List<object>();
if (m_clients.Count > 1)
{
UnitFnMethodR<object, Delegate, object[]> invokeDeleg;
IAsyncResult asyncResult;
List<IAsyncResult> invokeList = new List<IAsyncResult>();
List<UnitFnMethodR<object, Delegate, object[]>> invokeDelegList =
new List<UnitFnMethodR<object, Delegate, object[]>>();
foreach (ClientBase client in m_clients)
{
invokeDeleg = client.CallFnR;
asyncResult = invokeDeleg.BeginInvoke(deleg, paramList, null, null);
client.IncrementTasksRunning();
if (ClientTaskStarted != null)
{
ClientTaskStarted.Invoke(client);
}
invokeDelegList.Add(invokeDeleg);
invokeList.Add(asyncResult);
}
bool clientsRunning = true;
Dictionary<ClientBase, bool> doneTasks =
new Dictionary<ClientBase, bool>();
while (clientsRunning)
{
clientsRunning = false;
for (int i = 0; i < m_clients.Count; i++)
{
ClientBase client = m_clients[i];
if (!doneTasks.ContainsKey(client))
{
clientsRunning = true;
invokeDeleg = invokeDelegList[i];
asyncResult = invokeList[i];
try
{
if (asyncResult.AsyncWaitHandle.WaitOne(
ClientWaitLoopMillis, false))
{
doneTasks.Add(client, true);
client.DecrementTasksRunning();
resultList.Add(invokeDeleg.EndInvoke(asyncResult));
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, null);
}
}
}
catch (Exception ex)
{
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, ex);
}
}
}
}
}
}
else if (m_clients.Count == 1)
{
ClientBase client = m_clients[0];
try
{
client.IncrementTasksRunning();
if (ClientTaskStarted != null)
{
ClientTaskStarted.Invoke(client);
}
resultList.Add(client.CallFnR(deleg, paramList));
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, null);
}
}
catch (Exception ex)
{
if (ClientTaskDone != null)
{
ClientTaskDone.Invoke(client, ex);
}
}
client.DecrementTasksRunning();
}
if (m_aggregator != null)
{
return m_aggregator(resultList);
}
else
{
return resultList[0];
}
}
public override string HostName
{
get
{
return "localhost";
}
}
public override void SetLogFile(string logPath)
{
foreach (ClientBase client in m_clients)
{
client.SetLogFile(logPath);
}
}
public override void SetLogLevel(Util.LogLevel logLevel)
{
foreach (ClientBase client in m_clients)
{
client.SetLogLevel(logLevel);
}
}
/// <summary>
/// Dump the stack trace for all the clients that are stuck
/// i.e. a CallFn/CallFnR is executing on them.
/// To get the dump of all the clients use <see cref="DumpStackTraceAll"/>.
/// </summary>
public override void DumpStackTrace()
{
foreach (ClientBase client in m_clients)
{
if (!TaskRunning || client.TaskRunning)
{
client.DumpStackTrace();
}
}
}
public override void ForceKill(int waitMillis)
{
lock (((ICollection)m_clients).SyncRoot)
{
if (waitMillis > 0)
{
UnitFnMethod<int> timeoutDeleg;
IAsyncResult asyncResult;
List<IAsyncResult> timeoutList = new List<IAsyncResult>();
List<UnitFnMethod<int>> timeoutDelegList =
new List<UnitFnMethod<int>>();
foreach (ClientBase client in m_clients)
{
timeoutDeleg = client.ForceKill;
asyncResult = timeoutDeleg.BeginInvoke(waitMillis, null, null);
timeoutDelegList.Add(timeoutDeleg);
timeoutList.Add(asyncResult);
}
for (int i = 0; i < m_clients.Count; i++)
{
timeoutDeleg = timeoutDelegList[i];
asyncResult = timeoutList[i];
try
{
asyncResult.AsyncWaitHandle.WaitOne();
timeoutDeleg.EndInvoke(asyncResult);
}
catch (Exception)
{
// Some exception in invoking the kill -- just ignore.
}
}
}
else
{
foreach (ClientBase client in m_clients)
{
client.ForceKill(0);
}
}
}
}
public override ClientBase CreateNew(string clientId)
{
ClientGroup newGroup = new ClientGroup(true);
foreach (ClientBase client in m_clients)
{
newGroup.m_clients.Add(client.CreateNew(clientId));
}
return newGroup;
}
public override void TestCleanup()
{
lock (((ICollection)m_clients).SyncRoot)
{
if (m_managed)
{
foreach (ClientBase client in m_clients)
{
client.TestCleanup();
}
}
}
}
public override void Exit()
{
lock (((ICollection)m_clients).SyncRoot)
{
if (m_managed)
{
foreach (ClientBase client in m_clients)
{
client.Exit();
}
}
m_clients.Clear();
}
}
#endregion
/// <summary>
/// Dump stack trace for all the clients;
/// the <see cref="DumpStackTrace"/> function only dumps the stacks for
/// clients that are stuck.
/// </summary>
public void DumpStackTraceAll()
{
foreach (ClientBase client in m_clients)
{
client.DumpStackTrace();
}
}
/// <summary>
/// Sets the log file name with client name appended to each file.
/// </summary>
/// <param name="logPath">
/// The path of the log file.
/// The actual log file name shall be of the form {logPath}_{ClientId}.log
/// </param>
public void SetNameLogFile(string logPath)
{
foreach (ClientBase client in m_clients)
{
client.SetLogFile(logPath + '_' + client.ID + ".log");
}
}
}
}
| |
using BForms.Editor;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using BForms.Models;
using BForms.Utilities;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.EMMA;
namespace BForms.Renderers
{
public class BsEditorRenderer<TModel> : BsBaseRenderer<BsEditorHtmlBuilder<TModel>>
{
public BsEditorRenderer() { }
public BsEditorRenderer(BsEditorHtmlBuilder<TModel> builder)
: base(builder)
{
}
public override string Render()
{
var ignoreAjaxRequest = this.Builder.ignoreAjaxRequest.HasValue && this.Builder.ignoreAjaxRequest.Value;
var result = this.Builder.IsAjaxRequest() && !ignoreAjaxRequest ?
this.RenderAjax() :
this.RenderIndex();
return result;
}
public string RenderAjax()
{
var result = "";
foreach (var tab in this.Builder.TabConfigurator.Tabs)
{
if (tab.Value.HasModel)
{
tab.Value.Theme = this.Builder.Theme;
result += tab.Value.renderer.RenderAjax();
}
}
return result;
}
public string RenderTabs()
{
var result = string.Empty;
if (!string.IsNullOrEmpty(this.Builder.TabConfigurator.Title))
{
result += RenderTitle(this.Builder.TabConfigurator.Title);
}
if (this.Builder.TabConfigurator.Tabs.Count() > 1)
{
result += this.Builder.TabConfigurator.NavigationBuilder.ToString();
}
foreach (var tab in this.Builder.TabConfigurator.Tabs)
{
tab.Value.Theme = this.Builder.Theme;
var bulkMoveHtml = this.RenderMoveToGroups();
tab.Value.bulkMoveHtml = bulkMoveHtml;
result += tab.Value.ToString();
}
return result;
}
public string RenderGroups()
{
var result = string.Empty;
if (!string.IsNullOrEmpty(this.Builder.GroupConfigurator.Title))
{
result += RenderTitle(this.Builder.GroupConfigurator.Title);
}
var div = new TagBuilder("div");
div.AddCssClass("grid_view");
if (!this.Builder.isReadonly && !string.IsNullOrEmpty(this.Builder.GroupConfigurator.FormHtml))
{
var formWrapper = new TagBuilder("div");
formWrapper.AddCssClass("inline");
formWrapper.AddCssClass("search");
formWrapper.AddCssClass("bs-groupForm");
formWrapper.InnerHtml += this.Builder.GroupConfigurator.FormHtml;
div.InnerHtml += formWrapper.ToString();
}
foreach (var group in this.Builder.GroupConfigurator.Groups)
{
div.InnerHtml += group.Value.ToString();
}
result += div.ToString();
return result;
}
public string RenderGroupsFooter()
{
var cssClass = "col-lg-6 col-md-6 col-sm-6";
var counter = new TagBuilder("div");
counter.AddCssClass("row counter");
var total = new TagBuilder("div");
total.AddCssClass(cssClass);
var span = new TagBuilder("span");
span.AddCssClass("bs-counter");
total.InnerHtml += "Total: " + span;
counter.InnerHtml += total;
if (!this.Builder.isReadonly)
{
var reset = new TagBuilder("div");
reset.AddCssClass(cssClass);
var anchor = new TagBuilder("a");
anchor.MergeAttribute("href", "#");
anchor.AddCssClass("btn btn-default pull-right bs-resetGroupEditor");
anchor.InnerHtml += GetGlyphicon(Models.Glyphicon.Refresh);
anchor.InnerHtml += " " + BsResourceManager.Resource("BF_Reset");
if (!string.IsNullOrEmpty(this.Builder.saveUrl))
{
var saveAnchor = new TagBuilder("a");
saveAnchor.MergeAttribute("href", this.Builder.saveUrl);
saveAnchor.MergeAttribute("style", "margin-left:10px");
saveAnchor.AddCssClass("btn btn-default pull-right bs-saveGroupEditor");
saveAnchor.InnerHtml += GetGlyphicon(Models.Glyphicon.Save);
saveAnchor.InnerHtml += " " + BsResourceManager.Resource("BF_Save");
reset.InnerHtml += saveAnchor;
}
reset.InnerHtml += anchor;
counter.InnerHtml += reset;
}
return counter.ToString();
}
public string RenderTitle(string title)
{
var divToolbar = new TagBuilder("div");
divToolbar.AddCssClass("grid_toolbar");
var theme = this.Builder.Theme.GetDescription();
divToolbar.AddCssClass(theme);
var divToolbarHeader = new TagBuilder("div");
divToolbarHeader.AddCssClass("grid_toolbar_header");
var toolbarH = new TagBuilder("span");
toolbarH.AddCssClass("navbar-brand");
toolbarH.InnerHtml += title;
divToolbarHeader.InnerHtml += toolbarH;
divToolbar.InnerHtml += divToolbarHeader;
return divToolbar.ToString();
}
public string RenderMoveToGroups()
{
if (!this.Builder.isReadonly && this.Builder.GroupConfigurator.Groups.Any())
{
var button = new TagBuilder("button");
var glyph = GetGlyphiconTag(Glyphicon.ShareAlt);
if (this.Builder.GroupConfigurator.Groups.Count > 1)
{
var divContainer = new TagBuilder("div");
divContainer.AddCssClass("btn-default btn pull-right bs-bulkGroupMove");
var dropdownA = new TagBuilder("a");
dropdownA.MergeAttribute("data-toggle", "dropdown");
dropdownA.MergeAttribute("href", "#");
dropdownA.InnerHtml += BsResourceManager.Resource("BF_GroupEditorMoveToGroups");
dropdownA.InnerHtml += glyph;
var dropdownUl = new TagBuilder("ul");
dropdownUl.AddCssClass("dropdown-menu");
dropdownUl.MergeAttribute("style", "top:auto");
foreach (var group in this.Builder.GroupConfigurator.Groups)
{
var li = new TagBuilder("li");
var a = new TagBuilder("a");
a.MergeAttribute("href", "#");
a.MergeAttribute("class", "bs-moveToGroupBtn");
a.MergeAttribute("data-groupid", MvcHelpers.Serialize(group.Value.Uid));
a.InnerHtml += group.Value.Name;
li.InnerHtml += a;
dropdownUl.InnerHtml += li;
}
divContainer.InnerHtml += dropdownA;
divContainer.InnerHtml += dropdownUl;
return divContainer.ToString();
}
else
{
button.AddCssClass("btn-default btn pull-right bs-bulkGroupMove");
button.InnerHtml += BsResourceManager.Resource("BF_GroupEditorMoveToGroups");
button.InnerHtml += glyph;
button.AddCssClass("bs-moveToGroupBtn");
button.MergeAttribute("data-groupid", MvcHelpers.Serialize(this.Builder.GroupConfigurator.Groups.First().Value.Uid));
return button.ToString();
}
}
return string.Empty;
}
public string RenderIndex()
{
var container = new TagBuilder("div");
container.AddCssClass("group_editor");
if (this.Builder.htmlAttributes != null)
{
container.MergeAttributes(this.Builder.htmlAttributes);
}
#region Left
if (this.Builder.TabConfigurator.Tabs.Any())
{
var left = new TagBuilder("div");
left.AddCssClass("left bs-tabs");
left.InnerHtml += RenderTabs();
container.InnerHtml += left;
}
#endregion
#region Right
if (this.Builder.GroupConfigurator.Groups.Any())
{
var right = new TagBuilder("div");
right.AddCssClass("right bs-groups");
right.InnerHtml += RenderGroups();
right.InnerHtml += RenderGroupsFooter();
container.InnerHtml += right;
}
#endregion
return container.ToString();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
namespace SuperPolarity
{
public class Actor
{
protected SuperPolarity game;
public List<Actor> Children;
// In-Game Properties
public bool Active;
public Rectangle Box;
public Vector4 BoxDimensions;
protected Texture2D BoxTexture;
protected Color Color;
// Physical Properties
public Vector2 Position;
public bool Collides;
protected Vector2 Velocity;
protected Vector2 Acceleration;
public float Angle;
// Constraints / Behavior
public float MaxVelocity;
protected float AccelerationRate;
public bool Dying;
public Actor Parent;
public virtual int Width
{
get { return 0; }
}
public virtual int Height
{
get { return 0; }
}
public Actor(SuperPolarity newGame)
{
game = newGame;
BoxDimensions.X = 20;
BoxDimensions.Y = 20;
BoxDimensions.W = 15;
BoxDimensions.Z = 15;
}
public virtual void Initialize(Vector2 position)
{
Position = position;
Active = true;
Collides = false;
Children = new List<Actor>();
Velocity = new Vector2(0, 0);
Acceleration = new Vector2(0, 0);
MaxVelocity = 5;
AccelerationRate = 10;
Dying = false;
InitBox();
BoxTexture = new Texture2D(game.GraphicsDevice, 1, 1);
BoxTexture.SetData(new Color[] { Color.White });
Color = Color.White;
}
protected void InitBox()
{
Box = new Rectangle((int)(Position.X - BoxDimensions.X), (int)(Position.Y - BoxDimensions.X), (int)(BoxDimensions.X + BoxDimensions.X + BoxDimensions.W), (int)(BoxDimensions.Y + BoxDimensions.Y + BoxDimensions.Z));
}
public void AutoDeccelerate(GameTime gameTime)
{
if (Acceleration.X == 0 && Velocity.X > 0)
{
if (AccelerationRate * gameTime.ElapsedGameTime.TotalSeconds > Velocity.X)
{
Velocity.X = 0;
Acceleration.X = 0;
}
else
{
Acceleration.X = -AccelerationRate;
}
}
if (Acceleration.X == 0 && Velocity.X < 0)
{
if (-AccelerationRate * gameTime.ElapsedGameTime.TotalSeconds < Velocity.X)
{
Velocity.X = 0;
Acceleration.X = 0;
}
else
{
Acceleration.X = AccelerationRate;
}
}
if (Acceleration.Y == 0 && Velocity.Y > 0)
{
if (AccelerationRate * gameTime.ElapsedGameTime.TotalSeconds > Velocity.Y)
{
Velocity.Y = 0;
Acceleration.Y = 0;
}
else
{
Acceleration.Y = -AccelerationRate;
}
}
if (Acceleration.Y == 0 && Velocity.Y < 0)
{
if (-AccelerationRate * gameTime.ElapsedGameTime.TotalSeconds < Velocity.Y)
{
Velocity.Y = 0;
Acceleration.Y = 0;
}
else
{
Acceleration.Y = AccelerationRate;
}
}
}
public virtual void Update(GameTime gameTime)
{
Move(gameTime);
ChangeAngle();
CheckOutliers();
UpdateBox ();
}
protected virtual void UpdateBox()
{
Box.X = (int)(Position.X - BoxDimensions.X);
Box.Y = (int)(Position.Y - BoxDimensions.Y);
}
public virtual void Move(GameTime gameTime)
{
AutoDeccelerate(gameTime);
Velocity.X = Velocity.X + Acceleration.X * (float)gameTime.ElapsedGameTime.TotalSeconds;
Velocity.Y = Velocity.Y + Acceleration.Y * (float)gameTime.ElapsedGameTime.TotalSeconds;
if (Velocity.X > MaxVelocity)
{
Velocity.X = MaxVelocity;
}
if (Velocity.X < -MaxVelocity)
{
Velocity.X = -MaxVelocity;
}
if (Velocity.Y > MaxVelocity)
{
Velocity.Y = MaxVelocity;
}
if (Velocity.Y < -MaxVelocity)
{
Velocity.Y = -MaxVelocity;
}
Position.X = Position.X + Velocity.X;
Position.Y = Position.Y + Velocity.Y;
}
public void ChangeAngle()
{
if (Math.Abs(Velocity.Y) <= 0.1 && Math.Abs(Velocity.X) <= 0.1)
{
return;
}
Angle = (float)Math.Atan2(Velocity.Y, Velocity.X);
}
public virtual void Draw(SpriteBatch spriteBatch)
{
Actor child = null;
// TODO: Check what's up with the null children.
if (Children == null)
{
return;
}
for (var i = Children.Count - 1; i >= 0; i--)
{
child = Children[i];
child.Draw(spriteBatch);
}
//spriteBatch.Draw(BoxTexture, Box, new Color(255, 0, 255, 25));
}
void CheckOutliers()
{
for (var i = Children.Count; i > 0; i--)
{
var actor = Children[i - 1];
if (actor.Position.X < -SuperPolarity.OutlierBounds || actor.Position.Y < -SuperPolarity.OutlierBounds ||
actor.Position.X > game.GraphicsDevice.Viewport.Width + SuperPolarity.OutlierBounds ||
actor.Position.Y > game.GraphicsDevice.Viewport.Height + SuperPolarity.OutlierBounds)
{
Children.Remove(actor);
}
}
}
public virtual void Collide(Actor other, Rectangle collision)
{
}
protected virtual void Die()
{
Dying = true;
}
public virtual void CleanUp()
{
BoxTexture = null;
Children = null;
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.DataFactories.Common.Models;
using Microsoft.Azure.Management.DataFactories.Core;
using Microsoft.Azure.Management.DataFactories.Models;
namespace Microsoft.Azure.Management.DataFactories.Core
{
public static partial class GatewayOperationsExtensions
{
/// <summary>
/// Create or update a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory gateway.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static GatewayCreateOrUpdateResponse BeginCreateOrUpdate(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory gateway.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static Task<GatewayCreateOrUpdateResponse> BeginCreateOrUpdateAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway to delete.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static LongRunningOperationResponse BeginDelete(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).BeginDeleteAsync(resourceGroupName, dataFactoryName, gatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway to delete.
/// </param>
/// <returns>
/// A standard service response for long running operations.
/// </returns>
public static Task<LongRunningOperationResponse> BeginDeleteAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return operations.BeginDeleteAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None);
}
/// <summary>
/// Create or update a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory gateway.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static GatewayCreateOrUpdateResponse CreateOrUpdate(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create or update a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory gateway.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static Task<GatewayCreateOrUpdateResponse> CreateOrUpdateAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
/// <summary>
/// Delete a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).DeleteAsync(resourceGroupName, dataFactoryName, gatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway to delete.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return operations.DeleteAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None);
}
/// <summary>
/// Gets a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway to get.
/// </param>
/// <returns>
/// The Get data factory gateway operation response.
/// </returns>
public static GatewayGetResponse Get(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).GetAsync(resourceGroupName, dataFactoryName, gatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway to get.
/// </param>
/// <returns>
/// The Get data factory gateway operation response.
/// </returns>
public static Task<GatewayGetResponse> GetAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return operations.GetAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None);
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static GatewayCreateOrUpdateResponse GetCreateOrUpdateStatus(this IGatewayOperations operations, string operationStatusLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).GetCreateOrUpdateStatusAsync(operationStatusLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling an asynchronous operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, or is still in progress.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='operationStatusLink'>
/// Required. Location value returned by the Begin operation.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static Task<GatewayCreateOrUpdateResponse> GetCreateOrUpdateStatusAsync(this IGatewayOperations operations, string operationStatusLink)
{
return operations.GetCreateOrUpdateStatusAsync(operationStatusLink, CancellationToken.None);
}
/// <summary>
/// List all gateways under a data factory.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <returns>
/// The List data factory gateways operation response.
/// </returns>
public static GatewayListResponse List(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).ListAsync(resourceGroupName, dataFactoryName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// List all gateways under a data factory.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <returns>
/// The List data factory gateways operation response.
/// </returns>
public static Task<GatewayListResponse> ListAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName)
{
return operations.ListAsync(resourceGroupName, dataFactoryName, CancellationToken.None);
}
/// <summary>
/// Regenerate gateway key.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. The name of the gateway to regenerate key.
/// </param>
/// <returns>
/// The regenerate gateway key operation response.
/// </returns>
public static GatewayRegenerateKeyResponse RegenerateKey(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).RegenerateKeyAsync(resourceGroupName, dataFactoryName, gatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerate gateway key.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. The name of the gateway to regenerate key.
/// </param>
/// <returns>
/// The regenerate gateway key operation response.
/// </returns>
public static Task<GatewayRegenerateKeyResponse> RegenerateKeyAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return operations.RegenerateKeyAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None);
}
/// <summary>
/// Retrieve gateway connection information.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway.
/// </param>
/// <returns>
/// The retrieve gateway connection information operation response.
/// </returns>
public static GatewayConnectionInfoRetrieveResponse RetrieveConnectionInfo(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).RetrieveConnectionInfoAsync(resourceGroupName, dataFactoryName, gatewayName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve gateway connection information.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='gatewayName'>
/// Required. Name of the gateway.
/// </param>
/// <returns>
/// The retrieve gateway connection information operation response.
/// </returns>
public static Task<GatewayConnectionInfoRetrieveResponse> RetrieveConnectionInfoAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, string gatewayName)
{
return operations.RetrieveConnectionInfoAsync(resourceGroupName, dataFactoryName, gatewayName, CancellationToken.None);
}
/// <summary>
/// Update a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory gateway.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static GatewayCreateOrUpdateResponse Update(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IGatewayOperations)s).UpdateAsync(resourceGroupName, dataFactoryName, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Update a data factory gateway.
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.DataFactories.Core.IGatewayOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The resource group name of the data factory.
/// </param>
/// <param name='dataFactoryName'>
/// Required. A unique data factory instance name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters required to create or update a data
/// factory gateway.
/// </param>
/// <returns>
/// The create or update data factory gateway operation response.
/// </returns>
public static Task<GatewayCreateOrUpdateResponse> UpdateAsync(this IGatewayOperations operations, string resourceGroupName, string dataFactoryName, GatewayCreateOrUpdateParameters parameters)
{
return operations.UpdateAsync(resourceGroupName, dataFactoryName, parameters, CancellationToken.None);
}
}
}
| |
// 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.Concurrent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Concurrent.Tests
{
/// <summary>The class that contains the unit tests of the LazyInit.</summary>
public class ConcurrentBagTests
{
[Fact]
public static void TestBasicScenarios()
{
ConcurrentBag<int> cb = new ConcurrentBag<int>();
Task[] tks = new Task[2];
tks[0] = Task.Run(() =>
{
cb.Add(4);
cb.Add(5);
cb.Add(6);
});
// Consume the items in the bag
tks[1] = Task.Run(() =>
{
int item;
while (!cb.IsEmpty)
{
bool ret = cb.TryTake(out item);
Assert.True(ret);
// loose check
if (item != 4 && item != 5 && item != 6)
{
Assert.False(true, "Expected: 4|5|6; actual: " + item.ToString());
}
}
});
Task.WaitAll(tks);
}
[Fact]
public static void RTest1_Ctor()
{
ConcurrentBag<int> bag = new ConcurrentBag<int>(new int[] { 1, 2, 3 });
Assert.False(bag.IsEmpty);
Assert.Equal(3, bag.Count);
Assert.Throws<ArgumentNullException>( () => {bag = new ConcurrentBag<int>(null);} );
}
[Fact]
public static void RTest2_Add()
{
RTest2_Add(1, 10);
RTest2_Add(3, 100);
}
[Fact]
[OuterLoop]
public static void RTest2_Add01()
{
RTest2_Add(8, 1000);
}
[Fact]
public static void RTest3_TakeOrPeek()
{
ConcurrentBag<int> bag = CreateBag(100);
RTest3_TakeOrPeek(bag, 1, 100, true);
bag = CreateBag(100);
RTest3_TakeOrPeek(bag, 4, 10, false);
bag = CreateBag(1000);
RTest3_TakeOrPeek(bag, 11, 100, true);
}
[Fact]
public static void RTest4_AddAndTake()
{
RTest4_AddAndTake(8);
RTest4_AddAndTake(16);
}
[Fact]
public static void RTest5_CopyTo()
{
const int SIZE = 10;
Array array = new int[SIZE];
int index = 0;
ConcurrentBag<int> bag = CreateBag(SIZE);
bag.CopyTo((int[])array, index);
Assert.Throws<ArgumentNullException>(() => bag.CopyTo(null, index));
Assert.Throws<ArgumentOutOfRangeException>(() => bag.CopyTo((int[]) array, -1));
Assert.Throws<ArgumentException>(() => bag.CopyTo((int[])array, SIZE));
Assert.Throws<ArgumentException>(() => bag.CopyTo((int[])array, SIZE-2));
}
[Fact]
public static void RTest5_ICollectionCopyTo()
{
const int SIZE = 10;
Array array = new int[SIZE];
int index = 0;
ConcurrentBag<int> bag = CreateBag(SIZE);
ICollection collection = bag as ICollection;
Assert.NotNull(collection);
collection.CopyTo(array, index);
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, index));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo((int[])array, -1));
Assert.Throws<ArgumentException>(() => collection.CopyTo((int[])array, SIZE));
Assert.Throws<ArgumentException>(() => collection.CopyTo((int[])array, SIZE - 2));
Array array2 = new int[SIZE, 5];
Assert.Throws<ArgumentException>(() => collection.CopyTo(array2, 0));
}
/// <summary>
/// Test bag addition
/// </summary>
/// <param name="threadsCount"></param>
/// <param name="itemsPerThread"></param>
/// <returns>True if succeeded, false otherwise</returns>
private static void RTest2_Add(int threadsCount, int itemsPerThread)
{
int failures = 0;
ConcurrentBag<int> bag = new ConcurrentBag<int>();
Task[] threads = new Task[threadsCount];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = Task.Run(() =>
{
for (int j = 0; j < itemsPerThread; j++)
{
try
{
bag.Add(j);
int item;
if (!bag.TryPeek(out item) || item != j)
{
Interlocked.Increment(ref failures);
}
}
catch
{
Interlocked.Increment(ref failures);
}
}
});
}
Task.WaitAll(threads);
Assert.Equal(0, failures);
Assert.Equal(itemsPerThread * threadsCount, bag.Count);
}
/// <summary>
/// Test bag Take and Peek operations
/// </summary>
/// <param name="bag"></param>
/// <param name="threadsCount"></param>
/// <param name="itemsPerThread"></param>
/// <param name="take"></param>
/// <returns>True if succeeded, false otherwise</returns>
private static void RTest3_TakeOrPeek(ConcurrentBag<int> bag, int threadsCount, int itemsPerThread, bool take)
{
int bagCount = bag.Count;
int succeeded = 0;
int failures = 0;
Task[] threads = new Task[threadsCount];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = Task.Run(() =>
{
for (int j = 0; j < itemsPerThread; j++)
{
int data;
bool result = false;
if (take)
{
result = bag.TryTake(out data);
}
else
{
result = bag.TryPeek(out data);
}
if (result)
{
Interlocked.Increment(ref succeeded);
}
else
{
Interlocked.Increment(ref failures);
}
}
});
}
Task.WaitAll(threads);
if (take)
{
if (bag.Count != bagCount - succeeded)
{
Console.WriteLine("* RTest3_TakeOrPeek(" + threadsCount + "," + itemsPerThread + ")");
Assert.False(true, "TryTake failed, the remaining count doesn't match the expected count");
}
}
else
{
Assert.Equal(0, failures);
}
}
/// <summary>
/// Test parallel Add/Take, insert uniqe elements in the bag, and each element should be removed once
/// </summary>
/// <param name="threadsCount"></param>
/// <returns>True if succeeded, false otherwise</returns>
private static void RTest4_AddAndTake(int threadsCount)
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
Task[] threads = new Task[threadsCount];
int start = 0;
int end = 10;
int[] validation = new int[(end - start) * threads.Length / 2];
for (int i = 0; i < threads.Length; i += 2)
{
Interval v = new Interval(start, end);
threads[i] = Task.Factory.StartNew(
(o) =>
{
Interval n = (Interval)o;
Add(bag, n.m_start, n.m_end);
}, v, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
threads[i + 1] = Task.Run(() => Take(bag, end - start - 1, validation));
int step = end - start;
start = end;
end += step;
}
Task.WaitAll(threads);
int valu = -1;
//validation
for (int i = 0; i < validation.Length; i++)
{
if (validation[i] > 1)
{
Console.WriteLine("* RTest4_AddAndTake(" + threadsCount + " )");
Assert.False(true, "Add/Take failed, item " + i + " has been taken more than once");
}
else if (validation[i] == 0)
{
Assert.True(bag.TryTake(out valu), String.Format("Add/Take failed, the list is not empty and TryTake returned false; thread count={0}", threadsCount));
}
}
Assert.False(bag.Count > 0 || bag.TryTake(out valu), String.Format("Add/Take failed, this list is not empty after all remove operations; thread count={0}", threadsCount));
}
[Fact]
public static void RTest6_GetEnumerator()
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
foreach (int x in bag)
{
Assert.False(true, "RTest6_GetEnumerator: GetEnumeration failed, returned items when the bag is empty");
}
for (int i = 0; i < 100; i++)
{
bag.Add(i);
}
int count = 0;
foreach (int x in bag)
{
count++;
}
Assert.Equal(count, bag.Count);
}
[Fact]
public static void RTest7_BugFix575975()
{
BlockingCollection<int> bc = new BlockingCollection<int>(new ConcurrentBag<int>());
bool succeeded = true;
Task[] threads = new Task[4];
for (int t = 0; t < threads.Length; t++)
{
threads[t] = Task.Factory.StartNew((obj) =>
{
int index = (int)obj;
for (int i = 0; i < 100000; i++)
{
if (index < threads.Length / 2)
{
int k = 0;
for (int j = 0; j < 1000; j++)
k++;
bc.Add(i);
}
else
{
try
{
bc.Take();
}
catch // Take must not fail
{
succeeded = false;
break;
}
}
}
}, t, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
Task.WaitAll(threads);
Assert.True(succeeded);
}
[Fact]
public static void RTest8_Interfaces()
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
//IPCC
IProducerConsumerCollection<int> ipcc = bag as IProducerConsumerCollection<int>;
Assert.False(ipcc == null, "RTest8_Interfaces: ConcurrentBag<T> doesn't implement IPCC<T>");
Assert.True(ipcc.TryAdd(1), "RTest8_Interfaces: IPCC<T>.TryAdd failed");
Assert.Equal(1, bag.Count);
int result = -1;
Assert.True(ipcc.TryTake(out result), "RTest8_Interfaces: IPCC<T>.TryTake failed");
Assert.True(1 == result, "RTest8_Interfaces: IPCC<T>.TryTake failed");
Assert.Equal(0, bag.Count);
//ICollection
ICollection collection = bag as ICollection;
Assert.False(collection == null, "RTest8_Interfaces: ConcurrentBag<T> doesn't implement ICollection");
Assert.False(collection.IsSynchronized, "RTest8_Interfaces: IsSynchronized returned true");
//IEnumerable
IEnumerable enumerable = bag as IEnumerable;
Assert.False(enumerable == null, "RTest8_Interfaces: ConcurrentBag<T> doesn't implement IEnumerable");
foreach (object o in enumerable)
{
Assert.True(false, "RTest8_Interfaces: Enumerable returned items when the bag is empty");
}
}
[Fact]
public static void RTest8_Interfaces_Negative()
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
//IPCC
IProducerConsumerCollection<int> ipcc = bag as IProducerConsumerCollection<int>;
ICollection collection = bag as ICollection;
Assert.Throws<NotSupportedException>(() => { object obj = collection.SyncRoot; });
}
[Fact]
public static void RTest9_ToArray()
{
var bag = new ConcurrentBag<int>();
Assert.NotNull(bag.ToArray());
Assert.Equal(0, bag.ToArray().Length);
int[] allItems = new int[10000];
for (int i = 0; i < allItems.Length; i++)
allItems[i] = i;
bag = new ConcurrentBag<int>(allItems);
int failCount = 0;
Task[] tasks = new Task[10];
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = Task.Run(() =>
{
int[] array = bag.ToArray();
if (array == null || array.Length != 10000)
Interlocked.Increment(ref failCount);
});
}
Task.WaitAll(tasks);
Assert.True(0 == failCount, "RTest9_ToArray: One or more thread failed to get the correct bag items from ToArray");
}
#region Helper Methods / Classes
private struct Interval
{
public Interval(int start, int end)
{
m_start = start;
m_end = end;
}
internal int m_start;
internal int m_end;
}
/// <summary>
/// Create a ComcurrentBag object
/// </summary>
/// <param name="numbers">number of the elements in the bag</param>
/// <returns>The bag object</returns>
private static ConcurrentBag<int> CreateBag(int numbers)
{
ConcurrentBag<int> bag = new ConcurrentBag<int>();
for (int i = 0; i < numbers; i++)
{
bag.Add(i);
}
return bag;
}
private static void Add(ConcurrentBag<int> bag, int start, int end)
{
for (int i = start; i < end; i++)
{
bag.Add(i);
}
}
private static void Take(ConcurrentBag<int> bag, int count, int[] validation)
{
for (int i = 0; i < count; i++)
{
int valu = -1;
if (bag.TryTake(out valu) && validation != null)
{
Interlocked.Increment(ref validation[valu]);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace SimpleInjectorWithWebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="Rule.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the Rule class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
/// <summary>
/// Represents a rule that automatically handles incoming messages.
/// A rule consists of a set of conditions and exceptions that determine whether or
/// not a set of actions should be executed on incoming messages.
/// </summary>
public sealed class Rule : ComplexProperty
{
/// <summary>
/// The rule ID.
/// </summary>
private string ruleId;
/// <summary>
/// The rule display name.
/// </summary>
private string displayName;
/// <summary>
/// The rule priority.
/// </summary>
private int priority;
/// <summary>
/// The rule status of enabled or not.
/// </summary>
private bool isEnabled;
/// <summary>
/// The rule status of is supported or not.
/// </summary>
private bool isNotSupported;
/// <summary>
/// The rule status of in error or not.
/// </summary>
private bool isInError;
/// <summary>
/// The rule conditions.
/// </summary>
private RulePredicates conditions;
/// <summary>
/// The rule actions.
/// </summary>
private RuleActions actions;
/// <summary>
/// The rule exceptions.
/// </summary>
private RulePredicates exceptions;
/// <summary>
/// Initializes a new instance of the <see cref="Rule"/> class.
/// </summary>
public Rule()
: base()
{
//// New rule has priority as 0 by default
this.priority = 1;
//// New rule is enabled by default
this.isEnabled = true;
this.conditions = new RulePredicates();
this.actions = new RuleActions();
this.exceptions = new RulePredicates();
}
/// <summary>
/// Gets or sets the Id of this rule.
/// </summary>
public string Id
{
get
{
return this.ruleId;
}
set
{
this.SetFieldValue<string>(ref this.ruleId, value);
}
}
/// <summary>
/// Gets or sets the name of this rule as it should be displayed to the user.
/// </summary>
public string DisplayName
{
get
{
return this.displayName;
}
set
{
this.SetFieldValue<string>(ref this.displayName, value);
}
}
/// <summary>
/// Gets or sets the priority of this rule, which determines its execution order.
/// </summary>
public int Priority
{
get
{
return this.priority;
}
set
{
this.SetFieldValue<int>(ref this.priority, value);
}
}
/// <summary>
/// Gets or sets a value indicating whether this rule is enabled.
/// </summary>
public bool IsEnabled
{
get
{
return this.isEnabled;
}
set
{
this.SetFieldValue<bool>(ref this.isEnabled, value);
}
}
/// <summary>
/// Gets a value indicating whether this rule can be modified via EWS.
/// If IsNotSupported is true, the rule cannot be modified via EWS.
/// </summary>
public bool IsNotSupported
{
get
{
return this.isNotSupported;
}
}
/// <summary>
/// Gets or sets a value indicating whether this rule has errors. A rule that is in error
/// cannot be processed unless it is updated and the error is corrected.
/// </summary>
public bool IsInError
{
get
{
return this.isInError;
}
set
{
this.SetFieldValue<bool>(ref this.isInError, value);
}
}
/// <summary>
/// Gets the conditions that determine whether or not this rule should be
/// executed against incoming messages.
/// </summary>
public RulePredicates Conditions
{
get
{
return this.conditions;
}
}
/// <summary>
/// Gets the actions that should be executed against incoming messages if the
/// conditions evaluate as true.
/// </summary>
public RuleActions Actions
{
get
{
return this.actions;
}
}
/// <summary>
/// Gets the exceptions that determine if this rule should be skipped even if
/// its conditions evaluate to true.
/// </summary>
public RulePredicates Exceptions
{
get
{
return this.exceptions;
}
}
/// <summary>
/// Tries to read element from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <returns>True if element was read.</returns>
internal override bool TryReadElementFromXml(EwsServiceXmlReader reader)
{
switch (reader.LocalName)
{
case XmlElementNames.DisplayName:
this.displayName = reader.ReadElementValue();
return true;
case XmlElementNames.RuleId:
this.ruleId = reader.ReadElementValue();
return true;
case XmlElementNames.Priority:
this.priority = reader.ReadElementValue<int>();
return true;
case XmlElementNames.IsEnabled:
this.isEnabled = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.IsNotSupported:
this.isNotSupported = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.IsInError:
this.isInError = reader.ReadElementValue<bool>();
return true;
case XmlElementNames.Conditions:
this.conditions.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.Actions:
this.actions.LoadFromXml(reader, reader.LocalName);
return true;
case XmlElementNames.Exceptions:
this.exceptions.LoadFromXml(reader, reader.LocalName);
return true;
default:
return false;
}
}
/// <summary>
/// Loads from json.
/// </summary>
/// <param name="jsonProperty">The json property.</param>
/// <param name="service">The service.</param>
internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service)
{
foreach (string key in jsonProperty.Keys)
{
switch (key)
{
case XmlElementNames.DisplayName:
this.displayName = jsonProperty.ReadAsString(key);
break;
case XmlElementNames.RuleId:
this.ruleId = jsonProperty.ReadAsString(key);
break;
case XmlElementNames.Priority:
this.priority = jsonProperty.ReadAsInt(key);
break;
case XmlElementNames.IsEnabled:
this.isEnabled = jsonProperty.ReadAsBool(key);
break;
case XmlElementNames.IsNotSupported:
this.isNotSupported = jsonProperty.ReadAsBool(key);
break;
case XmlElementNames.IsInError:
this.isInError = jsonProperty.ReadAsBool(key);
break;
case XmlElementNames.Conditions:
this.conditions.LoadFromJson(jsonProperty, service);
break;
case XmlElementNames.Actions:
this.actions.LoadFromJson(jsonProperty, service);
break;
case XmlElementNames.Exceptions:
this.exceptions.LoadFromJson(jsonProperty, service);
break;
default:
break;
}
}
}
/// <summary>
/// Writes elements to XML.
/// </summary>
/// <param name="writer">The writer.</param>
internal override void WriteElementsToXml(EwsServiceXmlWriter writer)
{
if (!string.IsNullOrEmpty(this.Id))
{
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.RuleId,
this.Id);
}
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.DisplayName,
this.DisplayName);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.Priority,
this.Priority);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.IsEnabled,
this.IsEnabled);
writer.WriteElementValue(
XmlNamespace.Types,
XmlElementNames.IsInError,
this.IsInError);
this.Conditions.WriteToXml(writer, XmlElementNames.Conditions);
this.Exceptions.WriteToXml(writer, XmlElementNames.Exceptions);
this.Actions.WriteToXml(writer, XmlElementNames.Actions);
}
/// <summary>
/// Serializes the property to a Json value.
/// </summary>
/// <param name="service">The service.</param>
/// <returns>
/// A Json value (either a JsonObject, an array of Json values, or a Json primitive)
/// </returns>
internal override object InternalToJson(ExchangeService service)
{
JsonObject jsonProperty = new JsonObject();
if (!string.IsNullOrEmpty(this.Id))
{
jsonProperty.Add(XmlElementNames.RuleId, this.Id);
}
jsonProperty.Add(XmlElementNames.DisplayName, this.DisplayName);
jsonProperty.Add(XmlElementNames.Priority, this.Priority);
jsonProperty.Add(XmlElementNames.IsEnabled, this.IsEnabled);
jsonProperty.Add(XmlElementNames.IsInError, this.IsInError);
jsonProperty.Add(XmlElementNames.Conditions, this.Conditions.InternalToJson(service));
jsonProperty.Add(XmlElementNames.Exceptions, this.Exceptions.InternalToJson(service));
jsonProperty.Add(XmlElementNames.Actions, this.Actions.InternalToJson(service));
return jsonProperty;
}
/// <summary>
/// Validates this instance.
/// </summary>
internal override void InternalValidate()
{
base.InternalValidate();
EwsUtilities.ValidateParam(this.displayName, "DisplayName");
EwsUtilities.ValidateParam(this.conditions, "Conditions");
EwsUtilities.ValidateParam(this.exceptions, "Exceptions");
EwsUtilities.ValidateParam(this.actions, "Actions");
}
}
}
| |
#region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Grpc.Core.Internal;
using NUnit.Framework;
namespace Grpc.Core.Internal.Tests
{
/// <summary>
/// Uses fake native call to test interaction of <c>AsyncCall</c> wrapping code with C core in different situations.
/// </summary>
public class AsyncCallTest
{
Channel channel;
FakeNativeCall fakeCall;
AsyncCall<string, string> asyncCall;
[SetUp]
public void Init()
{
channel = new Channel("localhost", ChannelCredentials.Insecure);
fakeCall = new FakeNativeCall();
var callDetails = new CallInvocationDetails<string, string>(channel, "someMethod", null, Marshallers.StringMarshaller, Marshallers.StringMarshaller, new CallOptions());
asyncCall = new AsyncCall<string, string>(callDetails, fakeCall);
}
[TearDown]
public void Cleanup()
{
channel.ShutdownAsync().Wait();
}
[Test]
public void AsyncUnary_CanBeStartedOnlyOnce()
{
asyncCall.UnaryCallAsync("request1");
Assert.Throws(typeof(InvalidOperationException),
() => asyncCall.UnaryCallAsync("abc"));
}
[Test]
public void AsyncUnary_StreamingOperationsNotAllowed()
{
asyncCall.UnaryCallAsync("request1");
Assert.ThrowsAsync(typeof(InvalidOperationException),
async () => await asyncCall.ReadMessageAsync());
Assert.Throws(typeof(InvalidOperationException),
() => asyncCall.SendMessageAsync("abc", new WriteFlags()));
}
[Test]
public void AsyncUnary_Success()
{
var resultTask = asyncCall.UnaryCallAsync("request1");
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void AsyncUnary_NonSuccessStatusCode()
{
var resultTask = asyncCall.UnaryCallAsync("request1");
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.InvalidArgument),
null,
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.InvalidArgument);
}
[Test]
public void AsyncUnary_NullResponsePayload()
{
var resultTask = asyncCall.UnaryCallAsync("request1");
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
null,
new Metadata());
// failure to deserialize will result in InvalidArgument status.
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Internal);
}
[Test]
public void ClientStreaming_StreamingReadNotAllowed()
{
asyncCall.ClientStreamingCallAsync();
Assert.ThrowsAsync(typeof(InvalidOperationException),
async () => await asyncCall.ReadMessageAsync());
}
[Test]
public void ClientStreaming_NoRequest_Success()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void ClientStreaming_NoRequest_NonSuccessStatusCode()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.InvalidArgument),
null,
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.InvalidArgument);
}
[Test]
public void ClientStreaming_MoreRequests_Success()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
fakeCall.SendCompletionHandler(true);
writeTask.Wait();
var writeTask2 = requestStream.WriteAsync("request2");
fakeCall.SendCompletionHandler(true);
writeTask2.Wait();
var completeTask = requestStream.CompleteAsync();
fakeCall.SendCompletionHandler(true);
completeTask.Wait();
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void ClientStreaming_WriteFailureThrowsRpcException()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
fakeCall.SendCompletionHandler(false);
// The write will wait for call to finish to receive the status code.
Assert.IsFalse(writeTask.IsCompleted);
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.Internal),
null,
new Metadata());
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(StatusCode.Internal, ex.Status.StatusCode);
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Internal);
}
[Test]
public void ClientStreaming_WriteFailureThrowsRpcException2()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.Internal),
null,
new Metadata());
fakeCall.SendCompletionHandler(false);
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(StatusCode.Internal, ex.Status.StatusCode);
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Internal);
}
[Test]
public void ClientStreaming_WriteFailureThrowsRpcException3()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
fakeCall.SendCompletionHandler(false);
// Until the delayed write completion has been triggered,
// we still act as if there was an active write.
Assert.Throws(typeof(InvalidOperationException), () => requestStream.WriteAsync("request2"));
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.Internal),
null,
new Metadata());
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(StatusCode.Internal, ex.Status.StatusCode);
// Following attempts to write keep delivering the same status
var ex2 = Assert.ThrowsAsync<RpcException>(async () => await requestStream.WriteAsync("after call has finished"));
Assert.AreEqual(StatusCode.Internal, ex2.Status.StatusCode);
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Internal);
}
[Test]
public void ClientStreaming_WriteAfterReceivingStatusThrowsRpcException()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
var writeTask = requestStream.WriteAsync("request1");
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(Status.DefaultSuccess, ex.Status);
}
[Test]
public void ClientStreaming_WriteAfterReceivingStatusThrowsRpcException2()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(new Status(StatusCode.OutOfRange, ""), new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.OutOfRange);
var writeTask = requestStream.WriteAsync("request1");
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(StatusCode.OutOfRange, ex.Status.StatusCode);
}
[Test]
public void ClientStreaming_WriteAfterCompleteThrowsInvalidOperationException()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
requestStream.CompleteAsync();
Assert.Throws(typeof(InvalidOperationException), () => requestStream.WriteAsync("request1"));
fakeCall.SendCompletionHandler(true);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
}
[Test]
public void ClientStreaming_CompleteAfterReceivingStatusSucceeds()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
fakeCall.UnaryResponseClientHandler(true,
new ClientSideStatus(Status.DefaultSuccess, new Metadata()),
CreateResponsePayload(),
new Metadata());
AssertUnaryResponseSuccess(asyncCall, fakeCall, resultTask);
Assert.DoesNotThrowAsync(async () => await requestStream.CompleteAsync());
}
[Test]
public void ClientStreaming_WriteAfterCancellationRequestThrowsTaskCanceledException()
{
var resultTask = asyncCall.ClientStreamingCallAsync();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
var writeTask = requestStream.WriteAsync("request1");
Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await writeTask);
fakeCall.UnaryResponseClientHandler(true,
CreateClientSideStatus(StatusCode.Cancelled),
null,
new Metadata());
AssertUnaryResponseError(asyncCall, fakeCall, resultTask, StatusCode.Cancelled);
}
[Test]
public void ServerStreaming_StreamingSendNotAllowed()
{
asyncCall.StartServerStreamingCall("request1");
Assert.Throws(typeof(InvalidOperationException),
() => asyncCall.SendMessageAsync("abc", new WriteFlags()));
}
[Test]
public void ServerStreaming_NoResponse_Success1()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedResponseHeadersHandler(true, new Metadata());
Assert.AreEqual(0, asyncCall.ResponseHeadersAsync.Result.Count);
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
}
[Test]
public void ServerStreaming_NoResponse_Success2()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
// try alternative order of completions
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
fakeCall.ReceivedMessageHandler(true, null);
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
}
[Test]
public void ServerStreaming_NoResponse_ReadFailure()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(false, null); // after a failed read, we rely on C core to deliver appropriate status code.
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Internal));
AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.Internal);
}
[Test]
public void ServerStreaming_MoreResponses_Success()
{
asyncCall.StartServerStreamingCall("request1");
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask1 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask1.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask2 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask2.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask3 = responseStream.MoveNext();
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
fakeCall.ReceivedMessageHandler(true, null);
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask3);
}
[Test]
public void DuplexStreaming_NoRequestNoResponse_Success()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var writeTask1 = requestStream.CompleteAsync();
fakeCall.SendCompletionHandler(true);
Assert.DoesNotThrowAsync(async () => await writeTask1);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
}
[Test]
public void DuplexStreaming_WriteAfterReceivingStatusThrowsRpcException()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
var writeTask = requestStream.WriteAsync("request1");
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(Status.DefaultSuccess, ex.Status);
}
[Test]
public void DuplexStreaming_CompleteAfterReceivingStatusSuceeds()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, new ClientSideStatus(Status.DefaultSuccess, new Metadata()));
AssertStreamingResponseSuccess(asyncCall, fakeCall, readTask);
Assert.DoesNotThrowAsync(async () => await requestStream.CompleteAsync());
}
[Test]
public void DuplexStreaming_WriteFailureThrowsRpcException()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
fakeCall.SendCompletionHandler(false);
// The write will wait for call to finish to receive the status code.
Assert.IsFalse(writeTask.IsCompleted);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.PermissionDenied));
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(StatusCode.PermissionDenied, ex.Status.StatusCode);
AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.PermissionDenied);
}
[Test]
public void DuplexStreaming_WriteFailureThrowsRpcException2()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var writeTask = requestStream.WriteAsync("request1");
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.PermissionDenied));
fakeCall.SendCompletionHandler(false);
var ex = Assert.ThrowsAsync<RpcException>(async () => await writeTask);
Assert.AreEqual(StatusCode.PermissionDenied, ex.Status.StatusCode);
AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.PermissionDenied);
}
[Test]
public void DuplexStreaming_WriteAfterCancellationRequestThrowsTaskCanceledException()
{
asyncCall.StartDuplexStreamingCall();
var requestStream = new ClientRequestStream<string, string>(asyncCall);
var responseStream = new ClientResponseStream<string, string>(asyncCall);
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
var writeTask = requestStream.WriteAsync("request1");
Assert.ThrowsAsync(typeof(TaskCanceledException), async () => await writeTask);
var readTask = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled));
AssertStreamingResponseError(asyncCall, fakeCall, readTask, StatusCode.Cancelled);
}
[Test]
public void DuplexStreaming_ReadAfterCancellationRequestCanSucceed()
{
asyncCall.StartDuplexStreamingCall();
var responseStream = new ClientResponseStream<string, string>(asyncCall);
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
var readTask1 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask1.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask2 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled));
AssertStreamingResponseError(asyncCall, fakeCall, readTask2, StatusCode.Cancelled);
}
[Test]
public void DuplexStreaming_ReadStartedBeforeCancellationRequestCanSucceed()
{
asyncCall.StartDuplexStreamingCall();
var responseStream = new ClientResponseStream<string, string>(asyncCall);
var readTask1 = responseStream.MoveNext(); // initiate the read before cancel request
asyncCall.Cancel();
Assert.IsTrue(fakeCall.IsCancelled);
fakeCall.ReceivedMessageHandler(true, CreateResponsePayload());
Assert.IsTrue(readTask1.Result);
Assert.AreEqual("response1", responseStream.Current);
var readTask2 = responseStream.MoveNext();
fakeCall.ReceivedMessageHandler(true, null);
fakeCall.ReceivedStatusOnClientHandler(true, CreateClientSideStatus(StatusCode.Cancelled));
AssertStreamingResponseError(asyncCall, fakeCall, readTask2, StatusCode.Cancelled);
}
ClientSideStatus CreateClientSideStatus(StatusCode statusCode)
{
return new ClientSideStatus(new Status(statusCode, ""), new Metadata());
}
byte[] CreateResponsePayload()
{
return Marshallers.StringMarshaller.Serializer("response1");
}
static void AssertUnaryResponseSuccess(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<string> resultTask)
{
Assert.IsTrue(resultTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.AreEqual(Status.DefaultSuccess, asyncCall.GetStatus());
Assert.AreEqual(0, asyncCall.ResponseHeadersAsync.Result.Count);
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
Assert.AreEqual("response1", resultTask.Result);
}
static void AssertStreamingResponseSuccess(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<bool> moveNextTask)
{
Assert.IsTrue(moveNextTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.IsFalse(moveNextTask.Result);
Assert.AreEqual(Status.DefaultSuccess, asyncCall.GetStatus());
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
}
static void AssertUnaryResponseError(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<string> resultTask, StatusCode expectedStatusCode)
{
Assert.IsTrue(resultTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
Assert.AreEqual(expectedStatusCode, asyncCall.GetStatus().StatusCode);
var ex = Assert.ThrowsAsync<RpcException>(async () => await resultTask);
Assert.AreEqual(expectedStatusCode, ex.Status.StatusCode);
Assert.AreEqual(0, asyncCall.ResponseHeadersAsync.Result.Count);
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
}
static void AssertStreamingResponseError(AsyncCall<string, string> asyncCall, FakeNativeCall fakeCall, Task<bool> moveNextTask, StatusCode expectedStatusCode)
{
Assert.IsTrue(moveNextTask.IsCompleted);
Assert.IsTrue(fakeCall.IsDisposed);
var ex = Assert.ThrowsAsync<RpcException>(async () => await moveNextTask);
Assert.AreEqual(expectedStatusCode, ex.Status.StatusCode);
Assert.AreEqual(expectedStatusCode, asyncCall.GetStatus().StatusCode);
Assert.AreEqual(0, asyncCall.GetTrailers().Count);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using Xunit.Abstractions;
using System;
using System.IO;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Xsl;
using XmlCoreTest.Common;
namespace System.Xml.Tests
{
public class CSameInstanceXsltArgTestCase : XsltApiTestCaseBase
{
// Variables from init string
protected string _strPath; // Path of the data files
// Other global variables
public XsltArgumentList xsltArg1; // Shared XsltArgumentList for same instance testing
private ITestOutputHelper _output;
public CSameInstanceXsltArgTestCase(ITestOutputHelper output) : base(output)
{
_output = output;
Init(null);
}
public new void Init(object objParam)
{
// Get parameter info
_strPath = Path.Combine("TestFiles", FilePathUtil.GetTestDataPath(), "XsltApi");
xsltArg1 = new XsltArgumentList();
MyObject obj1 = new MyObject(1, _output);
MyObject obj2 = new MyObject(2, _output);
MyObject obj3 = new MyObject(3, _output);
MyObject obj4 = new MyObject(4, _output);
MyObject obj5 = new MyObject(5, _output);
xsltArg1.AddExtensionObject("urn:my-obj1", obj1);
xsltArg1.AddExtensionObject("urn:my-obj2", obj2);
xsltArg1.AddExtensionObject("urn:my-obj3", obj3);
xsltArg1.AddExtensionObject("urn:my-obj4", obj4);
xsltArg1.AddExtensionObject("urn:my-obj5", obj5);
xsltArg1.AddParam("myArg1", szEmpty, "Test1");
xsltArg1.AddParam("myArg2", szEmpty, "Test2");
xsltArg1.AddParam("myArg3", szEmpty, "Test3");
xsltArg1.AddParam("myArg4", szEmpty, "Test4");
xsltArg1.AddParam("myArg5", szEmpty, "Test5");
return;
}
}
//[TestCase(Name = "Same instance testing: XsltArgList - GetParam", Desc = "GetParam test cases")]
public class CSameInstanceXsltArgumentListGetParam : CSameInstanceXsltArgTestCase
{
private ITestOutputHelper _output;
public CSameInstanceXsltArgumentListGetParam(ITestOutputHelper output) : base(output)
{
_output = output;
}
////////////////////////////////////////////////////////////////
// Same instance testing:
// Multiple GetParam() over same ArgumentList
////////////////////////////////////////////////////////////////
public int GetParam1(object args)
{
object retObj;
for (int i = 1; i <= 100; i++)
{
retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty);
_output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", "Test1", retObj.ToString());
if (retObj.ToString() != "Test1")
{
_output.WriteLine("ERROR!!!");
return 0;
}
}
return 1;
}
public int GetParam2(object args)
{
object retObj;
for (int i = 1; i <= 100; i++)
{
retObj = xsltArg1.GetParam(((object[])args)[1].ToString(), szEmpty);
string expected = "Test" + ((object[])args)[0];
_output.WriteLine("GetParam: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tAdded Value: {0}\tRetrieved Value:{1}\n", expected, retObj.ToString());
if (retObj.ToString() != expected)
{
_output.WriteLine("ERROR!!!");
return 0;
}
}
return 1;
}
//[Variation("Multiple GetParam for same parameter name")]
[Fact]
public void proc1()
{
CThreads rThreads = new CThreads(_output);
rThreads.Add(new ThreadFunc(GetParam1), new object[] { 1, "myArg1" });
rThreads.Add(new ThreadFunc(GetParam1), new object[] { 2, "myArg1" });
rThreads.Add(new ThreadFunc(GetParam1), new object[] { 3, "myArg1" });
rThreads.Add(new ThreadFunc(GetParam1), new object[] { 4, "myArg1" });
rThreads.Add(new ThreadFunc(GetParam1), new object[] { 5, "myArg1" });
//Wait until they are complete
rThreads.Start();
rThreads.Wait();
return;
}
//[Variation("Multiple GetParam for different parameter name")]
[Fact]
public void proc2()
{
CThreads rThreads = new CThreads(_output);
rThreads.Add(new ThreadFunc(GetParam2), new object[] { 1, "myArg1" });
rThreads.Add(new ThreadFunc(GetParam2), new object[] { 2, "myArg2" });
rThreads.Add(new ThreadFunc(GetParam2), new object[] { 3, "myArg3" });
rThreads.Add(new ThreadFunc(GetParam2), new object[] { 4, "myArg4" });
rThreads.Add(new ThreadFunc(GetParam2), new object[] { 5, "myArg5" });
//Wait until they are complete
rThreads.Start();
rThreads.Wait();
return;
}
}
//[TestCase(Name = "Same instance testing: XsltArgList - GetExtensionObject", Desc = "GetExtensionObject test cases")]
public class CSameInstanceXsltArgumentListGetExtnObject : CSameInstanceXsltArgTestCase
{
private ITestOutputHelper _output;
public CSameInstanceXsltArgumentListGetExtnObject(ITestOutputHelper output) : base(output)
{
_output = output;
}
////////////////////////////////////////////////////////////////
// Same instance testing:
// Multiple GetExtensionObject() over same ArgumentList
////////////////////////////////////////////////////////////////
public int GetExtnObject1(object args)
{
object retObj;
for (int i = 1; i <= 100; i++)
{
retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString());
_output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue());
if (((MyObject)retObj).MyValue() != 1)
{
_output.WriteLine("ERROR!!! Set and retrieved value appear to be different");
return 0;
}
}
return 1;
}
public int GetExtnObject2(object args)
{
object retObj;
for (int i = 1; i <= 100; i++)
{
retObj = xsltArg1.GetExtensionObject(((object[])args)[1].ToString());
_output.WriteLine("GetExtensionObject: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tValue returned: " + ((MyObject)retObj).MyValue());
if (((MyObject)retObj).MyValue() != (int)((object[])args)[0])
{
_output.WriteLine("ERROR!!! Set and retrieved value appear to be different");
return 0;
}
}
return 1;
}
//[Variation("Multiple GetExtensionObject for same namespace System.Xml.Tests")]
[Fact]
public void proc1()
{
CThreads rThreads = new CThreads(_output);
rThreads.Add(new ThreadFunc(GetExtnObject1), new object[] { 1, "urn:my-obj1" });
rThreads.Add(new ThreadFunc(GetExtnObject1), new object[] { 2, "urn:my-obj1" });
rThreads.Add(new ThreadFunc(GetExtnObject1), new object[] { 3, "urn:my-obj1" });
rThreads.Add(new ThreadFunc(GetExtnObject1), new object[] { 4, "urn:my-obj1" });
rThreads.Add(new ThreadFunc(GetExtnObject1), new object[] { 5, "urn:my-obj1" });
//Wait until they are complete
rThreads.Start();
rThreads.Wait();
return;
}
//[Variation("Multiple GetExtensionObject for different namespace System.Xml.Tests")]
[Fact]
public void proc2()
{
CThreads rThreads = new CThreads(_output);
rThreads.Add(new ThreadFunc(GetExtnObject2), new object[] { 1, "urn:my-obj1" });
rThreads.Add(new ThreadFunc(GetExtnObject2), new object[] { 2, "urn:my-obj2" });
rThreads.Add(new ThreadFunc(GetExtnObject2), new object[] { 3, "urn:my-obj3" });
rThreads.Add(new ThreadFunc(GetExtnObject2), new object[] { 4, "urn:my-obj4" });
rThreads.Add(new ThreadFunc(GetExtnObject2), new object[] { 5, "urn:my-obj5" });
//Wait until they are complete
rThreads.Start();
rThreads.Wait();
return;
}
}
//[TestCase(Name = "Same instance testing: XsltArgList - Transform", Desc = "Multiple transforms")]
public class CSameInstanceXsltArgumentListTransform : CSameInstanceXsltArgTestCase
{
private ITestOutputHelper _output;
public CSameInstanceXsltArgumentListTransform(ITestOutputHelper output) : base(output)
{
_output = output;
}
////////////////////////////////////////////////////////////////
// Same instance testing:
// Multiple Transform() using shared ArgumentList
////////////////////////////////////////////////////////////////
public int SharedArgList(object args)
{
string _strXslFile = ((object[])args)[1].ToString();
string _strXmlFile = ((object[])args)[2].ToString();
if (_strXslFile.Substring(0, 5) != "http:")
_strXslFile = Path.Combine(_strPath, _strXslFile);
if (_strXmlFile.Substring(0, 5) != "http:")
_strXmlFile = Path.Combine(_strPath, _strXmlFile);
#pragma warning disable 0618
XmlValidatingReader xrData = new XmlValidatingReader(new XmlTextReader(_strXmlFile));
XPathDocument xd = new XPathDocument(xrData, XmlSpace.Preserve);
xrData.Dispose();
XslTransform xslt = new XslTransform();
XmlValidatingReader xrTemp = new XmlValidatingReader(new XmlTextReader(_strXslFile));
#pragma warning restore 0618
xrTemp.ValidationType = ValidationType.None;
xrTemp.EntityHandling = EntityHandling.ExpandCharEntities;
xslt.Load(xrTemp);
XmlReader xrXSLT = null;
for (int i = 1; i <= 100; i++)
{
xrXSLT = xslt.Transform(xd, xsltArg1);
_output.WriteLine("SharedArgumentList: Thread " + ((object[])args)[0] + "\tIteration " + i + "\tDone with transform...");
}
return 1;
}
////////////////////////////////////////////////////////////////
// Same instance testing:
// Multiple Transform() using shared ArgumentList
////////////////////////////////////////////////////////////////
//[Variation("Multiple transforms using shared ArgumentList")]
[Fact]
public void proc1()
{
CThreads rThreads = new CThreads(_output);
rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 1, "xsltarg_multithreading1.xsl", "foo.xml" });
rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 2, "xsltarg_multithreading2.xsl", "foo.xml" });
rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 3, "xsltarg_multithreading3.xsl", "foo.xml" });
rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 4, "xsltarg_multithreading4.xsl", "foo.xml" });
rThreads.Add(new ThreadFunc(SharedArgList), new object[] { 5, "xsltarg_multithreading5.xsl", "foo.xml" });
//Wait until they are complete
rThreads.Start();
rThreads.Wait();
return;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using QED.Business;
using JCSLA;
namespace QED.UI
{
/// <summary>
/// Summary description for EffortData.
/// </summary>
public class EffortData : System.Windows.Forms.Form {
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtPM;
private System.Windows.Forms.TextBox txtWebResx;
private System.Windows.Forms.TextBox txtTestedBy;
private System.Windows.Forms.TextBox txtDBResx;
private System.Windows.Forms.Button btnOK;
private System.Windows.Forms.Button btnCancel;
private System.Windows.Forms.CheckBox chkUATApproved;
string _defaultUserDomain;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private System.Windows.Forms.TextBox txtMaxResx;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.TextBox txtUATApprovedBy;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.TextBox txtBranchFileHierarchy;
private System.Windows.Forms.TextBox txtEnv;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtRequester;
Effort _eff;
public EffortData(Effort eff) {
InitializeComponent();
CatLists cls = new CatLists(Connections.Inst.item("QED_DB").MySqlConnection);
CatList system = cls.item("System");
_defaultUserDomain = system.Entry("/Defaults/UserDomain").Value;
_eff = eff; this.Text = eff.ConventionalId;
this.txtDBResx.Text = eff.DBResource;
this.txtPM.Text = (eff.PMResource == "") ? _defaultUserDomain : eff.PMResource;
this.txtTestedBy.Text = (eff.TestedBy == "") ? _defaultUserDomain : eff.TestedBy;
this.txtWebResx.Text = (eff.WebResource == "") ? _defaultUserDomain : eff.WebResource;
this.txtDBResx.Text = (eff.DBResource == "") ? _defaultUserDomain : eff.DBResource;
this.txtMaxResx.Text = (eff.MaxResource == "") ? _defaultUserDomain : eff.MaxResource;
this.txtUATApprovedBy.Text = (eff.UATApprovedBy == "") ? _defaultUserDomain : _eff.UATApprovedBy;
// if (eff.IsTicket) this.txtRequester.Enabled = false;
this.txtRequester.Text = (eff.Requester == "") ? _defaultUserDomain : _eff.Requester;
this.chkUATApproved.Checked = eff.UATApproved;
this.txtEnv.Text = eff.Environment;
this.txtBranchFileHierarchy.Text = eff.BranchFileHierarchy;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing ) {
if( disposing ) {
if(components != null) {
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.txtPM = new System.Windows.Forms.TextBox();
this.label12 = new System.Windows.Forms.Label();
this.txtWebResx = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label();
this.txtTestedBy = new System.Windows.Forms.TextBox();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.txtDBResx = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.btnOK = new System.Windows.Forms.Button();
this.btnCancel = new System.Windows.Forms.Button();
this.chkUATApproved = new System.Windows.Forms.CheckBox();
this.txtMaxResx = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.txtUATApprovedBy = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.txtBranchFileHierarchy = new System.Windows.Forms.TextBox();
this.label6 = new System.Windows.Forms.Label();
this.txtEnv = new System.Windows.Forms.TextBox();
this.label7 = new System.Windows.Forms.Label();
this.txtRequester = new System.Windows.Forms.TextBox();
this.label8 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// txtPM
//
this.txtPM.Location = new System.Drawing.Point(200, 72);
this.txtPM.Name = "txtPM";
this.txtPM.Size = new System.Drawing.Size(304, 20);
this.txtPM.TabIndex = 2;
this.txtPM.Text = "";
//
// label12
//
this.label12.Location = new System.Drawing.Point(8, 16);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(186, 23);
this.label12.TabIndex = 47;
this.label12.Text = "UAT Approved";
//
// txtWebResx
//
this.txtWebResx.Location = new System.Drawing.Point(200, 144);
this.txtWebResx.Name = "txtWebResx";
this.txtWebResx.Size = new System.Drawing.Size(304, 20);
this.txtWebResx.TabIndex = 4;
this.txtWebResx.Text = "";
//
// label11
//
this.label11.Location = new System.Drawing.Point(8, 144);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(184, 23);
this.label11.TabIndex = 45;
this.label11.Text = "Web Resource";
//
// txtTestedBy
//
this.txtTestedBy.Location = new System.Drawing.Point(200, 208);
this.txtTestedBy.Name = "txtTestedBy";
this.txtTestedBy.Size = new System.Drawing.Size(304, 20);
this.txtTestedBy.TabIndex = 6;
this.txtTestedBy.Text = "";
//
// label3
//
this.label3.Location = new System.Drawing.Point(8, 208);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(184, 23);
this.label3.TabIndex = 37;
this.label3.Text = "Tested By";
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 80);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(186, 23);
this.label2.TabIndex = 35;
this.label2.Text = "PM";
//
// txtDBResx
//
this.txtDBResx.Location = new System.Drawing.Point(200, 112);
this.txtDBResx.Name = "txtDBResx";
this.txtDBResx.Size = new System.Drawing.Size(304, 20);
this.txtDBResx.TabIndex = 3;
this.txtDBResx.Text = "";
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 112);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(184, 24);
this.label1.TabIndex = 33;
this.label1.Text = "DB Resource";
//
// btnOK
//
this.btnOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.btnOK.Location = new System.Drawing.Point(336, 624);
this.btnOK.Name = "btnOK";
this.btnOK.TabIndex = 9;
this.btnOK.Text = "&OK";
this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
//
// btnCancel
//
this.btnCancel.Location = new System.Drawing.Point(424, 624);
this.btnCancel.Name = "btnCancel";
this.btnCancel.TabIndex = 10;
this.btnCancel.Text = "&Cancel";
this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
//
// chkUATApproved
//
this.chkUATApproved.Location = new System.Drawing.Point(200, 16);
this.chkUATApproved.Name = "chkUATApproved";
this.chkUATApproved.TabIndex = 0;
//
// txtMaxResx
//
this.txtMaxResx.Location = new System.Drawing.Point(200, 176);
this.txtMaxResx.Name = "txtMaxResx";
this.txtMaxResx.Size = new System.Drawing.Size(304, 20);
this.txtMaxResx.TabIndex = 5;
this.txtMaxResx.Text = "";
//
// label4
//
this.label4.Location = new System.Drawing.Point(8, 176);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(184, 23);
this.label4.TabIndex = 53;
this.label4.Text = "Max Resource";
//
// txtUATApprovedBy
//
this.txtUATApprovedBy.Location = new System.Drawing.Point(200, 40);
this.txtUATApprovedBy.Name = "txtUATApprovedBy";
this.txtUATApprovedBy.Size = new System.Drawing.Size(304, 20);
this.txtUATApprovedBy.TabIndex = 1;
this.txtUATApprovedBy.Text = "";
//
// label5
//
this.label5.Location = new System.Drawing.Point(8, 48);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(186, 23);
this.label5.TabIndex = 55;
this.label5.Text = "UAT Approved By";
//
// txtBranchFileHierarchy
//
this.txtBranchFileHierarchy.AcceptsTab = true;
this.txtBranchFileHierarchy.Location = new System.Drawing.Point(8, 336);
this.txtBranchFileHierarchy.Multiline = true;
this.txtBranchFileHierarchy.Name = "txtBranchFileHierarchy";
this.txtBranchFileHierarchy.Size = new System.Drawing.Size(496, 280);
this.txtBranchFileHierarchy.TabIndex = 8;
this.txtBranchFileHierarchy.Text = "";
//
// label6
//
this.label6.Location = new System.Drawing.Point(8, 304);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(184, 23);
this.label6.TabIndex = 57;
this.label6.Text = "Branch-File Hierarchy";
//
// txtEnv
//
this.txtEnv.Location = new System.Drawing.Point(200, 272);
this.txtEnv.Name = "txtEnv";
this.txtEnv.Size = new System.Drawing.Size(304, 20);
this.txtEnv.TabIndex = 7;
this.txtEnv.Text = "";
//
// label7
//
this.label7.Location = new System.Drawing.Point(8, 272);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(184, 23);
this.label7.TabIndex = 59;
this.label7.Text = "Environments";
//
// txtRequester
//
this.txtRequester.Location = new System.Drawing.Point(200, 240);
this.txtRequester.Name = "txtRequester";
this.txtRequester.Size = new System.Drawing.Size(304, 20);
this.txtRequester.TabIndex = 60;
this.txtRequester.Text = "";
//
// label8
//
this.label8.Location = new System.Drawing.Point(8, 240);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(184, 23);
this.label8.TabIndex = 61;
this.label8.Text = "Requestor";
//
// EffortData
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(512, 653);
this.Controls.Add(this.txtRequester);
this.Controls.Add(this.label8);
this.Controls.Add(this.txtEnv);
this.Controls.Add(this.label7);
this.Controls.Add(this.txtBranchFileHierarchy);
this.Controls.Add(this.label6);
this.Controls.Add(this.txtUATApprovedBy);
this.Controls.Add(this.label5);
this.Controls.Add(this.txtMaxResx);
this.Controls.Add(this.txtPM);
this.Controls.Add(this.txtWebResx);
this.Controls.Add(this.txtTestedBy);
this.Controls.Add(this.txtDBResx);
this.Controls.Add(this.label4);
this.Controls.Add(this.chkUATApproved);
this.Controls.Add(this.btnCancel);
this.Controls.Add(this.btnOK);
this.Controls.Add(this.label12);
this.Controls.Add(this.label11);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Name = "EffortData";
this.Text = "1";
this.Load += new System.EventHandler(this.EffortData_Load);
this.ResumeLayout(false);
}
#endregion
private void btnOK_Click(object sender, System.EventArgs e) {
_eff.PMResource = (this.txtPM.Text == _defaultUserDomain) ? "" : this.txtPM.Text;
_eff.TestedBy = (this.txtTestedBy.Text == _defaultUserDomain) ? "" : this.txtTestedBy.Text;
_eff.WebResource = (this.txtWebResx.Text == _defaultUserDomain) ? "" : this.txtWebResx.Text;
_eff.DBResource = (this.txtDBResx.Text == _defaultUserDomain) ? "" : this.txtDBResx.Text;
_eff.MaxResource = (this.txtMaxResx.Text == _defaultUserDomain) ? "" : this.txtMaxResx.Text;
_eff.UATApproved = this.chkUATApproved.Checked;
_eff.UATApprovedBy = (this.txtUATApprovedBy.Text == _defaultUserDomain) ? "" : this.txtUATApprovedBy.Text;
_eff.Requester = (this.txtRequester.Text == _defaultUserDomain) ? "" : this.txtRequester.Text;
_eff.Environment = this.txtEnv.Text;
_eff.BranchFileHierarchy = this.txtBranchFileHierarchy.Text;
if (_eff.IsValid){
_eff.Update();
this.DialogResult = DialogResult.OK;
this.Close();
}else{
MessageBox.Show(this, _eff.BrokenRules.ToString(), "QED");
}
}
private void btnCancel_Click(object sender, System.EventArgs e) {
this.Close();
}
private void EffortData_Load(object sender, System.EventArgs e) {
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
namespace OrchardCore.ResourceManagement
{
public class ResourceDefinition
{
private string _basePath;
public ResourceDefinition(ResourceManifest manifest, string type, string name)
{
Manifest = manifest;
Type = type;
Name = name;
}
private static string Coalesce(params string[] strings)
{
foreach (var str in strings)
{
if (!String.IsNullOrEmpty(str))
{
return str;
}
}
return null;
}
public ResourceManifest Manifest { get; private set; }
public string Name { get; private set; }
public string Type { get; private set; }
public string Version { get; private set; }
public bool? AppendVersion { get; private set; }
public string Url { get; private set; }
public string UrlDebug { get; private set; }
public string UrlCdn { get; private set; }
public string UrlCdnDebug { get; private set; }
public string CdnDebugIntegrity { get; private set; }
public string CdnIntegrity { get; private set; }
public string[] Cultures { get; private set; }
public bool CdnSupportsSsl { get; private set; }
public List<string> Dependencies { get; private set; }
public AttributeDictionary Attributes { get; private set; }
public string InnerContent { get; private set; }
public ResourceDefinition SetAttribute(string name, string value)
{
if (Attributes == null)
{
Attributes = new AttributeDictionary();
}
Attributes[name] = value;
return this;
}
public ResourceDefinition SetBasePath(string virtualPath)
{
_basePath = virtualPath;
return this;
}
public ResourceDefinition SetUrl(string url)
{
return SetUrl(url, null);
}
public ResourceDefinition SetUrl(string url, string urlDebug)
{
if (String.IsNullOrEmpty(url))
{
ThrowArgumentNullException(nameof(url));
}
Url = url;
if (urlDebug != null)
{
UrlDebug = urlDebug;
}
return this;
}
public ResourceDefinition SetCdn(string cdnUrl)
{
return SetCdn(cdnUrl, null, null);
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug)
{
return SetCdn(cdnUrl, cdnUrlDebug, null);
}
public ResourceDefinition SetCdnIntegrity(string cdnIntegrity)
{
return SetCdnIntegrity(cdnIntegrity, null);
}
public ResourceDefinition SetCdnIntegrity(string cdnIntegrity, string cdnDebugIntegrity)
{
if (String.IsNullOrEmpty(cdnIntegrity))
{
ThrowArgumentNullException(nameof(cdnIntegrity));
}
CdnIntegrity = cdnIntegrity;
if (cdnDebugIntegrity != null)
{
CdnDebugIntegrity = cdnDebugIntegrity;
}
return this;
}
public ResourceDefinition SetCdn(string cdnUrl, string cdnUrlDebug, bool? cdnSupportsSsl)
{
if (String.IsNullOrEmpty(cdnUrl))
{
ThrowArgumentNullException(nameof(cdnUrl));
}
UrlCdn = cdnUrl;
if (cdnUrlDebug != null)
{
UrlCdnDebug = cdnUrlDebug;
}
if (cdnSupportsSsl.HasValue)
{
CdnSupportsSsl = cdnSupportsSsl.Value;
}
return this;
}
/// <summary>
/// Sets the version of the resource.
/// </summary>
/// <param name="version">The version to set, in the form of <code>major.minor[.build[.revision]]</code></param>
public ResourceDefinition SetVersion(string version)
{
Version = version;
return this;
}
/// <summary>
/// Should a file version be appended to the resource.
/// </summary>
/// <param name="appendVersion"></param>
public ResourceDefinition ShouldAppendVersion(bool? appendVersion)
{
AppendVersion = appendVersion;
return this;
}
public ResourceDefinition SetCultures(params string[] cultures)
{
Cultures = cultures;
return this;
}
public ResourceDefinition SetDependencies(params string[] dependencies)
{
if (Dependencies == null)
{
Dependencies = new List<string>();
}
Dependencies.AddRange(dependencies);
return this;
}
public ResourceDefinition SetDependencies(List<string> dependencies)
{
if (Dependencies == null)
{
Dependencies = new List<string>();
}
Dependencies.AddRange(dependencies);
return this;
}
public ResourceDefinition SetInnerContent(string innerContent)
{
InnerContent = innerContent;
return this;
}
public TagBuilder GetTagBuilder(RequireSettings settings,
string applicationPath,
IFileVersionProvider fileVersionProvider)
{
string url, filePathAttributeName = null;
// Url priority:
if (settings.DebugMode)
{
url = settings.CdnMode
? Coalesce(UrlCdnDebug, UrlDebug, UrlCdn, Url)
: Coalesce(UrlDebug, Url, UrlCdnDebug, UrlCdn);
}
else
{
url = settings.CdnMode
? Coalesce(UrlCdn, Url, UrlCdnDebug, UrlDebug)
: Coalesce(Url, UrlDebug, UrlCdn, UrlCdnDebug);
}
if (String.IsNullOrEmpty(url))
{
url = null;
}
if (!String.IsNullOrEmpty(settings.Culture))
{
string nearestCulture = FindNearestCulture(settings.Culture);
if (!String.IsNullOrEmpty(nearestCulture))
{
url = Path.ChangeExtension(url, nearestCulture + Path.GetExtension(url));
}
}
if (url != null && url.StartsWith("~/", StringComparison.Ordinal))
{
if (!String.IsNullOrEmpty(_basePath))
{
url = _basePath + url.Substring(1);
}
else
{
url = applicationPath + url.Substring(1);
}
}
// If settings has value, it can override resource definition, otherwise use resource definition
if (url != null && ((settings.AppendVersion.HasValue && settings.AppendVersion == true) ||
(!settings.AppendVersion.HasValue && AppendVersion == true)))
{
url = fileVersionProvider.AddFileVersionToPath(applicationPath, url);
}
// Don't prefix cdn if the path is absolute, or is in debug mode.
if (!settings.DebugMode
&& !String.IsNullOrEmpty(settings.CdnBaseUrl)
&& !Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
url = settings.CdnBaseUrl + url;
}
TagBuilder tagBuilder;
switch (Type)
{
case "script":
tagBuilder = new TagBuilder("script")
{
Attributes = {
{ "type", "text/javascript" }
}
};
filePathAttributeName = "src";
break;
case "stylesheet":
if (url == null && InnerContent != null)
{
// Inline style declaration
tagBuilder = new TagBuilder("style")
{
Attributes = {
{ "type", "text/css" }
}
};
}
else
{
// Stylesheet resource
tagBuilder = new TagBuilder("link") {
TagRenderMode = TagRenderMode.SelfClosing,
Attributes = {
{ "type", "text/css" },
{ "rel", "stylesheet" }
}
};
filePathAttributeName = "href";
}
break;
case "link":
tagBuilder = new TagBuilder("link") { TagRenderMode = TagRenderMode.SelfClosing };
filePathAttributeName = "href";
break;
default:
tagBuilder = new TagBuilder("meta") { TagRenderMode = TagRenderMode.SelfClosing };
break;
}
if (!String.IsNullOrEmpty(CdnIntegrity) && url != null && url == UrlCdn)
{
tagBuilder.Attributes["integrity"] = CdnIntegrity;
tagBuilder.Attributes["crossorigin"] = "anonymous";
}
else if (!String.IsNullOrEmpty(CdnDebugIntegrity) && url != null && url == UrlCdnDebug)
{
tagBuilder.Attributes["integrity"] = CdnDebugIntegrity;
tagBuilder.Attributes["crossorigin"] = "anonymous";
}
if (Attributes != null)
{
tagBuilder.MergeAttributes(Attributes);
}
if (settings.HasAttributes)
{
tagBuilder.MergeAttributes(settings.Attributes);
}
if (!String.IsNullOrEmpty(url) && filePathAttributeName != null)
{
tagBuilder.MergeAttribute(filePathAttributeName, url, true);
}
else if (!String.IsNullOrEmpty(InnerContent))
{
tagBuilder.InnerHtml.AppendHtml(InnerContent);
}
return tagBuilder;
}
public string FindNearestCulture(string culture)
{
// go for an exact match
if (Cultures == null)
{
return null;
}
int selectedIndex = Array.IndexOf(Cultures, culture);
if (selectedIndex != -1)
{
return Cultures[selectedIndex];
}
// try parent culture if any
var cultureInfo = new CultureInfo(culture);
if (cultureInfo.Parent.Name != culture)
{
var selectedCulture = FindNearestCulture(cultureInfo.Parent.Name);
if (selectedCulture != null)
{
return selectedCulture;
}
}
return null;
}
public override bool Equals(object obj)
{
if (obj == null || obj.GetType() != GetType())
{
return false;
}
var that = (ResourceDefinition)obj;
return string.Equals(that.Name, Name) &&
string.Equals(that.Type, Type) &&
string.Equals(that.Version, Version);
}
public override int GetHashCode()
{
return HashCode.Combine(Name, Type);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowArgumentNullException(string paramName)
{
throw new ArgumentNullException(paramName);
}
}
}
| |
using System;
using System.Text;
using zipkin4net.Utils;
namespace zipkin4net.Propagation
{
///
/// This format corresponds to the propagation key "b3" (or "B3"), which delimits fields in the
/// following manner.
///
/// <pre><code>
/// b3: {x-b3-traceid}-{x-b3-spanid}-{if x-b3-flags 'd' else x-b3-sampled}-{x-b3-parentspanid}
/// </code></pre>
///
/// <p>For example, a sampled root span would look like:
/// <code>4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-1</code>
///
/// <p>... a not yet sampled root span would look like:
/// <code>4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7</code>
///
/// <p>... and a debug RPC child span would look like:
/// <code>4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-d-5b4185666d50f68b</code>
///
/// <p>Like normal B3, it is valid to omit trace identifiers in order to only propagate a sampling
/// decision. For example, the following are valid downstream hints:
/// <ul>
/// <li>don't sample - <code>b3: 0</code></li>
/// <li>sampled - <code>b3: 1</code></li>
/// <li>debug - <code>b3: d</code></li>
/// </ul>
///
/// Reminder: debug (previously <code>X-B3-Flags: 1</code>), is a boosted sample signal which is recorded
/// to ensure it reaches the collector tier. See <see cref="ISamplingFlags.Debug"/>.
///
/// <p>See <a href="https://github.com/openzipkin/b3-propagation">B3 Propagation</a>
///
public static class B3SingleFormat
{
private const int FormatMaxLength = 32 + 1 + 16 + 2 + 16; // traceid128-spanid-1-parentid
/// <summary>
/// Writes all B3 defined fields in the trace context, except <see cref="ITraceContext.ParentSpanId"/>,
/// to a hyphen delimited string.
///
/// <p>This is appropriate for receivers who understand "b3" single header format, and always do
/// work in a child span. For example, message consumers always do work in child spans, so message
/// producers can use this format to save bytes on the wire. On the other hand, RPC clients should
/// use <see cref="WriteB3SingleFormat(ITraceContext)"/>} instead, as RPC servers often share a span ID
/// with the client.
/// </summary>
///
public static string WriteB3SingleFormatWithoutParentId(ITraceContext context)
{
return WriteB3SingleFormat(context, null);
}
/// <summary>
/// Writes all B3 defined fields in the trace context to a hyphen delimited string. This is
/// appropriate for receivers who understand "b3" single header format.
///
/// <p>The <see cref="ITraceContext.ParentSpanId"/> is serialized in case the receiver is
/// an RPC server. When downstream is known to be a messaging consumer, or a server that never
/// reuses a client's span ID, prefer <see cref="WriteB3SingleFormat(ITraceContext)"/>.
/// </summary>
public static string WriteB3SingleFormat(ITraceContext context)
{
return WriteB3SingleFormat(context, context.ParentSpanId);
}
private static string WriteB3SingleFormat(ITraceContext context, long? parentId)
{
var result = new StringBuilder(FormatMaxLength);
var traceIdHigh = context.TraceIdHigh;
if (traceIdHigh != SpanState.NoTraceIdHigh)
{
var traceIdHighString = NumberUtils.EncodeLongToLowerHexString(traceIdHigh);
result.Append(traceIdHighString);
}
var traceIdString = NumberUtils.EncodeLongToLowerHexString(context.TraceId);
result.Append(traceIdString);
result.Append('-');
var spanIdString = NumberUtils.EncodeLongToLowerHexString(context.SpanId);
result.Append(spanIdString);
var sampled = context.Sampled;
if (sampled.HasValue || context.Debug)
{
result.Append('-');
result.Append(context.Debug ? 'd' : sampled.Value ? '1' : '0');
}
if (parentId.HasValue && parentId.Value != 0L)
{
result.Append('-');
var parentIdString = NumberUtils.EncodeLongToLowerHexString(parentId.Value);
result.Append(parentIdString);
}
return result.ToString();
}
public static ITraceContext ParseB3SingleFormat(string b3)
{
if (b3 == null)
{
return null;
}
return ParseB3SingleFormat(b3, 0, b3.Length);
}
/// <summary>
/// <param name="beginIndex">the start index, inclusive</param>
/// <param name="endIndex">the end index, exclusive</param>
/// </summary>
public static ITraceContext ParseB3SingleFormat(string b3, int beginIndex,
int endIndex)
{
if (beginIndex == endIndex)
{
return null;
}
int pos = beginIndex;
if (pos + 1 == endIndex)
{
// possibly sampling flags
return TryParseSamplingFlags(b3, pos);
}
// At this point we minimally expect a traceId-spanId pair
if (endIndex < 16 + 1 + 16 /* traceid64-spanid */)
{
return null;
}
else if (endIndex > FormatMaxLength)
{
return null;
}
long traceIdHigh, traceId;
if (b3[pos + 32] == '-')
{
traceIdHigh = TryParse16HexCharacters(b3, pos, endIndex);
pos += 16; // upper 64 bits of the trace ID
traceId = TryParse16HexCharacters(b3, pos, endIndex);
}
else
{
traceIdHigh = 0L;
traceId = TryParse16HexCharacters(b3, pos, endIndex);
}
pos += 16; // traceId
if (!CheckHyphen(b3, pos++)) return null;
if (traceIdHigh == 0L && traceId == 0L)
{
return null;
}
var spanId = TryParse16HexCharacters(b3, pos, endIndex);
if (spanId == 0L)
{
return null;
}
pos += 16; // spanid
var flags = SpanFlags.None;
long? parentId = null;
if (endIndex > pos)
{
// If we are at this point, we have more than just traceId-spanId.
// If the sampling field is present, we'll have a delimiter 2 characters from now. Ex "-1"
// If it is absent, but a parent ID is (which is strange), we'll have at least 17 characters.
// Therefore, if we have less than two characters, the input is truncated.
if (endIndex == pos + 1)
{
return null;
}
if (!CheckHyphen(b3, pos++)) return null;
// If our position is at the end of the string, or another delimiter is one character past our
// position, try to read sampled status.
if (endIndex == pos + 1 || DelimiterFollowsPos(b3, pos, endIndex))
{
flags = ParseFlags(b3, pos);
if (flags == 0) return null;
pos++; // consume the sampled status
}
if (endIndex > pos)
{
// If we are at this point, we should have a parent ID, encoded as "-[0-9a-f]{16}"
if (endIndex != pos + 17)
{
return null;
}
if (!CheckHyphen(b3, pos++)) return null;
parentId = TryParse16HexCharacters(b3, pos, endIndex);
if (parentId == 0L)
{
return null;
}
}
}
return new SpanState(traceIdHigh, traceId, parentId, spanId, flags.HasFlag(SpanFlags.Sampled), flags.HasFlag(SpanFlags.Debug));
}
static ITraceContext TryParseSamplingFlags(string b3, int pos)
{
var flags = ParseFlags(b3, pos);
if (flags == 0) return null;
return null; // Not handled yet
}
private static bool CheckHyphen(string b3, int pos)
{
return b3[pos] == '-';
}
private static bool DelimiterFollowsPos(string b3, int pos, int end)
{
return (end >= pos + 2) && b3[pos + 1] == '-';
}
private static long TryParse16HexCharacters(string lowerHex, int index, int end)
{
int endIndex = index + 16;
if (endIndex > end) return 0L;
try
{
return NumberUtils.DecodeHexString(lowerHex.Substring(index, 16));
}
catch (Exception e)
{
return 0L;
}
}
private static SpanFlags ParseFlags(string b3, int pos)
{
SpanFlags flags;
var sampledChar = b3[pos];
switch (sampledChar)
{
case 'd':
flags = SpanFlags.SamplingKnown | SpanFlags.Sampled | SpanFlags.Debug;
break;
case '1':
flags = SpanFlags.SamplingKnown | SpanFlags.Sampled;
break;
case '0':
flags = SpanFlags.SamplingKnown;
break;
default:
flags = 0;
break;
}
return flags;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Net.Test.Common;
using System.Threading;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SendPacketsAsync
{
private readonly ITestOutputHelper _log;
private IPAddress _serverAddress = IPAddress.IPv6Loopback;
// Accessible directories for UWP app:
// C:\Users\<UserName>\AppData\Local\Packages\<ApplicationPackageName>\
private string TestFileName = Environment.GetEnvironmentVariable("LocalAppData") + @"\NCLTest.Socket.SendPacketsAsync.testpayload";
private static int s_testFileSize = 1024;
#region Additional test attributes
public SendPacketsAsync(ITestOutputHelper output)
{
_log = TestLogging.GetInstance();
byte[] buffer = new byte[s_testFileSize];
for (int i = 0; i < s_testFileSize; i++)
{
buffer[i] = (byte)(i % 255);
}
try
{
_log.WriteLine("Creating file {0} with size: {1}", TestFileName, s_testFileSize);
using (FileStream fs = new FileStream(TestFileName, FileMode.CreateNew))
{
fs.Write(buffer, 0, buffer.Length);
}
}
catch (IOException)
{
// Test payload file already exists.
_log.WriteLine("Payload file exists: {0}", TestFileName);
}
}
#endregion Additional test attributes
#region Basic Arguments
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void Disposed_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
sock.Dispose();
Assert.Throws<ObjectDisposedException>(() =>
{
sock.SendPacketsAsync(new SocketAsyncEventArgs());
});
}
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[ActiveIssue(20135, TargetFrameworkMonikers.Uap)]
public void NullArgs_Throw(SocketImplementationType type)
{
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() =>
{
sock.SendPacketsAsync(null);
});
Assert.Equal("e", ex.ParamName);
}
}
}
[Fact]
public void NotConnected_Throw()
{
Socket socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
// Needs to be connected before send
Assert.Throws<NotSupportedException>(() =>
{
socket.SendPacketsAsync(new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] });
});
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null m_SendPacketsElementsInternal array")]
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[ActiveIssue(20135, TargetFrameworkMonikers.Uap)]
public void NullList_Throws(SocketImplementationType type)
{
ArgumentNullException ex = Assert.Throws<ArgumentNullException>(() =>
{
SendPackets(type, (SendPacketsElement[])null, SocketError.Success, 0);
});
Assert.Equal("e.SendPacketsElements", ex.ParamName);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[ActiveIssue(20135, TargetFrameworkMonikers.Uap)]
public void NullElement_Ignored(SocketImplementationType type)
{
SendPackets(type, (SendPacketsElement)null, 0);
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[ActiveIssue(20135, TargetFrameworkMonikers.Uap)]
public void EmptyList_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement[0], SocketError.Success, 0);
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public void SocketAsyncEventArgs_DefaultSendSize_0()
{
SocketAsyncEventArgs args = new SocketAsyncEventArgs();
Assert.Equal(0, args.SendPacketsSendSize);
}
#endregion Basic Arguments
#region Buffers
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBuffer_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10]), 10);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void NormalBufferRange_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 5, 5), 5);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[ActiveIssue(20135, TargetFrameworkMonikers.Uap)]
public void EmptyBuffer_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[0]), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[ActiveIssue(20135, TargetFrameworkMonikers.Uap)]
public void BufferZeroCount_Ignored(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 0), 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void BufferMixedBuffers_ZeroCountBufferIgnored(SocketImplementationType type)
{
SendPacketsElement[] elements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[10], 4, 0), // Ignored
new SendPacketsElement(new byte[10], 4, 4),
new SendPacketsElement(new byte[10], 0, 4)
};
SendPackets(type, elements, SocketError.Success, 8);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[ActiveIssue(20135, TargetFrameworkMonikers.Uap)]
public void BufferZeroCountThenNormal_ZeroCountIgnored(SocketImplementationType type)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
// First do an empty send, ignored
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 3, 0)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(0, args.BytesTransferred);
completed.Reset();
// Now do a real send
args.SendPacketsElements = new SendPacketsElement[]
{
new SendPacketsElement(new byte[5], 1, 4)
};
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(4, args.BytesTransferred);
}
}
}
}
#endregion Buffers
#region TransmitFileOptions
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnected_TransmitFileOptionDisconnect(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect, 4);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SocketDisconnectedAndReusable_TransmitFileOptionReuseSocket(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(new byte[10], 4, 4), TransmitFileOptions.Disconnect | TransmitFileOptions.ReuseSocket, 4);
}
#endregion
#region Files
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_EmptyFileName_Throws(SocketImplementationType type)
{
Assert.Throws<ArgumentException>(() =>
{
SendPackets(type, new SendPacketsElement(String.Empty), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // whitespace-only is a valid name on Unix
public void SendPacketsElement_BlankFileName_Throws(SocketImplementationType type)
{
Assert.Throws<ArgumentException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(" \t "), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
[PlatformSpecific(TestPlatforms.Windows)] // valid filename chars on Unix
public void SendPacketsElement_BadCharactersFileName_Throws(SocketImplementationType type)
{
Assert.Throws<ArgumentException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("blarkd@dfa?/sqersf"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingDirectoryName_Throws(SocketImplementationType type)
{
Assert.Throws<DirectoryNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement(Path.Combine("nodir", "nofile")), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_MissingFile_Throws(SocketImplementationType type)
{
Assert.Throws<FileNotFoundException>(() =>
{
// Existence is validated on send
SendPackets(type, new SendPacketsElement("DoesntExit"), 0);
});
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_File_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileZeroCount_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 0, 0), s_testFileSize); // Whole File
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FilePart_Success(SocketImplementationType type)
{
SendPackets(type, new SendPacketsElement(TestFileName, 10, 20), 20);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileMultiPart_Success(SocketImplementationType type)
{
SendPacketsElement[] elements = new SendPacketsElement[]
{
new SendPacketsElement(TestFileName, 10, 20),
new SendPacketsElement(TestFileName, 30, 10),
new SendPacketsElement(TestFileName, 0, 10),
};
SendPackets(type, elements, SocketError.Success, 40);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeOffset_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 11000, 1), SocketError.InvalidArgument, 0);
}
[Theory]
[InlineData(SocketImplementationType.APM)]
[InlineData(SocketImplementationType.Async)]
public void SendPacketsElement_FileLargeCount_Throws(SocketImplementationType type)
{
// Length is validated on Send
SendPackets(type, new SendPacketsElement(TestFileName, 5, 10000), SocketError.InvalidArgument, 0);
}
#endregion Files
#region Helpers
private void SendPackets(SocketImplementationType type, SendPacketsElement element, TransmitFileOptions flags, int bytesExpected)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = new[] { element };
args.SendPacketsFlags = flags;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(SocketError.Success, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
switch (flags)
{
case TransmitFileOptions.Disconnect:
// Sending data again throws with socket shut down error.
Assert.Throws<SocketException>(() => { sock.Send(new byte[1] { 01 }); });
break;
case TransmitFileOptions.ReuseSocket & TransmitFileOptions.Disconnect:
// Able to send data again with reuse socket flag set.
Assert.Equal(1, sock.Send(new byte[1] { 01 }));
break;
}
}
}
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, int bytesExpected)
{
SendPackets(type, new SendPacketsElement[] { element }, SocketError.Success, bytesExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement element, SocketError expectedResut, int bytesExpected)
{
SendPackets(type, new SendPacketsElement[] { element }, expectedResut, bytesExpected);
}
private void SendPackets(SocketImplementationType type, SendPacketsElement[] elements, SocketError expectedResut, int bytesExpected)
{
Assert.True(Capability.IPv6Support());
EventWaitHandle completed = new ManualResetEvent(false);
int port;
using (SocketTestServer.SocketTestServerFactory(type, _serverAddress, out port))
{
using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp))
{
sock.Connect(new IPEndPoint(_serverAddress, port));
using (SocketAsyncEventArgs args = new SocketAsyncEventArgs())
{
args.Completed += OnCompleted;
args.UserToken = completed;
args.SendPacketsElements = elements;
if (sock.SendPacketsAsync(args))
{
Assert.True(completed.WaitOne(TestSettings.PassingTestTimeout), "Timed out");
}
Assert.Equal(expectedResut, args.SocketError);
Assert.Equal(bytesExpected, args.BytesTransferred);
}
}
}
}
private void OnCompleted(object sender, SocketAsyncEventArgs e)
{
EventWaitHandle handle = (EventWaitHandle)e.UserToken;
handle.Set();
}
#endregion Helpers
}
}
| |
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace MacMemoryManipulator
{
public partial class MemoryManipulator
{
protected uint _self;
private int _id;
/// <summary>
/// Gets or sets the process id of the target process.
/// </summary>
/// <value>
/// The process id of the target process.
/// </value>
public int Id
{
get { return _id; }
set {
_id = value;
if (0 != task_for_pid(_self, Id, out _task)) {
throw new Exception("Task for the target process couldn't be received.");
}
}
}
protected uint _task;
/// <summary>
/// Gets the task id of the target process.
/// </summary>
/// <value>
/// The task id of the target process.
/// </value>
public uint Task
{
get { return _task; }
protected set { _task = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="MacMemoryManipulator.MemoryManipulator"/> class.
/// </summary>
/// <param name='processId'>
/// The process id of the target process.
/// </param>
public MemoryManipulator(int processId)
:this()
{
Id = processId;
}
/// <summary>
/// Initializes a new instance of the <see cref="MacMemoryManipulator.MemoryManipulator"/> class.
/// </summary>
/// <param name='processName'>
/// A part of the process name of the target process (see <see cref="System.Diagnostics.Process.GetProcessesByName"/>).
/// </param>
public MemoryManipulator(string processName)
:this()
{
var processes = System.Diagnostics.Process.GetProcessesByName(processName);
if (processes.Length == 0) {
throw new Exception("No process found.");
}
Id = processes[0].Id;
}
protected MemoryManipulator()
{
_self = mach_task_self();
}
/// <summary>
/// Read the specified address.
/// </summary>
/// <param name='address'>
/// Address.
/// </param>
/// <typeparam name='T'>
/// The type of the value. Can be a primitive type or a struct.
/// </typeparam>
public T Read<T>(ulong address) where T : struct
{
object result;
Type type = typeof(T);
TypeCode typeCode = Type.GetTypeCode(type);
if (typeCode == TypeCode.Object) {
result = ReadStruct(address, type);
}
else {
int size = type == typeof(char) ? Marshal.SystemDefaultCharSize : Marshal.SizeOf(type);
result = BytesToType(ReadBytes(address, size), typeCode);
}
return (T)result;
}
/// <summary>
/// Read the specified address with the specified offset chain (32-bit version).
/// </summary>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='offsets'>
/// Offsets.
/// </param>
/// <typeparam name='T'>
/// The type of the value. Can be a primitive type or a struct.
/// </typeparam>
public T Read<T>(uint address, uint[] offsets) where T : struct
{
address = Read<uint>(address);
for (int i = 0; i < offsets.Length - 1; i++)
{
address = Read<uint>(address + offsets[i]);
}
return Read<T>(address + offsets[offsets.Length - 1]);
}
/// <summary>
/// Read the specified address with the specified offset chain (64-bit version).
/// </summary>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='offsets'>
/// Offsets.
/// </param>
/// <typeparam name='T'>
/// The type of the value. Can be a primitive type or a struct.
/// </typeparam>
public T Read<T>(ulong address, ulong[] offsets) where T : struct
{
address = Read<ulong>(address);
for (int i = 0; i < offsets.Length - 1; i++)
{
address = Read<ulong>(address + offsets[i]);
}
return Read<T>(address + offsets[offsets.Length - 1]);
}
/// <summary>
/// Reads the specified address as byte array.
/// </summary>
/// <returns>
/// The byte array.
/// </returns>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='size'>
/// Size of the region to read in bytes.
/// </param>
public byte[] ReadBytes(ulong address, int size)
{
if (size <= 0) {
throw new ArgumentOutOfRangeException("size", size, "Must be bigger than 0.");
}
IntPtr dataPointer = Read(address, (ulong)size);
byte[] data = new byte[size];
Marshal.Copy(dataPointer, data, 0, size);
Marshal.FreeHGlobal(dataPointer);
return data;
}
/// <summary>
/// Reads a null terminated string with the specified max size and encoding.
/// </summary>
/// <returns>
/// The string.
/// </returns>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='maxSize'>
/// Max size.
/// </param>
/// <param name='encoding'>
/// Encoding.
/// </param>
public string ReadString(ulong address, int maxSize, Encoding encoding)
{
if (!(encoding.Equals(Encoding.UTF8) || encoding.Equals(Encoding.Unicode) || encoding.Equals(Encoding.ASCII)))
{
throw new ArgumentException(string.Format("Encoding type {0} is not supported", encoding.EncodingName), "encoding");
}
IntPtr dataPointer = Read(address, (ulong)maxSize);
string result;
if (encoding == Encoding.ASCII) {
result = Marshal.PtrToStringAnsi(dataPointer);
}
else {
result = Marshal.PtrToStringUni(dataPointer);
}
Marshal.FreeHGlobal(dataPointer);
return result;
}
/// <summary>
/// Reads a struct.
/// </summary>
/// <returns>
/// The struct.
/// </returns>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='type'>
/// Type of the struct.
/// </param>
/// <remarks>
/// Read<structType> can be used instead.
/// </remarks>
public object ReadStruct(ulong address, Type type)
{
IntPtr pointer = Read(address, (ulong)Marshal.SizeOf(type));
var structure = Marshal.PtrToStructure(pointer, type);
Marshal.FreeHGlobal(pointer);
return structure;
}
/// <summary>
/// Reads a array.
/// </summary>
/// <returns>
/// The array.
/// </returns>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='size'>
/// Size of the array.
/// </param>
/// <typeparam name='T'>
/// The type of the array values.
/// </typeparam>
public T[] ReadArray<T>(ulong address, int size) where T : struct
{
int typeSize = Marshal.SizeOf(typeof(T));
int dataSize = typeSize * size;
IntPtr dataPointer = Read(address, (ulong)dataSize);
try {
switch (Type.GetTypeCode(typeof(T)))
{
case TypeCode.Byte:
var bytes = new byte[size];
Marshal.Copy(dataPointer, bytes, 0, size);
return bytes.Cast<T>().ToArray();
case TypeCode.Char:
var chars = new char[size];
Marshal.Copy(dataPointer, chars, 0, size);
return chars.Cast<T>().ToArray();
case TypeCode.Int16:
var shorts = new short[size];
Marshal.Copy(dataPointer, shorts, 0, size);
return shorts.Cast<T>().ToArray();
case TypeCode.Int32:
var ints = new int[size];
Marshal.Copy(dataPointer, ints, 0, size);
return ints.Cast<T>().ToArray();
case TypeCode.Int64:
var longs = new long[size];
Marshal.Copy(dataPointer, longs, 0, size);
return longs.Cast<T>().ToArray();
case TypeCode.Single:
var floats = new float[size];
Marshal.Copy(dataPointer, floats, 0, size);
return floats.Cast<T>().ToArray();
case TypeCode.Double:
var doubles = new double[size];
Marshal.Copy(dataPointer, doubles, 0, size);
return doubles.Cast<T>().ToArray();
default:
var objects = new T[size];
IntPtr currentObjectPointer = dataPointer;
for (int i = 0; i < size; i++) {
objects[i] = (T)Marshal.PtrToStructure(currentObjectPointer, typeof(T));
currentObjectPointer = new IntPtr(currentObjectPointer.ToInt64() + typeSize);
}
return objects;
}
}
finally {
Marshal.FreeHGlobal(dataPointer);
}
}
/// <summary>
/// Writes data to the specified address.
/// </summary>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='data'>
/// Data to write.
/// </param>
/// <typeparam name='T'>
/// The type of the data.
/// </typeparam>
public void Write<T>(ulong address, T data) where T : struct
{
GCHandle pinnedData = GCHandle.Alloc(data, GCHandleType.Pinned);
IntPtr pointer = pinnedData.AddrOfPinnedObject();
try {
if (0 != mach_vm_write(Task, address, pointer, (uint)Marshal.SizeOf(data))) {
throw new Exception("Unable to write to address " + address.ToString("X"));
}
}
finally {
pinnedData.Free();
}
}
/// <summary>
/// Reads memory of the specified address and size.
/// </summary>
/// <param name='address'>
/// Address.
/// </param>
/// <param name='size'>
/// Size.
/// </param>
/// <remarks>
/// The returned pointer should be freed with Marshal.FreeHGlobal in the calling method to avoid memory leaks!
/// </remarks>
protected IntPtr Read(ulong address, ulong size)
{
IntPtr dataPointer = Marshal.AllocHGlobal((int)size);
ulong bytesRead;
if (0 != mach_vm_read_overwrite(Task, address, size, (ulong)dataPointer.ToInt64(), out bytesRead)) {
throw new Exception("Unable to read address " + address.ToString("X"));
}
if (bytesRead != size) {
throw new Exception(string.Format("Unable to read {0} bytes from process", size));
}
return dataPointer;
}
/// <summary>
/// Converts a bytes to the specified type.
/// </summary>
/// <returns>
/// The converted value.
/// </returns>
/// <param name='bytes'>
/// Bytes.
/// </param>
/// <param name='type'>
/// Type.
/// </param>
protected object BytesToType(byte[] bytes, TypeCode type)
{
object result;
switch (type) {
case TypeCode.Boolean:
result = BitConverter.ToBoolean(bytes, 0);
break;
case TypeCode.Char:
result = BitConverter.ToChar(bytes, 0);
break;
case TypeCode.Byte:
result = bytes[0];
break;
case TypeCode.SByte:
result = (sbyte)bytes[0];
break;
case TypeCode.Int16:
result = BitConverter.ToInt16(bytes, 0);
break;
case TypeCode.Int32:
result = BitConverter.ToInt32(bytes, 0);
break;
case TypeCode.Int64:
result = BitConverter.ToInt64(bytes, 0);
break;
case TypeCode.UInt16:
result = BitConverter.ToUInt16(bytes, 0);
break;
case TypeCode.UInt32:
result = BitConverter.ToUInt32(bytes, 0);
break;
case TypeCode.UInt64:
result = BitConverter.ToUInt64(bytes, 0);
break;
case TypeCode.Single:
result = BitConverter.ToSingle(bytes, 0);
break;
case TypeCode.Double:
result = BitConverter.ToDouble(bytes, 0);
break;
default:
throw new NotSupportedException(type + " is not supported yet");
}
return result;
}
}
}
| |
using SageCS.Core;
using System.Collections.Generic;
namespace SageCS.INI
{
class INIManager
{
private static GameData gameData;
private static Dictionary<string, Object> objects = new Dictionary<string, Object>();
private static Dictionary<string, Weapon> weapons = new Dictionary<string, Weapon>();
private static Dictionary<string, Upgrade> upgrades = new Dictionary<string, Upgrade>();
private static Dictionary<string, Armor> armors = new Dictionary<string, Armor>();
private static Dictionary<string, MappedImage> mappedImages = new Dictionary<string, MappedImage>();
private static Dictionary<string, AmbientStream> ambientStreams = new Dictionary<string, AmbientStream>();
private static Dictionary<string, CommandButton> commandButtons = new Dictionary<string, CommandButton>();
private static Dictionary<string, ModifierList> modifierLists = new Dictionary<string, ModifierList>();
public static void ParseINIs()
{
//map.ini files are loaded when the corresponding map is selected for the game
new INIParser(FileSystem.Open("data\\ini\\gamedata.ini"));
new INIParser(FileSystem.Open("data\\ini\\createaherogamedata.inc"));
new INIParser(FileSystem.Open("data\\ini\\armor.ini"));
new INIParser(FileSystem.Open("data\\ini\\ambientstream.ini"));
//new INIParser(FileSystem.Open("data\\ini\\attributemodifier.ini")); //still some error
new INIParser(FileSystem.Open("data\\ini\\commandbutton.ini"));
/*
List<Stream> streams = FileSystem.OpenAll(".ini");
foreach (Stream s in streams)
{
try
{
new INIParser(s);
}
catch
{
try
{
Console.WriteLine("## ERROR: unable to parse ini file: " + ((BigStream)s).Name);
}
catch
{
Console.WriteLine("#######");
}
}
}
Console.WriteLine("# finished parsing " + streams.Count + " ini files");
*/
}
public static void SetGameData(GameData data)
{
gameData = data;
}
public static void AddObject(string name, INI.Object obj)
{
if (!objects.ContainsKey(name))
objects.Add(name, obj);
else
//overwrite old object
objects[name] = obj;
}
public static Object getObject(string name)
{
return objects[name];
}
public static bool TryGetObject(string name, out Object obj)
{
if (objects.ContainsKey(name))
{
obj = getObject(name);
return true;
}
obj = null;
return false;
}
public static void AddWeapon(string name, Weapon wep)
{
if (!weapons.ContainsKey(name))
weapons.Add(name, wep);
else
//overwrite old object
weapons[name] = wep;
}
public static Weapon GetWeapon(string name)
{
return weapons[name];
}
public static bool TryGetWeapon(string name, out Weapon weapon)
{
if (weapons.ContainsKey(name))
{
weapon = GetWeapon(name);
return true;
}
weapon = null;
return false;
}
public static void AddUpgrade(string name, Upgrade up)
{
if (!upgrades.ContainsKey(name))
upgrades.Add(name, up);
else
//overwrite old object
upgrades[name] = up;
}
public static Upgrade GetUpgrade(string name)
{
return upgrades[name];
}
public static bool TryGetUpgrade(string name, out Upgrade upgrade)
{
if (upgrades.ContainsKey(name))
{
upgrade = GetUpgrade(name);
return true;
}
upgrade = null;
return false;
}
public static void AddArmor(string name, Armor ar)
{
if (!armors.ContainsKey(name))
armors.Add(name, ar);
else
//overwrite old object
armors[name] = ar;
}
public static Armor GetArmor(string name)
{
return armors[name];
}
public static bool TryGetArmor(string name, out Armor armor)
{
if (armors.ContainsKey(name))
{
armor = GetArmor(name);
return true;
}
armor = null;
return false;
}
public static void AddMappedImage(string name, MappedImage mi)
{
if (!mappedImages.ContainsKey(name))
mappedImages.Add(name, mi);
else
//overwrite old object
mappedImages[name] = mi;
}
public static MappedImage GetMappedImage(string name)
{
return mappedImages[name];
}
public static bool TryGetMappedImage(string name, out MappedImage mi)
{
if (mappedImages.ContainsKey(name))
{
mi = GetMappedImage(name);
return true;
}
mi = null;
return false;
}
public static void AddAmbientStream(string name, AmbientStream ast)
{
if (!ambientStreams.ContainsKey(name))
ambientStreams.Add(name, ast);
else
ambientStreams[name] = ast;
}
public static AmbientStream GetAmbientStream(string name)
{
return ambientStreams[name];
}
public static bool TryGetAmbientStream(string name, out AmbientStream ast)
{
if (ambientStreams.ContainsKey(name))
{
ast = GetAmbientStream(name);
return true;
}
ast = null;
return false;
}
public static void AddCommandButton(string name, CommandButton cb)
{
if (!commandButtons.ContainsKey(name))
commandButtons.Add(name, cb);
else
commandButtons[name] = cb;
}
public static CommandButton GetCommandButton(string name)
{
return commandButtons[name];
}
public static bool TryGetCommandButton(string name, out CommandButton cb)
{
if (commandButtons.ContainsKey(name))
{
cb = GetCommandButton(name);
return true;
}
cb = null;
return false;
}
public static void AddModifierList(string name, ModifierList ml)
{
if (!modifierLists.ContainsKey(name))
modifierLists.Add(name, ml);
else
modifierLists[name] = ml;
}
public static ModifierList GetModifierList(string name)
{
return modifierLists[name];
}
public static bool TryGetModifierList(string name, out ModifierList ml)
{
if(modifierLists.ContainsKey(name))
{
ml = GetModifierList(name);
return true;
}
ml = null;
return false;
}
//called after each match?
public static void ClearAll()
{
objects.Clear();
weapons.Clear();
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Region.Framework.Interfaces;
using OpenMetaverse;
using log4net;
namespace OpenSim.Region.CoreModules.World.Estate
{
public class EstateRequestHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
protected XEstateModule m_EstateModule;
protected Object m_RequestLock = new Object();
public EstateRequestHandler(XEstateModule fmodule)
: base("POST", "/estate")
{
m_EstateModule = fmodule;
}
protected override byte[] ProcessRequest(string path, Stream requestData,
IOSHttpRequest httpRequest, IOSHttpResponse httpResponse)
{
StreamReader sr = new StreamReader(requestData);
string body = sr.ReadToEnd();
sr.Close();
body = body.Trim();
m_log.DebugFormat("[XESTATE HANDLER]: query String: {0}", body);
try
{
lock (m_RequestLock)
{
Dictionary<string, object> request =
ServerUtils.ParseQueryString(body);
if (!request.ContainsKey("METHOD"))
return FailureResult();
string method = request["METHOD"].ToString();
request.Remove("METHOD");
try
{
m_EstateModule.InInfoUpdate = false;
switch (method)
{
case "update_covenant":
return UpdateCovenant(request);
case "update_estate":
return UpdateEstate(request);
case "estate_message":
return EstateMessage(request);
case "teleport_home_one_user":
return TeleportHomeOneUser(request);
case "teleport_home_all_users":
return TeleportHomeAllUsers(request);
}
}
finally
{
m_EstateModule.InInfoUpdate = false;
}
}
}
catch (Exception e)
{
m_log.Debug("[XESTATE]: Exception {0}" + e.ToString());
}
return FailureResult();
}
byte[] TeleportHomeAllUsers(Dictionary<string, object> request)
{
UUID PreyID = UUID.Zero;
int EstateID = 0;
if (!request.ContainsKey("EstateID"))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == EstateID)
{
s.ForEachScenePresence(delegate(ScenePresence p) {
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
s.TeleportClientHome(p.ControllingClient.AgentId, p.ControllingClient);
}
});
}
}
return SuccessResult();
}
byte[] TeleportHomeOneUser(Dictionary<string, object> request)
{
UUID PreyID = UUID.Zero;
int EstateID = 0;
if (!request.ContainsKey("PreyID") ||
!request.ContainsKey("EstateID"))
{
return FailureResult();
}
if (!UUID.TryParse(request["PreyID"].ToString(), out PreyID))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == EstateID)
{
ScenePresence p = s.GetScenePresence(PreyID);
if (p != null && !p.IsChildAgent)
{
p.ControllingClient.SendTeleportStart(16);
s.TeleportClientHome(PreyID, p.ControllingClient);
}
}
}
return SuccessResult();
}
byte[] EstateMessage(Dictionary<string, object> request)
{
UUID FromID = UUID.Zero;
string FromName = String.Empty;
string Message = String.Empty;
int EstateID = 0;
if (!request.ContainsKey("FromID") ||
!request.ContainsKey("FromName") ||
!request.ContainsKey("Message") ||
!request.ContainsKey("EstateID"))
{
return FailureResult();
}
if (!UUID.TryParse(request["FromID"].ToString(), out FromID))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
FromName = request["FromName"].ToString();
Message = request["Message"].ToString();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == EstateID)
{
IDialogModule dm = s.RequestModuleInterface<IDialogModule>();
if (dm != null)
{
dm.SendNotificationToUsersInRegion(FromID, FromName,
Message);
}
}
}
return SuccessResult();
}
byte[] UpdateCovenant(Dictionary<string, object> request)
{
UUID CovenantID = UUID.Zero;
int EstateID = 0;
if (!request.ContainsKey("CovenantID") || !request.ContainsKey("EstateID"))
return FailureResult();
if (!UUID.TryParse(request["CovenantID"].ToString(), out CovenantID))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == (uint)EstateID)
s.RegionInfo.RegionSettings.Covenant = CovenantID;
}
return SuccessResult();
}
byte[] UpdateEstate(Dictionary<string, object> request)
{
int EstateID = 0;
if (!request.ContainsKey("EstateID"))
return FailureResult();
if (!Int32.TryParse(request["EstateID"].ToString(), out EstateID))
return FailureResult();
foreach (Scene s in m_EstateModule.Scenes)
{
if (s.RegionInfo.EstateSettings.EstateID == (uint)EstateID)
s.ReloadEstateData();
}
return SuccessResult();
}
private byte[] FailureResult()
{
return BoolResult(false);
}
private byte[] SuccessResult()
{
return BoolResult(true);
}
private byte[] BoolResult(bool value)
{
XmlDocument doc = new XmlDocument();
XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration,
"", "");
doc.AppendChild(xmlnode);
XmlElement rootElement = doc.CreateElement("", "ServerResponse",
"");
doc.AppendChild(rootElement);
XmlElement result = doc.CreateElement("", "RESULT", "");
result.AppendChild(doc.CreateTextNode(value.ToString()));
rootElement.AppendChild(result);
return Util.DocToBytes(doc);
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Data.SimpleDB;
using System.Data;
namespace InWorldz.Data.Inventory.Cassandra
{
/// <summary>
/// A MySQL interface for the inventory server
/// </summary>
public class LegacyMysqlStorageImpl
{
private static readonly ILog m_log
= LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
ConnectionFactory _connFactory;
private string _connectString;
public LegacyMysqlStorageImpl(string connStr)
{
_connectString = connStr;
_connFactory = new ConnectionFactory("MySQL", _connectString);
}
public InventoryFolderBase findUserFolderForType(UUID userId, int typeId)
{
string query = "SELECT * FROM inventoryfolders WHERE agentID = ?agentId AND type = ?type;";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?agentId", userId);
parms.Add("?type", typeId);
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
using (IDataReader reader = conn.QueryAndUseReader(query, parms))
{
if (reader.Read())
{
// A null item (because something went wrong) breaks everything in the folder
return readInventoryFolder(reader);
}
else
{
return null;
}
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
/// <summary>
/// Returns the most appropriate folder for the given inventory type, or null if one could not be found
/// </summary>
/// <param name="userId"></param>
/// <param name="type"></param>
/// <returns></returns>
public InventoryFolderBase findUserTopLevelFolderFor(UUID owner, UUID folderID)
{
// this is a stub, not supported in MySQL legacy storage
m_log.ErrorFormat("[MySQLInventoryData]: Inventory for user {0} needs to be migrated to Cassandra.", owner.ToString());
return null;
}
/// <summary>
/// Returns a list of items in the given folders
/// </summary>
/// <param name="folders"></param>
/// <returns></returns>
public List<InventoryItemBase> getItemsInFolders(IEnumerable<InventoryFolderBase> folders)
{
string inList = "";
foreach (InventoryFolderBase folder in folders)
{
if (inList != "") inList += ",";
inList += "'" + folder.ID.ToString() + "'";
}
if (inList == "") return new List<InventoryItemBase>();
string query = "SELECT * FROM inventoryitems WHERE parentFolderID IN (" + inList + ");";
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
using (IDataReader reader = conn.QueryAndUseReader(query))
{
List<InventoryItemBase> items = new List<InventoryItemBase>();
while (reader.Read())
{
// A null item (because something went wrong) breaks everything in the folder
InventoryItemBase item = readInventoryItem(reader);
if (item != null)
items.Add(item);
}
return items;
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return new List<InventoryItemBase>();
}
}
/// <summary>
/// Returns a list of items in a specified folder
/// </summary>
/// <param name="folderID">The folder to search</param>
/// <returns>A list containing inventory items</returns>
public List<InventoryItemBase> getInventoryInFolder(UUID folderID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryitems WHERE parentFolderID = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", folderID.ToString());
List<InventoryItemBase> items = new List<InventoryItemBase>();
using (IDataReader reader = conn.QueryAndUseReader(query, parms))
{
while (reader.Read())
{
// A null item (because something went wrong) breaks everything in the folder
InventoryItemBase item = readInventoryItem(reader);
if (item != null)
items.Add(item);
}
}
return items;
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
/// <summary>
/// Returns a list of the root folders within a users inventory (folders that only have the root as their parent)
/// </summary>
/// <param name="user">The user whos inventory is to be searched</param>
/// <returns>A list of folder objects</returns>
public List<InventoryFolderBase> getUserRootFolders(UUID user, UUID root)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?root AND agentID = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", user.ToString());
parms.Add("?root", root.ToString());
using (IDataReader reader = conn.QueryAndUseReader(query, parms))
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
return items;
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
/// <summary>
/// see <see cref="InventoryItemBase.getUserRootFolder"/>
/// </summary>
/// <param name="user">The user UUID</param>
/// <returns></returns>
public InventoryFolderBase getUserRootFolder(UUID user)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?zero AND agentID = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", user.ToString());
parms.Add("?zero", UUID.Zero.ToString());
using (IDataReader reader = conn.QueryAndUseReader(query, parms))
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
InventoryFolderBase rootFolder = null;
// There should only ever be one root folder for a user. However, if there's more
// than one we'll simply use the first one rather than failing. It would be even
// nicer to print some message to this effect, but this feels like it's too low a
// to put such a message out, and it's too minor right now to spare the time to
// suitably refactor.
if (items.Count > 0)
{
rootFolder = items[0];
}
return rootFolder;
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
/// <summary>
/// Return a list of folders in a users inventory contained within the specified folder.
/// This method is only used in tests - in normal operation the user always have one,
/// and only one, root folder.
/// </summary>
/// <param name="parentID">The folder to search</param>
/// <returns>A list of inventory folders</returns>
public List<InventoryFolderBase> getInventoryFolders(UUID parentID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryfolders WHERE parentFolderID = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", parentID.ToString());
using (IDataReader reader = conn.QueryAndUseReader(query, parms))
{
List<InventoryFolderBase> items = new List<InventoryFolderBase>();
while (reader.Read())
items.Add(readInventoryFolder(reader));
return items;
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
/// <summary>
/// Reads a one item from an SQL result
/// </summary>
/// <param name="reader">The SQL Result</param>
/// <returns>the item read</returns>
private static InventoryItemBase readInventoryItem(IDataReader reader)
{
try
{
InventoryItemBase item = new InventoryItemBase();
// TODO: this is to handle a case where NULLs creep in there, which we are not sure is indemic to the system, or legacy. It would be nice to live fix these.
if (reader["creatorID"] == null)
{
item.CreatorId = UUID.Zero.ToString();
}
else
{
item.CreatorId = (string)reader["creatorID"];
}
// Be a bit safer in parsing these because the
// database doesn't enforce them to be not null, and
// the inventory still works if these are weird in the
// db
UUID Owner = UUID.Zero;
UUID GroupID = UUID.Zero;
UUID.TryParse(Convert.ToString(reader["avatarID"]), out Owner);
UUID.TryParse(Convert.ToString(reader["groupID"]), out GroupID);
item.Owner = Owner;
item.GroupID = GroupID;
// Rest of the parsing. If these UUID's fail, we're dead anyway
item.ID = new UUID(Convert.ToString(reader["inventoryID"]));
item.AssetID = new UUID(Convert.ToString(reader["assetID"]));
item.AssetType = (int)reader["assetType"];
item.Folder = new UUID(Convert.ToString(reader["parentFolderID"]));
item.Name = (string)reader["inventoryName"];
item.Description = (string)reader["inventoryDescription"];
item.NextPermissions = (uint)reader["inventoryNextPermissions"];
item.CurrentPermissions = (uint)reader["inventoryCurrentPermissions"];
item.InvType = (int)reader["invType"];
item.BasePermissions = (uint)reader["inventoryBasePermissions"];
item.EveryOnePermissions = (uint)reader["inventoryEveryOnePermissions"];
item.GroupPermissions = (uint)reader["inventoryGroupPermissions"];
item.SalePrice = (int)reader["salePrice"];
item.SaleType = Convert.ToByte(reader["saleType"]);
item.CreationDate = (int)reader["creationDate"];
item.GroupOwned = Convert.ToBoolean(reader["groupOwned"]);
item.Flags = (uint)reader["flags"];
return item;
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
return null;
}
/// <summary>
/// Returns a specified inventory item
/// </summary>
/// <param name="item">The item to return</param>
/// <returns>An inventory item</returns>
public InventoryItemBase getInventoryItem(UUID itemID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryitems WHERE inventoryID = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", itemID.ToString());
using (IDataReader reader = conn.QueryAndUseReader(query, parms))
{
InventoryItemBase item = null;
if (reader.Read())
item = readInventoryItem(reader);
return item;
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
return null;
}
/// <summary>
/// Reads a list of inventory folders returned by a query.
/// </summary>
/// <param name="reader">A MySQL Data Reader</param>
/// <returns>A List containing inventory folders</returns>
protected static InventoryFolderBase readInventoryFolder(IDataReader reader)
{
try
{
InventoryFolderBase folder = new InventoryFolderBase();
folder.Owner = new UUID(Convert.ToString(reader["agentID"]));
folder.ParentID = new UUID(Convert.ToString(reader["parentFolderID"]));
folder.ID = new UUID(Convert.ToString(reader["folderID"]));
folder.Name = (string)reader["folderName"];
folder.Type = (short)reader["type"];
folder.Version = (ushort)((int)reader["version"]);
return folder;
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
return null;
}
/// <summary>
/// Returns a specified inventory folder
/// </summary>
/// <param name="folder">The folder to return</param>
/// <returns>A folder class</returns>
public InventoryFolderBase getInventoryFolder(UUID folderID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryfolders WHERE folderID = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", folderID.ToString());
using (IDataReader reader = conn.QueryAndUseReader(query, parms))
{
if (reader.Read())
{
InventoryFolderBase folder = readInventoryFolder(reader);
return folder;
}
else
{
return null;
}
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
/// <summary>
/// Adds a specified item to the database
/// </summary>
/// <param name="item">The inventory item</param>
public void addInventoryItem(InventoryItemBase item)
{
string sql =
"REPLACE INTO inventoryitems (inventoryID, assetID, assetType, parentFolderID, avatarID, inventoryName"
+ ", inventoryDescription, inventoryNextPermissions, inventoryCurrentPermissions, invType"
+ ", creatorID, inventoryBasePermissions, inventoryEveryOnePermissions, inventoryGroupPermissions, salePrice, saleType"
+ ", creationDate, groupID, groupOwned, flags) VALUES ";
sql +=
"(?inventoryID, ?assetID, ?assetType, ?parentFolderID, ?avatarID, ?inventoryName, ?inventoryDescription"
+ ", ?inventoryNextPermissions, ?inventoryCurrentPermissions, ?invType, ?creatorID"
+ ", ?inventoryBasePermissions, ?inventoryEveryOnePermissions, ?inventoryGroupPermissions, ?salePrice, ?saleType, ?creationDate"
+ ", ?groupID, ?groupOwned, ?flags)";
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?inventoryID", item.ID.ToString());
parms.Add("?assetID", item.AssetID.ToString());
parms.Add("?assetType", item.AssetType.ToString());
parms.Add("?parentFolderID", item.Folder.ToString());
parms.Add("?avatarID", item.Owner.ToString());
parms.Add("?inventoryName", item.Name);
parms.Add("?inventoryDescription", item.Description);
parms.Add("?inventoryNextPermissions", item.NextPermissions.ToString());
parms.Add("?inventoryCurrentPermissions", item.CurrentPermissions.ToString());
parms.Add("?invType", item.InvType);
parms.Add("?creatorID", item.CreatorId);
parms.Add("?inventoryBasePermissions", item.BasePermissions);
parms.Add("?inventoryEveryOnePermissions", item.EveryOnePermissions);
parms.Add("?inventoryGroupPermissions", item.GroupPermissions);
parms.Add("?salePrice", item.SalePrice);
parms.Add("?saleType", item.SaleType);
parms.Add("?creationDate", item.CreationDate);
parms.Add("?groupID", item.GroupID);
parms.Add("?groupOwned", item.GroupOwned);
parms.Add("?flags", item.Flags);
conn.QueryNoResults(sql, parms);
string query = "update inventoryfolders set version=version+1 where folderID = ?folderID";
Dictionary<string, object> updParms = new Dictionary<string, object>();
updParms.Add("?folderID", item.Folder.ToString());
conn.QueryNoResults(query, updParms);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
/// <summary>
/// Updates the specified inventory item
/// </summary>
/// <param name="item">Inventory item to update</param>
public void updateInventoryItem(InventoryItemBase item)
{
//addInventoryItem(item);
/* 12/9/2009 - Ele's Edit - Rather than simply adding a whole new item, which seems kind of pointless to me,
let's actually try UPDATING the item as it should be. This is not fully functioning yet from the updating of items
* within Scene.Inventory.cs MoveInventoryItem yet. Not sure the effect it will have on the rest of the updates either, as they
* originally pointed back to addInventoryItem above.
*/
string sql =
"UPDATE inventoryitems SET assetID=?assetID, assetType=?assetType, parentFolderID=?parentFolderID, "
+ "avatarID=?avatarID, inventoryName=?inventoryName, inventoryDescription=?inventoryDescription, inventoryNextPermissions=?inventoryNextPermissions, "
+ "inventoryCurrentPermissions=?inventoryCurrentPermissions, invType=?invType, creatorID=?creatorID, inventoryBasePermissions=?inventoryBasePermissions, "
+ "inventoryEveryOnePermissions=?inventoryEveryOnePermissions, inventoryGroupPermissions=?inventoryGroupPermissions, salePrice=?salePrice, "
+ "saleType=?saleType, creationDate=?creationDate, groupID=?groupID, groupOwned=?groupOwned, flags=?flags "
+ "WHERE inventoryID=?inventoryID";
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?inventoryID", item.ID.ToString());
parms.Add("?assetID", item.AssetID.ToString());
parms.Add("?assetType", item.AssetType.ToString());
parms.Add("?parentFolderID", item.Folder.ToString());
parms.Add("?avatarID", item.Owner.ToString());
parms.Add("?inventoryName", item.Name);
parms.Add("?inventoryDescription", item.Description);
parms.Add("?inventoryNextPermissions", item.NextPermissions.ToString());
parms.Add("?inventoryCurrentPermissions", item.CurrentPermissions.ToString());
parms.Add("?invType", item.InvType);
parms.Add("?creatorID", item.CreatorId);
parms.Add("?inventoryBasePermissions", item.BasePermissions);
parms.Add("?inventoryEveryOnePermissions", item.EveryOnePermissions);
parms.Add("?inventoryGroupPermissions", item.GroupPermissions);
parms.Add("?salePrice", item.SalePrice);
parms.Add("?saleType", item.SaleType);
parms.Add("?creationDate", item.CreationDate);
parms.Add("?groupID", item.GroupID);
parms.Add("?groupOwned", item.GroupOwned);
parms.Add("?flags", item.Flags);
conn.QueryNoResults(sql, parms);
parms.Clear();
sql = "update inventoryfolders set version=version+1 where folderID = ?folderID";
parms.Add("?folderID", item.Folder.ToString());
conn.QueryNoResults(sql, parms);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
/// <summary>
/// Detele the specified inventory item
/// </summary>
/// <param name="item">The inventory item UUID to delete</param>
public void deleteInventoryItem(UUID itemID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "DELETE FROM inventoryitems WHERE inventoryID=?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", itemID.ToString());
conn.QueryNoResults(query, parms);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
public InventoryItemBase queryInventoryItem(UUID itemID)
{
return getInventoryItem(itemID);
}
public InventoryFolderBase queryInventoryFolder(UUID folderID)
{
return getInventoryFolder(folderID);
}
/// <summary>
/// Creates a new inventory folder
/// </summary>
/// <param name="folder">Folder to create</param>
public void addInventoryFolder(InventoryFolderBase folder)
{
if (folder.ID == UUID.Zero)
{
m_log.Error("Not storing zero UUID folder for " + folder.Owner.ToString());
return;
}
string sql =
"REPLACE INTO inventoryfolders (folderID, agentID, parentFolderID, folderName, type, version) VALUES ";
sql += "(?folderID, ?agentID, ?parentFolderID, ?folderName, ?type, ?version)";
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?folderID", folder.ID.ToString());
parms.Add("?agentID", folder.Owner.ToString());
parms.Add("?parentFolderID", folder.ParentID.ToString());
parms.Add("?folderName", folder.Name);
parms.Add("?type", (short)folder.Type);
parms.Add("?version", folder.Version);
conn.QueryNoResults(sql, parms);
//also increment the parent version number if not null
this.IncrementParentFolderVersion(conn, folder.ParentID);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
private void IncrementParentFolderVersion(ISimpleDB conn, UUID parentId)
{
if (parentId != UUID.Zero)
{
string query = "update inventoryfolders set version=version+1 where folderID = ?folderID";
Dictionary<string, object> updParms = new Dictionary<string, object>();
updParms.Add("?folderID", parentId.ToString());
conn.QueryNoResults(query, updParms);
}
}
/// <summary>
/// Updates an inventory folder
/// </summary>
/// <param name="folder">Folder to update</param>
public void updateInventoryFolder(InventoryFolderBase folder)
{
string sql =
"update inventoryfolders set folderName=?folderName where folderID=?folderID";
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?folderName", folder.Name);
parms.Add("?folderID", folder.ID.ToString());
conn.QueryNoResults(sql, parms);
//also increment the parent version number if not null
this.IncrementParentFolderVersion(conn, folder.ID);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
/// <summary>
/// Move an inventory folder
/// </summary>
/// <param name="folder">Folder to move</param>
/// <remarks>UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID</remarks>
public void moveInventoryFolder(InventoryFolderBase folder)
{
string sql = "UPDATE inventoryfolders SET parentFolderID=?parentFolderID WHERE folderID=?folderID";
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?folderID", folder.ID.ToString());
parms.Add("?parentFolderID", folder.ParentID.ToString());
conn.QueryNoResults(sql, parms);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
/// <summary>
/// Append a list of all the child folders of a parent folder
/// </summary>
/// <param name="folders">list where folders will be appended</param>
/// <param name="parentID">ID of parent</param>
protected void getInventoryFolders(ref List<InventoryFolderBase> folders, UUID parentID)
{
List<InventoryFolderBase> subfolderList = getInventoryFolders(parentID);
foreach (InventoryFolderBase f in subfolderList)
folders.Add(f);
}
/// <summary>
/// See IInventoryDataPlugin
/// </summary>
/// <param name="parentID"></param>
/// <returns></returns>
public List<InventoryFolderBase> getFolderHierarchy(UUID parentID)
{
/* Note: There are subtle changes between this implementation of getFolderHierarchy and the previous one
* - We will only need to hit the database twice instead of n times.
* - We assume the database is well-formed - no stranded/dangling folders, all folders in heirarchy owned
* by the same person, each user only has 1 inventory heirarchy
* - The returned list is not ordered, instead of breadth-first ordered
There are basically 2 usage cases for getFolderHeirarchy:
1) Getting the user's entire inventory heirarchy when they log in
2) Finding a subfolder heirarchy to delete when emptying the trash.
This implementation will pull all inventory folders from the database, and then prune away any folder that
is not part of the requested sub-heirarchy. The theory is that it is cheaper to make 1 request from the
database than to make n requests. This pays off only if requested heirarchy is large.
By making this choice, we are making the worst case better at the cost of making the best case worse.
This way is generally better because we don't have to rebuild the connection/sql query per subfolder,
even if we end up getting more data from the SQL server than we need.
- Francis
*/
try
{
List<InventoryFolderBase> folders = new List<InventoryFolderBase>();
Dictionary<UUID, List<InventoryFolderBase>> hashtable
= new Dictionary<UUID, List<InventoryFolderBase>>(); ;
List<InventoryFolderBase> parentFolder = new List<InventoryFolderBase>();
using (ISimpleDB conn = _connFactory.GetConnection())
{
bool buildResultsFromHashTable = false;
/* Fetch the parent folder from the database to determine the agent ID, and if
* we're querying the root of the inventory folder tree */
string query = "SELECT * FROM inventoryfolders WHERE folderID = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", parentID.ToString());
IDataReader reader;
using (reader = conn.QueryAndUseReader(query, parms))
{
while (reader.Read()) // Should be at most 1 result
parentFolder.Add(readInventoryFolder(reader));
}
if (parentFolder.Count >= 1) // No result means parent folder does not exist
{
if (parentFolder[0].ParentID == UUID.Zero) // We are querying the root folder
{
/* Get all of the agent's folders from the database, put them in a list and return it */
parms.Clear();
query = "SELECT * FROM inventoryfolders WHERE agentID = ?uuid";
parms.Add("?uuid", parentFolder[0].Owner.ToString());
using (reader = conn.QueryAndUseReader(query, parms))
{
while (reader.Read())
{
InventoryFolderBase curFolder = readInventoryFolder(reader);
if (curFolder.ID != parentID) // Do not need to add the root node of the tree to the list
folders.Add(curFolder);
}
}
} // if we are querying the root folder
else // else we are querying a subtree of the inventory folder tree
{
/* Get all of the agent's folders from the database, put them all in a hash table
* indexed by their parent ID */
parms.Clear();
query = "SELECT * FROM inventoryfolders WHERE agentID = ?uuid";
parms.Add("?uuid", parentFolder[0].Owner.ToString());
using (reader = conn.QueryAndUseReader(query, parms))
{
while (reader.Read())
{
InventoryFolderBase curFolder = readInventoryFolder(reader);
if (hashtable.ContainsKey(curFolder.ParentID)) // Current folder already has a sibling
hashtable[curFolder.ParentID].Add(curFolder); // append to sibling list
else // else current folder has no known (yet) siblings
{
List<InventoryFolderBase> siblingList = new List<InventoryFolderBase>();
siblingList.Add(curFolder);
// Current folder has no known (yet) siblings
hashtable.Add(curFolder.ParentID, siblingList);
}
} // while more items to read from the database
}
// Set flag so we know we need to build the results from the hash table after
// we unlock the database
buildResultsFromHashTable = true;
} // else we are querying a subtree of the inventory folder tree
} // if folder parentID exists
if (buildResultsFromHashTable)
{
/* We have all of the user's folders stored in a hash table indexed by their parent ID
* and we need to return the requested subtree. We will build the requested subtree
* by performing a breadth-first-search on the hash table */
if (hashtable.ContainsKey(parentID))
folders.AddRange(hashtable[parentID]);
for (int i = 0; i < folders.Count; i++) // **Note: folders.Count is *not* static
if (hashtable.ContainsKey(folders[i].ID))
folders.AddRange(hashtable[folders[i].ID]);
}
} // lock (database)
return folders;
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
/// <summary>
/// Delete a folder from database
/// </summary>
/// <param name="folderID">the folder UUID</param>
protected void deleteOneFolder(UUID folderID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "DELETE FROM inventoryfolders WHERE folderID=?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", folderID.ToString());
conn.QueryNoResults(query, parms);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
/// <summary>
/// Delete all item in a folder
/// </summary>
/// <param name="folderID">the folder UUID</param>
public void deleteItemsInFolder(UUID folderID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "DELETE FROM inventoryitems WHERE parentFolderID=?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", folderID.ToString());
conn.QueryNoResults(query, parms);
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
}
}
/// <summary>
/// Deletes an inventory folder
/// </summary>
/// <param name="folderId">Id of folder to delete</param>
public void deleteInventoryFolder(UUID folderID)
{
List<InventoryFolderBase> subFolders = getFolderHierarchy(folderID);
//Delete all sub-folders
foreach (InventoryFolderBase f in subFolders)
{
deleteOneFolder(f.ID);
deleteItemsInFolder(f.ID);
}
//Delete the actual row
deleteOneFolder(folderID);
deleteItemsInFolder(folderID);
}
public List<InventoryItemBase> fetchActiveGestures(UUID avatarID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryitems WHERE avatarId = ?uuid AND assetType = ?type and flags & 1";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", avatarID.ToString());
parms.Add("?type", (int)AssetType.Gesture);
using (IDataReader result = conn.QueryAndUseReader(query, parms))
{
List<InventoryItemBase> list = new List<InventoryItemBase>();
while (result.Read())
{
InventoryItemBase item = readInventoryItem(result);
if (item != null)
list.Add(item);
}
return list;
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return new List<InventoryItemBase>();
}
}
public List<InventoryItemBase> getAllItems(UUID avatarID)
{
try
{
using (ISimpleDB conn = _connFactory.GetConnection())
{
string query = "SELECT * FROM inventoryitems WHERE avatarId = ?uuid";
Dictionary<string, object> parms = new Dictionary<string, object>();
parms.Add("?uuid", avatarID.ToString());
using (IDataReader result = conn.QueryAndUseReader(query, parms))
{
List<InventoryItemBase> list = new List<InventoryItemBase>();
while (result.Read())
{
InventoryItemBase item = readInventoryItem(result);
if (item != null)
list.Add(item);
}
return list;
}
}
}
catch (Exception e)
{
m_log.Error(e.ToString());
return null;
}
}
}
}
| |
/*
* 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 Apache.Ignite.Core.Impl.Binary.IO
{
using System;
using System.IO;
using System.Text;
using Apache.Ignite.Core.Impl.Memory;
/// <summary>
/// Base class for managed and unmanaged data streams.
/// </summary>
internal abstract unsafe class BinaryStreamBase : IBinaryStream
{
/** Byte: zero. */
private const byte ByteZero = 0;
/** Byte: one. */
private const byte ByteOne = 1;
/** LITTLE_ENDIAN flag. */
private static readonly bool LittleEndian = BitConverter.IsLittleEndian;
/** Position. */
protected int Pos;
/** Disposed flag. */
private bool _disposed;
/// <summary>
/// Write byte.
/// </summary>
/// <param name="val">Byte value.</param>
public abstract void WriteByte(byte val);
/// <summary>
/// Read byte.
/// </summary>
/// <returns>
/// Byte value.
/// </returns>
public abstract byte ReadByte();
/// <summary>
/// Write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
public abstract void WriteByteArray(byte[] val);
/// <summary>
/// Internal routine to write byte array.
/// </summary>
/// <param name="val">Byte array.</param>
/// <param name="data">Data pointer.</param>
protected static void WriteByteArray0(byte[] val, byte* data)
{
fixed (byte* val0 = val)
{
CopyMemory(val0, data, val.Length);
}
}
/// <summary>
/// Read byte array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Byte array.
/// </returns>
public abstract byte[] ReadByteArray(int cnt);
/// <summary>
/// Internal routine to read byte array.
/// </summary>
/// <param name="len">Array length.</param>
/// <param name="data">Data pointer.</param>
/// <returns>Byte array</returns>
protected static byte[] ReadByteArray0(int len, byte* data)
{
byte[] res = new byte[len];
fixed (byte* res0 = res)
{
CopyMemory(data, res0, len);
}
return res;
}
/// <summary>
/// Write bool.
/// </summary>
/// <param name="val">Bool value.</param>
public void WriteBool(bool val)
{
WriteByte(val ? ByteOne : ByteZero);
}
/// <summary>
/// Read bool.
/// </summary>
/// <returns>
/// Bool value.
/// </returns>
public bool ReadBool()
{
return ReadByte() == ByteOne;
}
/// <summary>
/// Write bool array.
/// </summary>
/// <param name="val">Bool array.</param>
public abstract void WriteBoolArray(bool[] val);
/// <summary>
/// Internal routine to write bool array.
/// </summary>
/// <param name="val">Bool array.</param>
/// <param name="data">Data pointer.</param>
protected static void WriteBoolArray0(bool[] val, byte* data)
{
fixed (bool* val0 = val)
{
CopyMemory((byte*)val0, data, val.Length);
}
}
/// <summary>
/// Read bool array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Bool array.
/// </returns>
public abstract bool[] ReadBoolArray(int cnt);
/// <summary>
/// Internal routine to read bool array.
/// </summary>
/// <param name="len">Array length.</param>
/// <param name="data">Data pointer.</param>
/// <returns>Bool array</returns>
protected static bool[] ReadBoolArray0(int len, byte* data)
{
bool[] res = new bool[len];
fixed (bool* res0 = res)
{
CopyMemory(data, (byte*)res0, len);
}
return res;
}
/// <summary>
/// Write short.
/// </summary>
/// <param name="val">Short value.</param>
public abstract void WriteShort(short val);
/// <summary>
/// Internal routine to write short value.
/// </summary>
/// <param name="val">Short value.</param>
/// <param name="data">Data pointer.</param>
protected static void WriteShort0(short val, byte* data)
{
if (LittleEndian)
*((short*)data) = val;
else
{
byte* valPtr = (byte*)&val;
data[0] = valPtr[1];
data[1] = valPtr[0];
}
}
/// <summary>
/// Read short.
/// </summary>
/// <returns>
/// Short value.
/// </returns>
public abstract short ReadShort();
/// <summary>
/// Internal routine to read short value.
/// </summary>
/// <param name="data">Data pointer.</param>
/// <returns>Short value</returns>
protected static short ReadShort0(byte* data)
{
short val;
if (LittleEndian)
val = *((short*)data);
else
{
byte* valPtr = (byte*)&val;
valPtr[0] = data[1];
valPtr[1] = data[0];
}
return val;
}
/// <summary>
/// Write short array.
/// </summary>
/// <param name="val">Short array.</param>
public abstract void WriteShortArray(short[] val);
/// <summary>
/// Internal routine to write short array.
/// </summary>
/// <param name="val">Short array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected static void WriteShortArray0(short[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (short* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
short val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read short array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Short array.
/// </returns>
public abstract short[] ReadShortArray(int cnt);
/// <summary>
/// Internal routine to read short array.
/// </summary>
/// <param name="len">Array length.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Short array</returns>
protected static short[] ReadShortArray0(int len, byte* data, int cnt)
{
short[] res = new short[len];
if (LittleEndian)
{
fixed (short* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
short val;
byte* valPtr = (byte*)&val;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write char.
/// </summary>
/// <param name="val">Char value.</param>
public void WriteChar(char val)
{
WriteShort(*(short*)(&val));
}
/// <summary>
/// Read char.
/// </summary>
/// <returns>
/// Char value.
/// </returns>
public char ReadChar()
{
short val = ReadShort();
return *(char*)(&val);
}
/// <summary>
/// Write char array.
/// </summary>
/// <param name="val">Char array.</param>
public abstract void WriteCharArray(char[] val);
/// <summary>
/// Internal routine to write char array.
/// </summary>
/// <param name="val">Char array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected static void WriteCharArray0(char[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (char* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
char val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read char array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Char array.
/// </returns>
public abstract char[] ReadCharArray(int cnt);
/// <summary>
/// Internal routine to read char array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Char array</returns>
protected static char[] ReadCharArray0(int len, byte* data, int cnt)
{
char[] res = new char[len];
if (LittleEndian)
{
fixed (char* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
char val;
byte* valPtr = (byte*)&val;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write int.
/// </summary>
/// <param name="val">Int value.</param>
public abstract void WriteInt(int val);
/// <summary>
/// Write int to specific position.
/// </summary>
/// <param name="writePos">Position.</param>
/// <param name="val">Value.</param>
public abstract void WriteInt(int writePos, int val);
/// <summary>
/// Internal routine to write int value.
/// </summary>
/// <param name="val">Int value.</param>
/// <param name="data">Data pointer.</param>
protected static void WriteInt0(int val, byte* data)
{
if (LittleEndian)
*((int*)data) = val;
else
{
byte* valPtr = (byte*)&val;
data[0] = valPtr[3];
data[1] = valPtr[2];
data[2] = valPtr[1];
data[3] = valPtr[0];
}
}
/// <summary>
/// Read int.
/// </summary>
/// <returns>
/// Int value.
/// </returns>
public abstract int ReadInt();
/// <summary>
/// Internal routine to read int value.
/// </summary>
/// <param name="data">Data pointer.</param>
/// <returns>Int value</returns>
protected static int ReadInt0(byte* data) {
int val;
if (LittleEndian)
val = *((int*)data);
else
{
byte* valPtr = (byte*)&val;
valPtr[0] = data[3];
valPtr[1] = data[2];
valPtr[2] = data[1];
valPtr[3] = data[0];
}
return val;
}
/// <summary>
/// Write int array.
/// </summary>
/// <param name="val">Int array.</param>
public abstract void WriteIntArray(int[] val);
/// <summary>
/// Internal routine to write int array.
/// </summary>
/// <param name="val">Int array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected static void WriteIntArray0(int[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (int* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
int val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read int array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Int array.
/// </returns>
public abstract int[] ReadIntArray(int cnt);
/// <summary>
/// Internal routine to read int array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Int array</returns>
protected static int[] ReadIntArray0(int len, byte* data, int cnt)
{
int[] res = new int[len];
if (LittleEndian)
{
fixed (int* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
int val;
byte* valPtr = (byte*)&val;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write float.
/// </summary>
/// <param name="val">Float value.</param>
public void WriteFloat(float val)
{
int val0 = *(int*)(&val);
WriteInt(val0);
}
/// <summary>
/// Read float.
/// </summary>
/// <returns>
/// Float value.
/// </returns>
public float ReadFloat()
{
int val = ReadInt();
return *(float*)(&val);
}
/// <summary>
/// Write float array.
/// </summary>
/// <param name="val">Float array.</param>
public abstract void WriteFloatArray(float[] val);
/// <summary>
/// Internal routine to write float array.
/// </summary>
/// <param name="val">Int array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected static void WriteFloatArray0(float[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (float* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
float val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read float array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Float array.
/// </returns>
public abstract float[] ReadFloatArray(int cnt);
/// <summary>
/// Internal routine to read float array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Float array</returns>
protected static float[] ReadFloatArray0(int len, byte* data, int cnt)
{
float[] res = new float[len];
if (LittleEndian)
{
fixed (float* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
int val;
byte* valPtr = (byte*)&val;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write long.
/// </summary>
/// <param name="val">Long value.</param>
public abstract void WriteLong(long val);
/// <summary>
/// Internal routine to write long value.
/// </summary>
/// <param name="val">Long value.</param>
/// <param name="data">Data pointer.</param>
protected static void WriteLong0(long val, byte* data)
{
if (LittleEndian)
*((long*)data) = val;
else
{
byte* valPtr = (byte*)&val;
data[0] = valPtr[7];
data[1] = valPtr[6];
data[2] = valPtr[5];
data[3] = valPtr[4];
data[4] = valPtr[3];
data[5] = valPtr[2];
data[6] = valPtr[1];
data[7] = valPtr[0];
}
}
/// <summary>
/// Read long.
/// </summary>
/// <returns>
/// Long value.
/// </returns>
public abstract long ReadLong();
/// <summary>
/// Internal routine to read long value.
/// </summary>
/// <param name="data">Data pointer.</param>
/// <returns>Long value</returns>
protected static long ReadLong0(byte* data)
{
long val;
if (LittleEndian)
val = *((long*)data);
else
{
byte* valPtr = (byte*)&val;
valPtr[0] = data[7];
valPtr[1] = data[6];
valPtr[2] = data[5];
valPtr[3] = data[4];
valPtr[4] = data[3];
valPtr[5] = data[2];
valPtr[6] = data[1];
valPtr[7] = data[0];
}
return val;
}
/// <summary>
/// Write long array.
/// </summary>
/// <param name="val">Long array.</param>
public abstract void WriteLongArray(long[] val);
/// <summary>
/// Internal routine to write long array.
/// </summary>
/// <param name="val">Long array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected static void WriteLongArray0(long[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (long* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
long val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[7];
*curPos++ = valPtr[6];
*curPos++ = valPtr[5];
*curPos++ = valPtr[4];
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read long array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Long array.
/// </returns>
public abstract long[] ReadLongArray(int cnt);
/// <summary>
/// Internal routine to read long array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Long array</returns>
protected static long[] ReadLongArray0(int len, byte* data, int cnt)
{
long[] res = new long[len];
if (LittleEndian)
{
fixed (long* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
long val;
byte* valPtr = (byte*)&val;
valPtr[7] = *data++;
valPtr[6] = *data++;
valPtr[5] = *data++;
valPtr[4] = *data++;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write double.
/// </summary>
/// <param name="val">Double value.</param>
public void WriteDouble(double val)
{
long val0 = *(long*)(&val);
WriteLong(val0);
}
/// <summary>
/// Read double.
/// </summary>
/// <returns>
/// Double value.
/// </returns>
public double ReadDouble()
{
long val = ReadLong();
return *(double*)(&val);
}
/// <summary>
/// Write double array.
/// </summary>
/// <param name="val">Double array.</param>
public abstract void WriteDoubleArray(double[] val);
/// <summary>
/// Internal routine to write double array.
/// </summary>
/// <param name="val">Double array.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
protected static void WriteDoubleArray0(double[] val, byte* data, int cnt)
{
if (LittleEndian)
{
fixed (double* val0 = val)
{
CopyMemory((byte*)val0, data, cnt);
}
}
else
{
byte* curPos = data;
for (int i = 0; i < val.Length; i++)
{
double val0 = val[i];
byte* valPtr = (byte*)&(val0);
*curPos++ = valPtr[7];
*curPos++ = valPtr[6];
*curPos++ = valPtr[5];
*curPos++ = valPtr[4];
*curPos++ = valPtr[3];
*curPos++ = valPtr[2];
*curPos++ = valPtr[1];
*curPos++ = valPtr[0];
}
}
}
/// <summary>
/// Read double array.
/// </summary>
/// <param name="cnt">Count.</param>
/// <returns>
/// Double array.
/// </returns>
public abstract double[] ReadDoubleArray(int cnt);
/// <summary>
/// Internal routine to read double array.
/// </summary>
/// <param name="len">Count.</param>
/// <param name="data">Data pointer.</param>
/// <param name="cnt">Bytes count.</param>
/// <returns>Double array</returns>
protected static double[] ReadDoubleArray0(int len, byte* data, int cnt)
{
double[] res = new double[len];
if (LittleEndian)
{
fixed (double* res0 = res)
{
CopyMemory(data, (byte*)res0, cnt);
}
}
else
{
for (int i = 0; i < len; i++)
{
double val;
byte* valPtr = (byte*)&val;
valPtr[7] = *data++;
valPtr[6] = *data++;
valPtr[5] = *data++;
valPtr[4] = *data++;
valPtr[3] = *data++;
valPtr[2] = *data++;
valPtr[1] = *data++;
valPtr[0] = *data++;
res[i] = val;
}
}
return res;
}
/// <summary>
/// Write string.
/// </summary>
/// <param name="chars">Characters.</param>
/// <param name="charCnt">Char count.</param>
/// <param name="byteCnt">Byte count.</param>
/// <param name="encoding">Encoding.</param>
/// <returns>
/// Amounts of bytes written.
/// </returns>
public abstract int WriteString(char* chars, int charCnt, int byteCnt, Encoding encoding);
/// <summary>
/// Write arbitrary data.
/// </summary>
/// <param name="src">Source array.</param>
/// <param name="off">Offset</param>
/// <param name="cnt">Count.</param>
public void Write(byte[] src, int off, int cnt)
{
fixed (byte* src0 = src)
{
Write(src0 + off, cnt);
}
}
/// <summary>
/// Read arbitrary data.
/// </summary>
/// <param name="dest">Destination array.</param>
/// <param name="off">Offset.</param>
/// <param name="cnt">Count.</param>
/// <returns>
/// Amount of bytes read.
/// </returns>
public void Read(byte[] dest, int off, int cnt)
{
fixed (byte* dest0 = dest)
{
Read(dest0 + off, cnt);
}
}
/// <summary>
/// Write arbitrary data.
/// </summary>
/// <param name="src">Source.</param>
/// <param name="cnt">Count.</param>
public abstract void Write(byte* src, int cnt);
/// <summary>
/// Internal write routine.
/// </summary>
/// <param name="src">Source.</param>
/// <param name="cnt">Count.</param>
/// <param name="data">Data (dsetination).</param>
protected void WriteInternal(byte* src, int cnt, byte* data)
{
CopyMemory(src, data + Pos, cnt);
}
/// <summary>
/// Read arbitrary data.
/// </summary>
/// <param name="dest">Destination.</param>
/// <param name="cnt">Count.</param>
/// <returns></returns>
public abstract void Read(byte* dest, int cnt);
/// <summary>
/// Internal read routine.
/// </summary>
/// <param name="src">Source</param>
/// <param name="dest">Destination.</param>
/// <param name="cnt">Count.</param>
/// <returns>Amount of bytes written.</returns>
protected void ReadInternal(byte* src, byte* dest, int cnt)
{
int cnt0 = Math.Min(Remaining, cnt);
CopyMemory(src + Pos, dest, cnt0);
ShiftRead(cnt0);
}
/// <summary>
/// Position.
/// </summary>
public int Position
{
get { return Pos; }
}
/// <summary>
/// Gets remaining bytes in the stream.
/// </summary>
/// <value>
/// Remaining bytes.
/// </value>
public abstract int Remaining { get; }
/// <summary>
/// Gets underlying array, avoiding copying if possible.
/// </summary>
/// <returns>
/// Underlying array.
/// </returns>
public abstract byte[] GetArray();
/// <summary>
/// Gets underlying data in a new array.
/// </summary>
/// <returns>
/// New array with data.
/// </returns>
public abstract byte[] GetArrayCopy();
/// <summary>
/// Check whether array passed as argument is the same as the stream hosts.
/// </summary>
/// <param name="arr">Array.</param>
/// <returns>
/// <c>True</c> if they are same.
/// </returns>
public abstract bool IsSameArray(byte[] arr);
/// <summary>
/// Seek to the given position.
/// </summary>
/// <param name="offset">Offset.</param>
/// <param name="origin">Seek origin.</param>
/// <returns>
/// Position.
/// </returns>
/// <exception cref="System.ArgumentException">
/// Unsupported seek origin: + origin
/// or
/// Seek before origin: + newPos
/// </exception>
public int Seek(int offset, SeekOrigin origin)
{
int newPos;
switch (origin)
{
case SeekOrigin.Begin:
{
newPos = offset;
break;
}
case SeekOrigin.Current:
{
newPos = Pos + offset;
break;
}
default:
throw new ArgumentException("Unsupported seek origin: " + origin);
}
if (newPos < 0)
throw new ArgumentException("Seek before origin: " + newPos);
EnsureWriteCapacity(newPos);
Pos = newPos;
return Pos;
}
/** <inheritdoc /> */
public void Dispose()
{
if (_disposed)
return;
Dispose(true);
GC.SuppressFinalize(this);
_disposed = true;
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected abstract void Dispose(bool disposing);
/// <summary>
/// Ensure capacity for write.
/// </summary>
/// <param name="cnt">Bytes count.</param>
protected abstract void EnsureWriteCapacity(int cnt);
/// <summary>
/// Ensure capacity for write and shift position.
/// </summary>
/// <param name="cnt">Bytes count.</param>
/// <returns>Position before shift.</returns>
protected int EnsureWriteCapacityAndShift(int cnt)
{
int pos0 = Pos;
EnsureWriteCapacity(Pos + cnt);
ShiftWrite(cnt);
return pos0;
}
/// <summary>
/// Ensure capacity for read.
/// </summary>
/// <param name="cnt">Bytes count.</param>
protected abstract void EnsureReadCapacity(int cnt);
/// <summary>
/// Ensure capacity for read and shift position.
/// </summary>
/// <param name="cnt">Bytes count.</param>
/// <returns>Position before shift.</returns>
protected int EnsureReadCapacityAndShift(int cnt)
{
int pos0 = Pos;
EnsureReadCapacity(cnt);
ShiftRead(cnt);
return pos0;
}
/// <summary>
/// Shift position due to write
/// </summary>
/// <param name="cnt">Bytes count.</param>
protected void ShiftWrite(int cnt)
{
Pos += cnt;
}
/// <summary>
/// Shift position due to read.
/// </summary>
/// <param name="cnt">Bytes count.</param>
private void ShiftRead(int cnt)
{
Pos += cnt;
}
/// <summary>
/// Calculate new capacity.
/// </summary>
/// <param name="curCap">Current capacity.</param>
/// <param name="reqCap">Required capacity.</param>
/// <returns>New capacity.</returns>
protected static int Capacity(int curCap, int reqCap)
{
int newCap;
if (reqCap < 256)
newCap = 256;
else
{
newCap = curCap << 1;
if (newCap < reqCap)
newCap = reqCap;
}
return newCap;
}
/// <summary>
/// Unsafe memory copy routine.
/// </summary>
/// <param name="src">Source.</param>
/// <param name="dest">Destination.</param>
/// <param name="len">Length.</param>
private static void CopyMemory(byte* src, byte* dest, int len)
{
PlatformMemoryUtils.CopyMemory(src, dest, len);
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="EasingKeyFrames.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using MS.Internal.PresentationCore;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This class is used as part of a ByteKeyFrameCollection in
/// conjunction with a KeyFrameByteAnimation to animate a
/// Byte property value along a set of key frames.
///
/// This ByteKeyFrame interpolates the between the Byte Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingByteKeyFrame : ByteKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingByteKeyFrame.
/// </summary>
public EasingByteKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingByteKeyFrame.
/// </summary>
public EasingByteKeyFrame(Byte value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingByteKeyFrame.
/// </summary>
public EasingByteKeyFrame(Byte value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingByteKeyFrame.
/// </summary>
public EasingByteKeyFrame(Byte value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingByteKeyFrame();
}
#endregion
#region ByteKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Byte InterpolateValueCore(Byte baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateByte(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingByteKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a ColorKeyFrameCollection in
/// conjunction with a KeyFrameColorAnimation to animate a
/// Color property value along a set of key frames.
///
/// This ColorKeyFrame interpolates the between the Color Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingColorKeyFrame : ColorKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingColorKeyFrame.
/// </summary>
public EasingColorKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingColorKeyFrame.
/// </summary>
public EasingColorKeyFrame(Color value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingColorKeyFrame.
/// </summary>
public EasingColorKeyFrame(Color value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingColorKeyFrame.
/// </summary>
public EasingColorKeyFrame(Color value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingColorKeyFrame();
}
#endregion
#region ColorKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Color InterpolateValueCore(Color baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateColor(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingColorKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a DecimalKeyFrameCollection in
/// conjunction with a KeyFrameDecimalAnimation to animate a
/// Decimal property value along a set of key frames.
///
/// This DecimalKeyFrame interpolates the between the Decimal Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingDecimalKeyFrame : DecimalKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingDecimalKeyFrame.
/// </summary>
public EasingDecimalKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingDecimalKeyFrame.
/// </summary>
public EasingDecimalKeyFrame(Decimal value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingDecimalKeyFrame.
/// </summary>
public EasingDecimalKeyFrame(Decimal value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingDecimalKeyFrame.
/// </summary>
public EasingDecimalKeyFrame(Decimal value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingDecimalKeyFrame();
}
#endregion
#region DecimalKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Decimal InterpolateValueCore(Decimal baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateDecimal(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingDecimalKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a DoubleKeyFrameCollection in
/// conjunction with a KeyFrameDoubleAnimation to animate a
/// Double property value along a set of key frames.
///
/// This DoubleKeyFrame interpolates the between the Double Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingDoubleKeyFrame : DoubleKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingDoubleKeyFrame.
/// </summary>
public EasingDoubleKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingDoubleKeyFrame.
/// </summary>
public EasingDoubleKeyFrame(Double value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingDoubleKeyFrame.
/// </summary>
public EasingDoubleKeyFrame(Double value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingDoubleKeyFrame.
/// </summary>
public EasingDoubleKeyFrame(Double value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingDoubleKeyFrame();
}
#endregion
#region DoubleKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Double InterpolateValueCore(Double baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateDouble(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingDoubleKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Int16KeyFrameCollection in
/// conjunction with a KeyFrameInt16Animation to animate a
/// Int16 property value along a set of key frames.
///
/// This Int16KeyFrame interpolates the between the Int16 Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingInt16KeyFrame : Int16KeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingInt16KeyFrame.
/// </summary>
public EasingInt16KeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingInt16KeyFrame.
/// </summary>
public EasingInt16KeyFrame(Int16 value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingInt16KeyFrame.
/// </summary>
public EasingInt16KeyFrame(Int16 value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingInt16KeyFrame.
/// </summary>
public EasingInt16KeyFrame(Int16 value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingInt16KeyFrame();
}
#endregion
#region Int16KeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Int16 InterpolateValueCore(Int16 baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateInt16(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingInt16KeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Int32KeyFrameCollection in
/// conjunction with a KeyFrameInt32Animation to animate a
/// Int32 property value along a set of key frames.
///
/// This Int32KeyFrame interpolates the between the Int32 Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingInt32KeyFrame : Int32KeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingInt32KeyFrame.
/// </summary>
public EasingInt32KeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingInt32KeyFrame.
/// </summary>
public EasingInt32KeyFrame(Int32 value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingInt32KeyFrame.
/// </summary>
public EasingInt32KeyFrame(Int32 value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingInt32KeyFrame.
/// </summary>
public EasingInt32KeyFrame(Int32 value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingInt32KeyFrame();
}
#endregion
#region Int32KeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Int32 InterpolateValueCore(Int32 baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateInt32(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingInt32KeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Int64KeyFrameCollection in
/// conjunction with a KeyFrameInt64Animation to animate a
/// Int64 property value along a set of key frames.
///
/// This Int64KeyFrame interpolates the between the Int64 Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingInt64KeyFrame : Int64KeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingInt64KeyFrame.
/// </summary>
public EasingInt64KeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingInt64KeyFrame.
/// </summary>
public EasingInt64KeyFrame(Int64 value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingInt64KeyFrame.
/// </summary>
public EasingInt64KeyFrame(Int64 value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingInt64KeyFrame.
/// </summary>
public EasingInt64KeyFrame(Int64 value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingInt64KeyFrame();
}
#endregion
#region Int64KeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Int64 InterpolateValueCore(Int64 baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateInt64(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingInt64KeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a PointKeyFrameCollection in
/// conjunction with a KeyFramePointAnimation to animate a
/// Point property value along a set of key frames.
///
/// This PointKeyFrame interpolates the between the Point Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingPointKeyFrame : PointKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingPointKeyFrame.
/// </summary>
public EasingPointKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingPointKeyFrame.
/// </summary>
public EasingPointKeyFrame(Point value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingPointKeyFrame.
/// </summary>
public EasingPointKeyFrame(Point value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingPointKeyFrame.
/// </summary>
public EasingPointKeyFrame(Point value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingPointKeyFrame();
}
#endregion
#region PointKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Point InterpolateValueCore(Point baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolatePoint(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingPointKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Point3DKeyFrameCollection in
/// conjunction with a KeyFramePoint3DAnimation to animate a
/// Point3D property value along a set of key frames.
///
/// This Point3DKeyFrame interpolates the between the Point3D Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingPoint3DKeyFrame : Point3DKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingPoint3DKeyFrame.
/// </summary>
public EasingPoint3DKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingPoint3DKeyFrame.
/// </summary>
public EasingPoint3DKeyFrame(Point3D value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingPoint3DKeyFrame.
/// </summary>
public EasingPoint3DKeyFrame(Point3D value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingPoint3DKeyFrame.
/// </summary>
public EasingPoint3DKeyFrame(Point3D value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingPoint3DKeyFrame();
}
#endregion
#region Point3DKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Point3D InterpolateValueCore(Point3D baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolatePoint3D(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingPoint3DKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a QuaternionKeyFrameCollection in
/// conjunction with a KeyFrameQuaternionAnimation to animate a
/// Quaternion property value along a set of key frames.
///
/// This QuaternionKeyFrame interpolates the between the Quaternion Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingQuaternionKeyFrame : QuaternionKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingQuaternionKeyFrame.
/// </summary>
public EasingQuaternionKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingQuaternionKeyFrame.
/// </summary>
public EasingQuaternionKeyFrame(Quaternion value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingQuaternionKeyFrame.
/// </summary>
public EasingQuaternionKeyFrame(Quaternion value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingQuaternionKeyFrame.
/// </summary>
public EasingQuaternionKeyFrame(Quaternion value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingQuaternionKeyFrame();
}
#endregion
#region QuaternionKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Quaternion InterpolateValueCore(Quaternion baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateQuaternion(baseValue, Value, keyFrameProgress, UseShortestPath);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingQuaternionKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Rotation3DKeyFrameCollection in
/// conjunction with a KeyFrameRotation3DAnimation to animate a
/// Rotation3D property value along a set of key frames.
///
/// This Rotation3DKeyFrame interpolates the between the Rotation3D Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingRotation3DKeyFrame : Rotation3DKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingRotation3DKeyFrame.
/// </summary>
public EasingRotation3DKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingRotation3DKeyFrame.
/// </summary>
public EasingRotation3DKeyFrame(Rotation3D value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingRotation3DKeyFrame.
/// </summary>
public EasingRotation3DKeyFrame(Rotation3D value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingRotation3DKeyFrame.
/// </summary>
public EasingRotation3DKeyFrame(Rotation3D value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingRotation3DKeyFrame();
}
#endregion
#region Rotation3DKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Rotation3D InterpolateValueCore(Rotation3D baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateRotation3D(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingRotation3DKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a RectKeyFrameCollection in
/// conjunction with a KeyFrameRectAnimation to animate a
/// Rect property value along a set of key frames.
///
/// This RectKeyFrame interpolates the between the Rect Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingRectKeyFrame : RectKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingRectKeyFrame.
/// </summary>
public EasingRectKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingRectKeyFrame.
/// </summary>
public EasingRectKeyFrame(Rect value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingRectKeyFrame.
/// </summary>
public EasingRectKeyFrame(Rect value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingRectKeyFrame.
/// </summary>
public EasingRectKeyFrame(Rect value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingRectKeyFrame();
}
#endregion
#region RectKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Rect InterpolateValueCore(Rect baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateRect(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingRectKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a SingleKeyFrameCollection in
/// conjunction with a KeyFrameSingleAnimation to animate a
/// Single property value along a set of key frames.
///
/// This SingleKeyFrame interpolates the between the Single Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingSingleKeyFrame : SingleKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingSingleKeyFrame.
/// </summary>
public EasingSingleKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingSingleKeyFrame.
/// </summary>
public EasingSingleKeyFrame(Single value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingSingleKeyFrame.
/// </summary>
public EasingSingleKeyFrame(Single value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingSingleKeyFrame.
/// </summary>
public EasingSingleKeyFrame(Single value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingSingleKeyFrame();
}
#endregion
#region SingleKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Single InterpolateValueCore(Single baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateSingle(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingSingleKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a SizeKeyFrameCollection in
/// conjunction with a KeyFrameSizeAnimation to animate a
/// Size property value along a set of key frames.
///
/// This SizeKeyFrame interpolates the between the Size Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingSizeKeyFrame : SizeKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingSizeKeyFrame.
/// </summary>
public EasingSizeKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingSizeKeyFrame.
/// </summary>
public EasingSizeKeyFrame(Size value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingSizeKeyFrame.
/// </summary>
public EasingSizeKeyFrame(Size value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingSizeKeyFrame.
/// </summary>
public EasingSizeKeyFrame(Size value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingSizeKeyFrame();
}
#endregion
#region SizeKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Size InterpolateValueCore(Size baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateSize(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingSizeKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a VectorKeyFrameCollection in
/// conjunction with a KeyFrameVectorAnimation to animate a
/// Vector property value along a set of key frames.
///
/// This VectorKeyFrame interpolates the between the Vector Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingVectorKeyFrame : VectorKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingVectorKeyFrame.
/// </summary>
public EasingVectorKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingVectorKeyFrame.
/// </summary>
public EasingVectorKeyFrame(Vector value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingVectorKeyFrame.
/// </summary>
public EasingVectorKeyFrame(Vector value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingVectorKeyFrame.
/// </summary>
public EasingVectorKeyFrame(Vector value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingVectorKeyFrame();
}
#endregion
#region VectorKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Vector InterpolateValueCore(Vector baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateVector(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingVectorKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
/// <summary>
/// This class is used as part of a Vector3DKeyFrameCollection in
/// conjunction with a KeyFrameVector3DAnimation to animate a
/// Vector3D property value along a set of key frames.
///
/// This Vector3DKeyFrame interpolates the between the Vector3D Value of
/// the previous key frame and its own Value Linearly with an EasingFunction to produce its output value.
/// </summary>
public partial class EasingVector3DKeyFrame : Vector3DKeyFrame
{
#region Constructors
/// <summary>
/// Creates a new EasingVector3DKeyFrame.
/// </summary>
public EasingVector3DKeyFrame()
: base()
{
}
/// <summary>
/// Creates a new EasingVector3DKeyFrame.
/// </summary>
public EasingVector3DKeyFrame(Vector3D value)
: this()
{
Value = value;
}
/// <summary>
/// Creates a new EasingVector3DKeyFrame.
/// </summary>
public EasingVector3DKeyFrame(Vector3D value, KeyTime keyTime)
: this()
{
Value = value;
KeyTime = keyTime;
}
/// <summary>
/// Creates a new EasingVector3DKeyFrame.
/// </summary>
public EasingVector3DKeyFrame(Vector3D value, KeyTime keyTime, IEasingFunction easingFunction)
: this()
{
Value = value;
KeyTime = keyTime;
EasingFunction = easingFunction;
}
#endregion
#region Freezable
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new EasingVector3DKeyFrame();
}
#endregion
#region Vector3DKeyFrame
/// <summary>
/// Implemented to Easingly interpolate between the baseValue and the
/// Value of this KeyFrame using the keyFrameProgress.
/// </summary>
protected override Vector3D InterpolateValueCore(Vector3D baseValue, double keyFrameProgress)
{
IEasingFunction easingFunction = EasingFunction;
if (easingFunction != null)
{
keyFrameProgress = easingFunction.Ease(keyFrameProgress);
}
if (keyFrameProgress == 0.0)
{
return baseValue;
}
else if (keyFrameProgress == 1.0)
{
return Value;
}
else
{
return AnimatedTypeHelpers.InterpolateVector3D(baseValue, Value, keyFrameProgress);
}
}
#endregion
#region Public Properties
/// <summary>
/// EasingFunctionProperty
/// </summary>
public static readonly DependencyProperty EasingFunctionProperty =
DependencyProperty.Register(
"EasingFunction",
typeof(IEasingFunction),
typeof(EasingVector3DKeyFrame));
/// <summary>
/// EasingFunction
/// </summary>
public IEasingFunction EasingFunction
{
get
{
return (IEasingFunction)GetValue(EasingFunctionProperty);
}
set
{
SetValueInternal(EasingFunctionProperty, value);
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Threading;
using MS.Utility;
using MS.Internal.WindowsBase;
#pragma warning disable 1634, 1691 // suppressing PreSharp warnings
namespace System.Windows
{
/// <summary>
/// Type cache for all DependencyObject derived types
/// </summary>
/// <remarks>
/// Every <see cref="DependencyObject"/> stores a reference to its DependencyObjectType.
/// This is an object that represents a specific system (CLR) Type.<para/>
///
/// DTypes have 2 purposes:
/// <list type="number">
/// <item>
/// More performant type operations (especially for Expressions that
/// rely heavily on type inspection)
/// </item>
/// <item>
/// Forces static constructors of base types to always run first. This
/// consistancy is necessary for components (such as Expressions) that
/// rely on static construction order for correctness.
/// </item>
/// </list>
/// </remarks>
public class DependencyObjectType
{
/// <summary>
/// Retrieve a DependencyObjectType that represents a given system (CLR) type
/// </summary>
/// <param name="systemType">The system (CLR) type to convert</param>
/// <returns>
/// A DependencyObjectType that represents the system (CLR) type (will create
/// a new one if doesn't exist)
/// </returns>
public static DependencyObjectType FromSystemType(Type systemType)
{
if (systemType == null)
{
throw new ArgumentNullException("systemType");
}
if (!typeof(DependencyObject).IsAssignableFrom(systemType))
{
#pragma warning suppress 6506 // systemType is obviously not null
throw new ArgumentException(SR.Get(SRID.DTypeNotSupportForSystemType, systemType.Name));
}
return FromSystemTypeInternal(systemType);
}
/// <summary>
/// Helper method for the public FromSystemType call but without
/// the expensive IsAssignableFrom parameter validation.
/// </summary>
[FriendAccessAllowed] // Built into Base, also used by Framework.
internal static DependencyObjectType FromSystemTypeInternal(Type systemType)
{
Debug.Assert(systemType != null && typeof(DependencyObject).IsAssignableFrom(systemType), "Invalid systemType argument");
DependencyObjectType retVal;
lock(_lock)
{
// Recursive routine to (set up if necessary) and use the
// DTypeFromCLRType hashtable that is used for the actual lookup.
retVal = FromSystemTypeRecursive( systemType );
}
return retVal;
}
// The caller must wrap this routine inside a locked block.
// This recursive routine manipulates the static hashtable DTypeFromCLRType
// and it must not be allowed to do this across multiple threads
// simultaneously.
private static DependencyObjectType FromSystemTypeRecursive(Type systemType)
{
DependencyObjectType dType;
// Map a CLR Type to a DependencyObjectType
if (!DTypeFromCLRType.TryGetValue(systemType, out dType))
{
// No DependencyObjectType found, create
dType = new DependencyObjectType();
// Store CLR type
dType._systemType = systemType;
// Store reverse mapping
DTypeFromCLRType[systemType] = dType;
// Establish base DependencyObjectType and base property count
if (systemType != typeof(DependencyObject))
{
// Get base type
dType._baseDType = FromSystemTypeRecursive(systemType.BaseType);
}
// Store DependencyObjectType zero-based Id
dType._id = DTypeCount++;
}
return dType;
}
/// <summary>
/// Zero-based unique identifier for constant-time array lookup operations
/// </summary>
/// <remarks>
/// There is no guarantee on this value. It can vary between application runs.
/// </remarks>
public int Id { get { return _id; } }
/// <summary>
/// The system (CLR) type that this DependencyObjectType represents
/// </summary>
public Type SystemType { get { return _systemType; } }
/// <summary>
/// The DependencyObjectType of the base class
/// </summary>
public DependencyObjectType BaseType
{
get
{
return _baseDType;
}
}
/// <summary>
/// Returns the name of the represented system (CLR) type
/// </summary>
public string Name { get { return SystemType.Name; } }
/// <summary>
/// Determines whether the specifed object is an instance of the current DependencyObjectType
/// </summary>
/// <param name="dependencyObject">The object to compare with the current Type</param>
/// <returns>
/// true if the current DependencyObjectType is in the inheritance hierarchy of the
/// object represented by the o parameter. false otherwise.
/// </returns>
public bool IsInstanceOfType(DependencyObject dependencyObject)
{
if (dependencyObject != null)
{
DependencyObjectType dType = dependencyObject.DependencyObjectType;
do
{
if (dType.Id == Id)
{
return true;
}
dType = dType._baseDType;
}
while (dType != null);
}
return false;
}
/// <summary>
/// Determines whether the current DependencyObjectType derives from the
/// specified DependencyObjectType
/// </summary>
/// <param name="dependencyObjectType">The DependencyObjectType to compare
/// with the current DependencyObjectType</param>
/// <returns>
/// true if the DependencyObjectType represented by the dType parameter and the
/// current DependencyObjectType represent classes, and the class represented
/// by the current DependencyObjectType derives from the class represented by
/// c; otherwise, false. This method also returns false if dType and the
/// current Type represent the same class.
/// </returns>
public bool IsSubclassOf(DependencyObjectType dependencyObjectType)
{
// Check for null and return false, since this type is never a subclass of null.
if (dependencyObjectType != null)
{
// A DependencyObjectType isn't considered a subclass of itself, so start with base type
DependencyObjectType dType = _baseDType;
while (dType != null)
{
if (dType.Id == dependencyObjectType.Id)
{
return true;
}
dType = dType._baseDType;
}
}
return false;
}
/// <summary>
/// Serves as a hash function for a particular type, suitable for use in
/// hashing algorithms and data structures like a hash table
/// </summary>
/// <returns>The DependencyObjectType's Id</returns>
public override int GetHashCode()
{
return _id;
}
// DTypes may not be constructed outside of FromSystemType
private DependencyObjectType()
{
}
private int _id;
private Type _systemType;
private DependencyObjectType _baseDType;
// Synchronized: Covered by DispatcherLock
private static Dictionary<Type, DependencyObjectType> DTypeFromCLRType = new Dictionary<Type, DependencyObjectType>();
// Synchronized: Covered by DispatcherLock
private static int DTypeCount = 0;
private static object _lock = new object();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.CompilerServices;
using System.Transactions;
namespace System.Data.Common
{
internal static partial class ADP
{
// The class ADP defines the exceptions that are specific to the Adapters.
// The class contains functions that take the proper informational variables and then construct
// the appropriate exception with an error string obtained from the resource framework.
// The exception is then returned to the caller, so that the caller may then throw from its
// location so that the catcher of the exception will have the appropriate call stack.
// This class is used so that there will be compile time checking of error messages.
internal static Exception ExceptionWithStackTrace(Exception e)
{
try
{
throw e;
}
catch (Exception caught)
{
return caught;
}
}
//
// COM+ exceptions
//
internal static IndexOutOfRangeException IndexOutOfRange(int value)
{
IndexOutOfRangeException e = new IndexOutOfRangeException(value.ToString(CultureInfo.InvariantCulture));
return e;
}
internal static IndexOutOfRangeException IndexOutOfRange()
{
IndexOutOfRangeException e = new IndexOutOfRangeException();
return e;
}
internal static TimeoutException TimeoutException(string error)
{
TimeoutException e = new TimeoutException(error);
return e;
}
internal static InvalidOperationException InvalidOperation(string error, Exception inner)
{
InvalidOperationException e = new InvalidOperationException(error, inner);
return e;
}
internal static OverflowException Overflow(string error)
{
return Overflow(error, null);
}
internal static OverflowException Overflow(string error, Exception inner)
{
OverflowException e = new OverflowException(error, inner);
return e;
}
internal static PlatformNotSupportedException DbTypeNotSupported(string dbType)
{
PlatformNotSupportedException e = new PlatformNotSupportedException(SR.GetString(SR.SQL_DbTypeNotSupportedOnThisPlatform, dbType));
return e;
}
internal static InvalidCastException InvalidCast()
{
InvalidCastException e = new InvalidCastException();
return e;
}
internal static IOException IO(string error)
{
IOException e = new IOException(error);
return e;
}
internal static IOException IO(string error, Exception inner)
{
IOException e = new IOException(error, inner);
return e;
}
internal static ObjectDisposedException ObjectDisposed(object instance)
{
ObjectDisposedException e = new ObjectDisposedException(instance.GetType().Name);
return e;
}
internal static Exception DataTableDoesNotExist(string collectionName)
{
return Argument(SR.GetString(SR.MDF_DataTableDoesNotExist, collectionName));
}
internal static InvalidOperationException MethodCalledTwice(string method)
{
InvalidOperationException e = new InvalidOperationException(SR.GetString(SR.ADP_CalledTwice, method));
return e;
}
// IDbCommand.CommandType
internal static ArgumentOutOfRangeException InvalidCommandType(CommandType value)
{
#if DEBUG
switch (value)
{
case CommandType.Text:
case CommandType.StoredProcedure:
case CommandType.TableDirect:
Debug.Assert(false, "valid CommandType " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(CommandType), (int)value);
}
// IDbConnection.BeginTransaction, OleDbTransaction.Begin
internal static ArgumentOutOfRangeException InvalidIsolationLevel(IsolationLevel value)
{
#if DEBUG
switch (value)
{
case IsolationLevel.Unspecified:
case IsolationLevel.Chaos:
case IsolationLevel.ReadUncommitted:
case IsolationLevel.ReadCommitted:
case IsolationLevel.RepeatableRead:
case IsolationLevel.Serializable:
case IsolationLevel.Snapshot:
Debug.Fail("valid IsolationLevel " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(IsolationLevel), (int)value);
}
// IDataParameter.Direction
internal static ArgumentOutOfRangeException InvalidParameterDirection(ParameterDirection value)
{
#if DEBUG
switch (value)
{
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
Debug.Assert(false, "valid ParameterDirection " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(ParameterDirection), (int)value);
}
internal static Exception TooManyRestrictions(string collectionName)
{
return Argument(SR.GetString(SR.MDF_TooManyRestrictions, collectionName));
}
// IDbCommand.UpdateRowSource
internal static ArgumentOutOfRangeException InvalidUpdateRowSource(UpdateRowSource value)
{
#if DEBUG
switch (value)
{
case UpdateRowSource.None:
case UpdateRowSource.OutputParameters:
case UpdateRowSource.FirstReturnedRecord:
case UpdateRowSource.Both:
Debug.Assert(false, "valid UpdateRowSource " + value.ToString());
break;
}
#endif
return InvalidEnumerationValue(typeof(UpdateRowSource), (int)value);
}
//
// DbConnectionOptions, DataAccess
//
internal static ArgumentException InvalidMinMaxPoolSizeValues()
{
return ADP.Argument(SR.GetString(SR.ADP_InvalidMinMaxPoolSizeValues));
}
//
// DbConnection
//
internal static InvalidOperationException NoConnectionString()
{
return InvalidOperation(SR.GetString(SR.ADP_NoConnectionString));
}
internal static Exception MethodNotImplemented([CallerMemberName] string methodName = "")
{
return NotImplemented.ByDesignWithMessage(methodName);
}
internal static Exception QueryFailed(string collectionName, Exception e)
{
return InvalidOperation(SR.GetString(SR.MDF_QueryFailed, collectionName), e);
}
//
// : DbConnectionOptions, DataAccess, SqlClient
//
internal static Exception InvalidConnectionOptionValueLength(string key, int limit)
{
return Argument(SR.GetString(SR.ADP_InvalidConnectionOptionValueLength, key, limit));
}
internal static Exception MissingConnectionOptionValue(string key, string requiredAdditionalKey)
{
return Argument(SR.GetString(SR.ADP_MissingConnectionOptionValue, key, requiredAdditionalKey));
}
//
// DbConnectionPool and related
//
internal static Exception PooledOpenTimeout()
{
return ADP.InvalidOperation(SR.GetString(SR.ADP_PooledOpenTimeout));
}
internal static Exception NonPooledOpenTimeout()
{
return ADP.TimeoutException(SR.GetString(SR.ADP_NonPooledOpenTimeout));
}
//
// DbProviderException
//
internal static InvalidOperationException TransactionConnectionMismatch()
{
return Provider(SR.GetString(SR.ADP_TransactionConnectionMismatch));
}
internal static InvalidOperationException TransactionRequired(string method)
{
return Provider(SR.GetString(SR.ADP_TransactionRequired, method));
}
internal static Exception CommandTextRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_CommandTextRequired, method));
}
internal static Exception NoColumns()
{
return Argument(SR.GetString(SR.MDF_NoColumns));
}
internal static InvalidOperationException ConnectionRequired(string method)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionRequired, method));
}
internal static InvalidOperationException OpenConnectionRequired(string method, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionRequired, method, ADP.ConnectionStateMsg(state)));
}
internal static Exception OpenReaderExists()
{
return OpenReaderExists(null);
}
internal static Exception OpenReaderExists(Exception e)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenReaderExists), e);
}
//
// DbDataReader
//
internal static Exception NonSeqByteAccess(long badIndex, long currIndex, string method)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSeqByteAccess, badIndex.ToString(CultureInfo.InvariantCulture), currIndex.ToString(CultureInfo.InvariantCulture), method));
}
internal static Exception InvalidXml()
{
return Argument(SR.GetString(SR.MDF_InvalidXml));
}
internal static Exception NegativeParameter(string parameterName)
{
return InvalidOperation(SR.GetString(SR.ADP_NegativeParameter, parameterName));
}
internal static Exception InvalidXmlMissingColumn(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlMissingColumn, collectionName, columnName));
}
//
// SqlMetaData, SqlTypes, SqlClient
//
internal static Exception InvalidMetaDataValue()
{
return ADP.Argument(SR.GetString(SR.ADP_InvalidMetaDataValue));
}
internal static InvalidOperationException NonSequentialColumnAccess(int badCol, int currCol)
{
return InvalidOperation(SR.GetString(SR.ADP_NonSequentialColumnAccess, badCol.ToString(CultureInfo.InvariantCulture), currCol.ToString(CultureInfo.InvariantCulture)));
}
internal static Exception InvalidXmlInvalidValue(string collectionName, string columnName)
{
return Argument(SR.GetString(SR.MDF_InvalidXmlInvalidValue, collectionName, columnName));
}
internal static Exception CollectionNameIsNotUnique(string collectionName)
{
return Argument(SR.GetString(SR.MDF_CollectionNameISNotUnique, collectionName));
}
//
// : IDbCommand
//
internal static Exception InvalidCommandTimeout(int value, [CallerMemberName] string property = "")
{
return Argument(SR.GetString(SR.ADP_InvalidCommandTimeout, value.ToString(CultureInfo.InvariantCulture)), property);
}
internal static Exception UninitializedParameterSize(int index, Type dataType)
{
return InvalidOperation(SR.GetString(SR.ADP_UninitializedParameterSize, index.ToString(CultureInfo.InvariantCulture), dataType.Name));
}
internal static Exception UnableToBuildCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnableToBuildCollection, collectionName));
}
internal static Exception PrepareParameterType(DbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterType, cmd.GetType().Name));
}
internal static Exception UndefinedCollection(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UndefinedCollection, collectionName));
}
internal static Exception UnsupportedVersion(string collectionName)
{
return Argument(SR.GetString(SR.MDF_UnsupportedVersion, collectionName));
}
internal static Exception AmbigousCollectionName(string collectionName)
{
return Argument(SR.GetString(SR.MDF_AmbigousCollectionName, collectionName));
}
internal static Exception PrepareParameterSize(DbCommand cmd)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterSize, cmd.GetType().Name));
}
internal static Exception PrepareParameterScale(DbCommand cmd, string type)
{
return InvalidOperation(SR.GetString(SR.ADP_PrepareParameterScale, cmd.GetType().Name, type));
}
internal static Exception MissingDataSourceInformationColumn()
{
return Argument(SR.GetString(SR.MDF_MissingDataSourceInformationColumn));
}
internal static Exception IncorrectNumberOfDataSourceInformationRows()
{
return Argument(SR.GetString(SR.MDF_IncorrectNumberOfDataSourceInformationRows));
}
internal static Exception MismatchedAsyncResult(string expectedMethod, string gotMethod)
{
return InvalidOperation(SR.GetString(SR.ADP_MismatchedAsyncResult, expectedMethod, gotMethod));
}
//
// : ConnectionUtil
//
internal static Exception ClosedConnectionError()
{
return InvalidOperation(SR.GetString(SR.ADP_ClosedConnectionError));
}
internal static Exception ConnectionAlreadyOpen(ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_ConnectionAlreadyOpen, ADP.ConnectionStateMsg(state)));
}
internal static Exception TransactionPresent()
{
return InvalidOperation(SR.GetString(SR.ADP_TransactionPresent));
}
internal static Exception LocalTransactionPresent()
{
return InvalidOperation(SR.GetString(SR.ADP_LocalTransactionPresent));
}
internal static Exception OpenConnectionPropertySet(string property, ConnectionState state)
{
return InvalidOperation(SR.GetString(SR.ADP_OpenConnectionPropertySet, property, ADP.ConnectionStateMsg(state)));
}
internal static Exception EmptyDatabaseName()
{
return Argument(SR.GetString(SR.ADP_EmptyDatabaseName));
}
internal enum ConnectionError
{
BeginGetConnectionReturnsNull,
GetConnectionReturnsNull,
ConnectionOptionsMissing,
CouldNotSwitchToClosedPreviouslyOpenedState,
}
internal static Exception MissingRestrictionColumn()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionColumn));
}
internal static Exception InternalConnectionError(ConnectionError internalError)
{
return InvalidOperation(SR.GetString(SR.ADP_InternalConnectionError, (int)internalError));
}
internal static Exception InvalidConnectRetryCountValue()
{
return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryCountValue));
}
internal static Exception MissingRestrictionRow()
{
return Argument(SR.GetString(SR.MDF_MissingRestrictionRow));
}
internal static Exception InvalidConnectRetryIntervalValue()
{
return Argument(SR.GetString(SR.SQLCR_InvalidConnectRetryIntervalValue));
}
//
// : DbDataReader
//
internal static InvalidOperationException AsyncOperationPending()
{
return InvalidOperation(SR.GetString(SR.ADP_PendingAsyncOperation));
}
//
// : Stream
//
internal static IOException ErrorReadingFromStream(Exception internalException)
{
return IO(SR.GetString(SR.SqlMisc_StreamErrorMessage), internalException);
}
internal static ArgumentException InvalidDataType(string typeName)
{
return Argument(SR.GetString(SR.ADP_InvalidDataType, typeName));
}
internal static ArgumentException UnknownDataType(Type dataType)
{
return Argument(SR.GetString(SR.ADP_UnknownDataType, dataType.FullName));
}
internal static ArgumentException DbTypeNotSupported(DbType type, Type enumtype)
{
return Argument(SR.GetString(SR.ADP_DbTypeNotSupported, type.ToString(), enumtype.Name));
}
internal static ArgumentException InvalidOffsetValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidOffsetValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static ArgumentException InvalidSizeValue(int value)
{
return Argument(SR.GetString(SR.ADP_InvalidSizeValue, value.ToString(CultureInfo.InvariantCulture)));
}
internal static ArgumentException ParameterValueOutOfRange(Decimal value)
{
return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString((IFormatProvider)null)));
}
internal static ArgumentException ParameterValueOutOfRange(SqlDecimal value)
{
return ADP.Argument(SR.GetString(SR.ADP_ParameterValueOutOfRange, value.ToString()));
}
internal static ArgumentException VersionDoesNotSupportDataType(string typeName)
{
return Argument(SR.GetString(SR.ADP_VersionDoesNotSupportDataType, typeName));
}
internal static Exception ParameterConversionFailed(object value, Type destType, Exception inner)
{
Debug.Assert(null != value, "null value on conversion failure");
Debug.Assert(null != inner, "null inner on conversion failure");
Exception e;
string message = SR.GetString(SR.ADP_ParameterConversionFailed, value.GetType().Name, destType.Name);
if (inner is ArgumentException)
{
e = new ArgumentException(message, inner);
}
else if (inner is FormatException)
{
e = new FormatException(message, inner);
}
else if (inner is InvalidCastException)
{
e = new InvalidCastException(message, inner);
}
else if (inner is OverflowException)
{
e = new OverflowException(message, inner);
}
else
{
e = inner;
}
return e;
}
//
// : IDataParameterCollection
//
internal static Exception ParametersMappingIndex(int index, DbParameterCollection collection)
{
return CollectionIndexInt32(index, collection.GetType(), collection.Count);
}
internal static Exception ParametersSourceIndex(string parameterName, DbParameterCollection collection, Type parameterType)
{
return CollectionIndexString(parameterType, ADP.ParameterName, parameterName, collection.GetType());
}
internal static Exception ParameterNull(string parameter, DbParameterCollection collection, Type parameterType)
{
return CollectionNullValue(parameter, collection.GetType(), parameterType);
}
internal static Exception UndefinedPopulationMechanism(string populationMechanism)
{
throw new NotImplementedException();
}
internal static Exception InvalidParameterType(DbParameterCollection collection, Type parameterType, object invalidValue)
{
return CollectionInvalidType(collection.GetType(), parameterType, invalidValue);
}
//
// : IDbTransaction
//
internal static Exception ParallelTransactionsNotSupported(DbConnection obj)
{
return InvalidOperation(SR.GetString(SR.ADP_ParallelTransactionsNotSupported, obj.GetType().Name));
}
internal static Exception TransactionZombied(DbTransaction obj)
{
return InvalidOperation(SR.GetString(SR.ADP_TransactionZombied, obj.GetType().Name));
}
// global constant strings
internal const string Parameter = "Parameter";
internal const string ParameterName = "ParameterName";
internal const string ParameterSetPosition = "set_Position";
internal const int DefaultCommandTimeout = 30;
internal const float FailoverTimeoutStep = 0.08F; // fraction of timeout to use for fast failover connections
// security issue, don't rely upon public static readonly values
internal static readonly string StrEmpty = ""; // String.Empty
internal const int CharSize = sizeof(char);
internal static Delegate FindBuilder(MulticastDelegate mcd)
{
if (null != mcd)
{
foreach (Delegate del in mcd.GetInvocationList())
{
if (del.Target is DbCommandBuilder)
return del;
}
}
return null;
}
internal static void TimerCurrent(out long ticks)
{
ticks = DateTime.UtcNow.ToFileTimeUtc();
}
internal static long TimerCurrent()
{
return DateTime.UtcNow.ToFileTimeUtc();
}
internal static long TimerFromSeconds(int seconds)
{
long result = checked((long)seconds * TimeSpan.TicksPerSecond);
return result;
}
internal static long TimerFromMilliseconds(long milliseconds)
{
long result = checked(milliseconds * TimeSpan.TicksPerMillisecond);
return result;
}
internal static bool TimerHasExpired(long timerExpire)
{
bool result = TimerCurrent() > timerExpire;
return result;
}
internal static long TimerRemaining(long timerExpire)
{
long timerNow = TimerCurrent();
long result = checked(timerExpire - timerNow);
return result;
}
internal static long TimerRemainingMilliseconds(long timerExpire)
{
long result = TimerToMilliseconds(TimerRemaining(timerExpire));
return result;
}
internal static long TimerRemainingSeconds(long timerExpire)
{
long result = TimerToSeconds(TimerRemaining(timerExpire));
return result;
}
internal static long TimerToMilliseconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerMillisecond;
return result;
}
private static long TimerToSeconds(long timerValue)
{
long result = timerValue / TimeSpan.TicksPerSecond;
return result;
}
internal static string MachineName()
{
return Environment.MachineName;
}
internal static Transaction GetCurrentTransaction()
{
return Transaction.Current;
}
internal static bool IsDirection(DbParameter value, ParameterDirection condition)
{
#if DEBUG
IsDirectionValid(condition);
#endif
return (condition == (condition & value.Direction));
}
#if DEBUG
private static void IsDirectionValid(ParameterDirection value)
{
switch (value)
{ // @perfnote: Enum.IsDefined
case ParameterDirection.Input:
case ParameterDirection.Output:
case ParameterDirection.InputOutput:
case ParameterDirection.ReturnValue:
break;
default:
throw ADP.InvalidParameterDirection(value);
}
}
#endif
internal static void IsNullOrSqlType(object value, out bool isNull, out bool isSqlType)
{
if ((value == null) || (value == DBNull.Value))
{
isNull = true;
isSqlType = false;
}
else
{
INullable nullable = (value as INullable);
if (nullable != null)
{
isNull = nullable.IsNull;
// Duplicated from DataStorage.cs
// For back-compat, SqlXml is not in this list
isSqlType = ((value is SqlBinary) ||
(value is SqlBoolean) ||
(value is SqlByte) ||
(value is SqlBytes) ||
(value is SqlChars) ||
(value is SqlDateTime) ||
(value is SqlDecimal) ||
(value is SqlDouble) ||
(value is SqlGuid) ||
(value is SqlInt16) ||
(value is SqlInt32) ||
(value is SqlInt64) ||
(value is SqlMoney) ||
(value is SqlSingle) ||
(value is SqlString));
}
else
{
isNull = false;
isSqlType = false;
}
}
}
internal static Exception AmbientTransactionIsNotSupported()
{
return new NotSupportedException(SR.AmbientTransactionsNotSupported);
}
private static Version s_systemDataVersion;
internal static Version GetAssemblyVersion()
{
// NOTE: Using lazy thread-safety since we don't care if two threads both happen to update the value at the same time
if (s_systemDataVersion == null)
{
s_systemDataVersion = new Version(ThisAssembly.InformationalVersion);
}
return s_systemDataVersion;
}
internal static readonly string[] AzureSqlServerEndpoints = {SR.GetString(SR.AZURESQL_GenericEndpoint),
SR.GetString(SR.AZURESQL_GermanEndpoint),
SR.GetString(SR.AZURESQL_UsGovEndpoint),
SR.GetString(SR.AZURESQL_ChinaEndpoint)};
// This method assumes dataSource parameter is in TCP connection string format.
internal static bool IsAzureSqlServerEndpoint(string dataSource)
{
// remove server port
int i = dataSource.LastIndexOf(',');
if (i >= 0)
{
dataSource = dataSource.Substring(0, i);
}
// check for the instance name
i = dataSource.LastIndexOf('\\');
if (i >= 0)
{
dataSource = dataSource.Substring(0, i);
}
// trim redundant whitespace
dataSource = dataSource.Trim();
// check if servername end with any azure endpoints
for (i = 0; i < AzureSqlServerEndpoints.Length; i++)
{
if (dataSource.EndsWith(AzureSqlServerEndpoints[i], StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
return false;
}
internal static ArgumentOutOfRangeException InvalidDataRowVersion(DataRowVersion value)
{
#if DEBUG
switch (value)
{
case DataRowVersion.Default:
case DataRowVersion.Current:
case DataRowVersion.Original:
case DataRowVersion.Proposed:
Debug.Fail($"Invalid DataRowVersion {value}");
break;
}
#endif
return InvalidEnumerationValue(typeof(DataRowVersion), (int)value);
}
internal static ArgumentException SingleValuedProperty(string propertyName, string value)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_SingleValuedProperty, propertyName, value));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException DoubleValuedProperty(string propertyName, string value1, string value2)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_DoubleValuedProperty, propertyName, value1, value2));
TraceExceptionAsReturnValue(e);
return e;
}
internal static ArgumentException InvalidPrefixSuffix()
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_InvalidPrefixSuffix));
TraceExceptionAsReturnValue(e);
return e;
}
// the return value is true if the string was quoted and false if it was not
// this allows the caller to determine if it is an error or not for the quotedString to not be quoted
internal static bool RemoveStringQuotes(string quotePrefix, string quoteSuffix, string quotedString, out string unquotedString)
{
int prefixLength = quotePrefix != null ? quotePrefix.Length : 0;
int suffixLength = quoteSuffix != null ? quoteSuffix.Length : 0;
if ((suffixLength + prefixLength) == 0)
{
unquotedString = quotedString;
return true;
}
if (quotedString == null)
{
unquotedString = quotedString;
return false;
}
int quotedStringLength = quotedString.Length;
// is the source string too short to be quoted
if (quotedStringLength < prefixLength + suffixLength)
{
unquotedString = quotedString;
return false;
}
// is the prefix present?
if (prefixLength > 0)
{
if (!quotedString.StartsWith(quotePrefix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
}
// is the suffix present?
if (suffixLength > 0)
{
if (!quotedString.EndsWith(quoteSuffix, StringComparison.Ordinal))
{
unquotedString = quotedString;
return false;
}
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - (prefixLength + suffixLength)).Replace(quoteSuffix + quoteSuffix, quoteSuffix);
}
else
{
unquotedString = quotedString.Substring(prefixLength, quotedStringLength - prefixLength);
}
return true;
}
internal static ArgumentOutOfRangeException InvalidCommandBehavior(CommandBehavior value)
{
Debug.Assert((0 > (int)value) || ((int)value > 0x3F), "valid CommandType " + value.ToString());
return InvalidEnumerationValue(typeof(CommandBehavior), (int)value);
}
internal static void ValidateCommandBehavior(CommandBehavior value)
{
if (((int)value < 0) || (0x3F < (int)value))
{
throw InvalidCommandBehavior(value);
}
}
internal static ArgumentOutOfRangeException NotSupportedCommandBehavior(CommandBehavior value, string method)
{
return NotSupportedEnumerationValue(typeof(CommandBehavior), value.ToString(), method);
}
internal static ArgumentException BadParameterName(string parameterName)
{
ArgumentException e = new ArgumentException(SR.GetString(SR.ADP_BadParameterName, parameterName));
TraceExceptionAsReturnValue(e);
return e;
}
internal static Exception DeriveParametersNotSupported(IDbCommand value)
{
return DataAdapter(SR.GetString(SR.ADP_DeriveParametersNotSupported, value.GetType().Name, value.CommandType.ToString()));
}
internal static Exception NoStoredProcedureExists(string sproc)
{
return InvalidOperation(SR.GetString(SR.ADP_NoStoredProcedureExists, sproc));
}
//
// DbProviderException
//
internal static InvalidOperationException TransactionCompletedButNotDisposed()
{
return Provider(SR.GetString(SR.ADP_TransactionCompletedButNotDisposed));
}
}
}
| |
// 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 files defines the following types:
* - _IOCompletionCallback
* - OverlappedData
* - Overlapped
*/
/*=============================================================================
**
**
**
** Purpose: Class for converting information to and from the native
** overlapped structure used in asynchronous file i/o
**
**
=============================================================================*/
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Runtime.ConstrainedExecution;
using System.Diagnostics;
using System.Collections.Concurrent;
using Internal.Runtime.CompilerServices;
namespace System.Threading
{
#region class _IOCompletionCallback
internal class _IOCompletionCallback
{
private IOCompletionCallback _ioCompletionCallback;
private ExecutionContext _executionContext;
private uint _errorCode; // Error code
private uint _numBytes; // No. of bytes transferred
private unsafe NativeOverlapped* _pOVERLAP;
internal _IOCompletionCallback(IOCompletionCallback ioCompletionCallback)
{
_ioCompletionCallback = ioCompletionCallback;
_executionContext = ExecutionContext.Capture();
}
private static ContextCallback s_ccb = new ContextCallback(IOCompletionCallback_Context);
private static unsafe void IOCompletionCallback_Context(Object state)
{
_IOCompletionCallback helper = (_IOCompletionCallback)state;
Debug.Assert(helper != null, "_IOCompletionCallback cannot be null");
helper._ioCompletionCallback(helper._errorCode, helper._numBytes, helper._pOVERLAP);
}
internal static unsafe void PerformIOCompletionCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP)
{
Overlapped overlapped;
_IOCompletionCallback helper;
do
{
overlapped = OverlappedData.GetOverlappedFromNative(pOVERLAP).m_overlapped;
helper = overlapped.iocbHelper;
if (helper == null || helper._executionContext == null || helper._executionContext == ExecutionContext.Default)
{
// We got here because of UnsafePack (or) Pack with EC flow supressed
IOCompletionCallback callback = overlapped.UserCallback;
callback(errorCode, numBytes, pOVERLAP);
}
else
{
// We got here because of Pack
helper._errorCode = errorCode;
helper._numBytes = numBytes;
helper._pOVERLAP = pOVERLAP;
ExecutionContext.Run(helper._executionContext, s_ccb, helper);
}
//Quickly check the VM again, to see if a packet has arrived.
//OverlappedData.CheckVMForIOPacket(out pOVERLAP, out errorCode, out numBytes);
pOVERLAP = null;
} while (pOVERLAP != null);
}
}
#endregion class _IOCompletionCallback
#region class OverlappedData
internal sealed class OverlappedData
{
// The offset of m_nativeOverlapped field from m_pEEType
private static int s_nativeOverlappedOffset;
internal IAsyncResult m_asyncResult;
internal IOCompletionCallback m_iocb;
internal _IOCompletionCallback m_iocbHelper;
internal Overlapped m_overlapped;
private Object m_userObject;
private IntPtr m_pinSelf;
private GCHandle[] m_pinnedData;
internal NativeOverlapped m_nativeOverlapped;
// Adding an empty default ctor for annotation purposes
internal OverlappedData() { }
~OverlappedData()
{
if (m_pinnedData != null)
{
for (int i = 0; i < m_pinnedData.Length; i++)
{
if (m_pinnedData[i].IsAllocated)
{
m_pinnedData[i].Free();
}
}
}
}
internal void ReInitialize()
{
m_asyncResult = null;
m_iocb = null;
m_iocbHelper = null;
m_overlapped = null;
m_userObject = null;
Debug.Assert(m_pinSelf == IntPtr.Zero, "OverlappedData has not been freed: m_pinSelf");
m_pinSelf = IntPtr.Zero;
// Reuse m_pinnedData array
m_nativeOverlapped = default(NativeOverlapped);
}
internal unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
if (m_pinSelf != IntPtr.Zero)
{
throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack);
}
m_iocb = iocb;
m_iocbHelper = (iocb != null) ? new _IOCompletionCallback(iocb) : null;
m_userObject = userData;
return AllocateNativeOverlapped();
}
internal unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
if (m_pinSelf != IntPtr.Zero)
{
throw new InvalidOperationException(SR.InvalidOperation_Overlapped_Pack);
}
m_iocb = iocb;
m_iocbHelper = null;
m_userObject = userData;
return AllocateNativeOverlapped();
}
internal IntPtr UserHandle
{
get { return m_nativeOverlapped.EventHandle; }
set { m_nativeOverlapped.EventHandle = value; }
}
private unsafe NativeOverlapped* AllocateNativeOverlapped()
{
if (m_userObject != null)
{
if (m_userObject.GetType() == typeof(Object[]))
{
Object[] objArray = (Object[])m_userObject;
if (m_pinnedData == null || m_pinnedData.Length < objArray.Length)
Array.Resize(ref m_pinnedData, objArray.Length);
for (int i = 0; i < objArray.Length; i++)
{
if (!m_pinnedData[i].IsAllocated)
m_pinnedData[i] = GCHandle.Alloc(objArray[i], GCHandleType.Pinned);
else
m_pinnedData[i].Target = objArray[i];
}
}
else
{
if (m_pinnedData == null || m_pinnedData.Length < 1)
m_pinnedData = new GCHandle[1];
if (!m_pinnedData[0].IsAllocated)
m_pinnedData[0] = GCHandle.Alloc(m_userObject, GCHandleType.Pinned);
else
m_pinnedData[0].Target = m_userObject;
}
}
m_pinSelf = RuntimeImports.RhHandleAlloc(this, GCHandleType.Pinned);
fixed (NativeOverlapped* pNativeOverlapped = &m_nativeOverlapped)
{
return pNativeOverlapped;
}
}
internal static unsafe void FreeNativeOverlapped(NativeOverlapped* nativeOverlappedPtr)
{
OverlappedData overlappedData = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr);
overlappedData.FreeNativeOverlapped();
}
private void FreeNativeOverlapped()
{
IntPtr pinSelf = m_pinSelf;
if (pinSelf != IntPtr.Zero)
{
if (Interlocked.CompareExchange(ref m_pinSelf, IntPtr.Zero, pinSelf) == pinSelf)
{
if (m_pinnedData != null)
{
for (int i = 0; i < m_pinnedData.Length; i++)
{
if (m_pinnedData[i].IsAllocated && (m_pinnedData[i].Target != null))
{
m_pinnedData[i].Target = null;
}
}
}
RuntimeImports.RhHandleFree(pinSelf);
}
}
}
internal static unsafe OverlappedData GetOverlappedFromNative(NativeOverlapped* nativeOverlappedPtr)
{
if (s_nativeOverlappedOffset == 0)
{
CalculateNativeOverlappedOffset();
}
void* pOverlappedData = (byte*)nativeOverlappedPtr - s_nativeOverlappedOffset;
return Unsafe.Read<OverlappedData>(&pOverlappedData);
}
private static unsafe void CalculateNativeOverlappedOffset()
{
OverlappedData overlappedData = new OverlappedData();
fixed (IntPtr* pEETypePtr = &overlappedData.m_pEEType)
fixed (NativeOverlapped* pNativeOverlapped = &overlappedData.m_nativeOverlapped)
{
s_nativeOverlappedOffset = (int)((byte*)pNativeOverlapped - (byte*)pEETypePtr);
}
}
}
#endregion class OverlappedData
#region class Overlapped
public class Overlapped
{
private static PinnableBufferCache s_overlappedDataCache = new PinnableBufferCache("System.Threading.OverlappedData", () => new OverlappedData());
private OverlappedData m_overlappedData;
public Overlapped()
{
m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
}
public Overlapped(int offsetLo, int offsetHi, IntPtr hEvent, IAsyncResult ar)
{
m_overlappedData = (OverlappedData)s_overlappedDataCache.Allocate();
m_overlappedData.m_overlapped = this;
m_overlappedData.m_nativeOverlapped.OffsetLow = offsetLo;
m_overlappedData.m_nativeOverlapped.OffsetHigh = offsetHi;
m_overlappedData.UserHandle = hEvent;
m_overlappedData.m_asyncResult = ar;
}
[Obsolete("This constructor is not 64-bit compatible. Use the constructor that takes an IntPtr for the event handle. http://go.microsoft.com/fwlink/?linkid=14202")]
public Overlapped(int offsetLo, int offsetHi, int hEvent, IAsyncResult ar) : this(offsetLo, offsetHi, new IntPtr(hEvent), ar)
{
}
public IAsyncResult AsyncResult
{
get { return m_overlappedData.m_asyncResult; }
set { m_overlappedData.m_asyncResult = value; }
}
public int OffsetLow
{
get { return m_overlappedData.m_nativeOverlapped.OffsetLow; }
set { m_overlappedData.m_nativeOverlapped.OffsetLow = value; }
}
public int OffsetHigh
{
get { return m_overlappedData.m_nativeOverlapped.OffsetHigh; }
set { m_overlappedData.m_nativeOverlapped.OffsetHigh = value; }
}
[Obsolete("This property is not 64-bit compatible. Use EventHandleIntPtr instead. http://go.microsoft.com/fwlink/?linkid=14202")]
public int EventHandle
{
get { return m_overlappedData.UserHandle.ToInt32(); }
set { m_overlappedData.UserHandle = new IntPtr(value); }
}
public IntPtr EventHandleIntPtr
{
get { return m_overlappedData.UserHandle; }
set { m_overlappedData.UserHandle = value; }
}
internal _IOCompletionCallback iocbHelper
{
get { return m_overlappedData.m_iocbHelper; }
}
internal IOCompletionCallback UserCallback
{
get { return m_overlappedData.m_iocb; }
}
/*====================================================================
* Packs a managed overlapped class into native Overlapped struct.
* Roots the iocb and stores it in the ReservedCOR field of native Overlapped
* Pins the native Overlapped struct and returns the pinned index.
====================================================================*/
[Obsolete("This method is not safe. Use Pack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb)
{
return Pack(iocb, null);
}
[CLSCompliant(false)]
public unsafe NativeOverlapped* Pack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.Pack(iocb, userData);
}
[Obsolete("This method is not safe. Use UnsafePack (iocb, userData) instead. http://go.microsoft.com/fwlink/?linkid=14202")]
[CLSCompliant(false)]
public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb)
{
return UnsafePack(iocb, null);
}
[CLSCompliant(false)]
public unsafe NativeOverlapped* UnsafePack(IOCompletionCallback iocb, Object userData)
{
return m_overlappedData.UnsafePack(iocb, userData);
}
/*====================================================================
* Unpacks an unmanaged native Overlapped struct.
* Unpins the native Overlapped struct
====================================================================*/
[CLSCompliant(false)]
public static unsafe Overlapped Unpack(NativeOverlapped* nativeOverlappedPtr)
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException(nameof(nativeOverlappedPtr));
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
return overlapped;
}
[CLSCompliant(false)]
public static unsafe void Free(NativeOverlapped* nativeOverlappedPtr)
{
if (nativeOverlappedPtr == null)
throw new ArgumentNullException(nameof(nativeOverlappedPtr));
Overlapped overlapped = OverlappedData.GetOverlappedFromNative(nativeOverlappedPtr).m_overlapped;
OverlappedData.FreeNativeOverlapped(nativeOverlappedPtr);
OverlappedData overlappedData = overlapped.m_overlappedData;
overlapped.m_overlappedData = null;
overlappedData.ReInitialize();
s_overlappedDataCache.Free(overlappedData);
}
}
#endregion class Overlapped
} // namespace
| |
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 frmFloatRepre : System.Windows.Forms.Form
{
//Save Default ....
int g_Default;
int g_Defailt2;
int grsKey_ID;
int g_FloatU;
bool g_Enough;
bool g_NewKy;
bool g_FloatU_1;
bool g_floatSet;
bool grsKeyboard;
List<TextBox> txtFloat = new List<TextBox>();
private void loadLanguage()
{
//frmFloatRepre = No Code [Denomination Details]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmFloatRepre.Caption = rsLang("LanguageLayoutLnk_Description"): frmFloatRepre.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){Command1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;Command1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//Label1 = No Code [Float Details]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label1.Caption = rsLang("LanguageLayoutLnk_Description"): Label1.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label3 = No Code [Float Name]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label3.Caption = rsLang("LanguageLayoutLnk_Description"): Label3.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label5 = No Code [Float Type]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label5.Caption = rsLang("LanguageLayoutLnk_Description"): COMPONENT(0).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label9 = No Code [Float Value]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label9.Caption = rsLang("LanguageLayoutLnk_Description"): Label9.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label4 = No Code [Float Pack]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label4.Caption = rsLang("LanguageLayoutLnk_Description"): Label4.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label8 = No Code [Change Float Type]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label8.Caption = rsLang("LanguageLayoutLnk_Description"): Label8.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkDisable = No Code [Float Disabled]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkDisable.Caption = rsLang("LanguageLayoutLnk_Description"): chkDisable.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label2 = No Code [Preset Details]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label2.Caption = rsLang("LanguageLayoutLnk_Description"): Label2.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//chkKey = No Code [Float set as a Fast Preset Tender on POS]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then chkKey.Caption = rsLang("LanguageLayoutLnk_Description"): chkKey.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label6 = No Code [Keyboard Name]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label6.Caption = rsLang("LanguageLayoutLnk_Description"): Label6.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//Label7 = No Code [Keyboard Key(s)]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then Label7.Caption = rsLang("LanguageLayoutLnk_Description"): Label7.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'";
//UPGRADE_ISSUE: Form property frmFloatRepre.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 loadItem(ref int id)
{
ADODB.Recordset rs = default(ADODB.Recordset);
ADODB.Recordset rt = default(ADODB.Recordset);
ADODB.Recordset rk = default(ADODB.Recordset);
g_floatSet = false;
rs = modRecordSet.getRS(ref "SELECT * FROM [Float] WHERE Float.Float_Unit = " + Convert.ToInt32(id) + ";");
if (rs.RecordCount) {
g_FloatU = Convert.ToInt32(id);
_txtFloat_0.Text = rs.Fields("Float_Name").Value;
//_txtFloat_1.Text = rs("Float_Pack")
_txtFloat_1.Text = Strings.FormatNumber(rs.Fields("Float_Pack").Value);
g_Defailt2 = Convert.ToDouble(Strings.FormatNumber(rs.Fields("Float_Pack").Value)) * 100;
//If rs("Float_Type") = True Then
// _txtFloat_2.Text = "Note"
if (rs.Fields("Float_Type").Value == true) {
_txtFloat_2.Text = "Note";
this.cbmChangeType.SelectedIndex = 1;
} else {
_txtFloat_2.Text = "Coin";
this.cbmChangeType.SelectedIndex = 0;
}
//Do presets....
rt = modRecordSet.getRS(ref "SELECT Float.*, tblPresetTender.* FROM tblPresetTender INNER JOIN [Float] ON tblPresetTender.tblValue = Float.Float_Unit WHERE Float.Float_Unit = " + Convert.ToInt32(id) + ";");
if (rt.RecordCount) {
rk = modRecordSet.getRS(ref "SELECT keyboard.keyboard_Name,keyboard.keyboard_Description, keyboard.keyboard_Show,keyboard.keyboardID FROM tblPresetTender INNER JOIN keyboard ON tblPresetTender.tblKey = keyboard.KeyboardID WHERE tblPresetTender.tblValue = " + Convert.ToInt32(id) + ";");
if (rk.RecordCount) {
g_Enough = false;
_txtKey_0.Text = rk.Fields("keyboard_Name").Value;
grsKey_ID = rk.Fields("keyboardID").Value;
rk = modRecordSet.getRS(ref "SELECT KeyboardKeyboardLayoutLnk.KeyboardKeyboardLayoutLnk_Description FROM KeyboardKeyboardLayoutLnk WHERE KeyboardKeyboardLayoutLnk_KeyboardID = " + rk.Fields("keyboardID").Value + ";");
//UPGRADE_WARNING: Use of Null/IsNull() detected. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="2EED02CB-5C0E-4DC1-AE94-4FAA3A30F51A"'
if (Information.IsDBNull(rk.Fields("KeyboardKeyboardLayoutLnk_Description").Value)) {
} else {
_txtKey_1.Text = rk.Fields("KeyboardKeyboardLayoutLnk_Description").Value;
}
if (rt.Fields("tblActivated").Value == true) {
g_FloatU_1 = true;
chkKey.CheckState = System.Windows.Forms.CheckState.Checked;
chkKey.Tag = 1;
} else {
g_FloatU_1 = false;
chkKey.CheckState = System.Windows.Forms.CheckState.Unchecked;
chkKey.Tag = 0;
}
} else {
g_Enough = true;
}
} else {
//Check if there is option for new Preset....
rt = modRecordSet.getRS(ref "SELECT * FROM tblPresetTender WHERE tblKey >= 5000 AND tblActivated = False");
if (rt.RecordCount) {
g_Enough = true;
g_FloatU_1 = false;
chkKey.CheckState = System.Windows.Forms.CheckState.Unchecked;
chkKey.Tag = 0;
_txtKey_0.Enabled = false;
_txtKey_1.Enabled = false;
} else {
g_Enough = true;
g_FloatU_1 = false;
chkKey.CheckState = System.Windows.Forms.CheckState.Unchecked;
chkKey.Tag = 0;
chkKey.Enabled = false;
_txtKey_0.Enabled = false;
_txtKey_1.Enabled = false;
}
}
g_Default = rs.Fields("Float_unit").Value;
_txtFloat_3.Text = Strings.FormatNumber(rs.Fields("Float_unit").Value / 100);
if (rs.Fields("Float_Disabled").Value == true) {
chkDisable.CheckState = System.Windows.Forms.CheckState.Checked;
chkDisable.Tag = 1;
} else {
chkDisable.CheckState = System.Windows.Forms.CheckState.Unchecked;
chkDisable.Tag = 0;
}
}
g_floatSet = true;
loadLanguage();
ShowDialog();
}
private void chkKey_CheckStateChanged(System.Object eventSender, System.EventArgs eventArgs)
{
string st1 = null;
string grsKeyID = null;
ADODB.Recordset rs = default(ADODB.Recordset);
// ERROR: Not supported in C#: OnErrorStatement
if (g_floatSet == true) {
if (g_Enough == false) {
return;
}
if (g_Enough == true) {
rs = modRecordSet.getRS(ref "SELECT * FROM tblPresetTender WHERE tblKey >= 5000 AND tblActivated = False");
if (rs.RecordCount) {
grsKeyID = rs.Fields("tblkey").Value;
_txtKey_0.Text = this._txtFloat_0.Text;
grsKey_ID = rs.Fields("tblKey").Value;
g_NewKy = true;
} else {
st1 = "You've already allocated enough presets on your POS.";
st1 = st1 + "To allocate a new one please disable anyone.";
Interaction.MsgBox(st1, MsgBoxStyle.ApplicationModal + MsgBoxStyle.Information + MsgBoxStyle.OkOnly, "New Preset");
return;
}
}
}
}
private void Command1_Click(System.Object eventSender, System.EventArgs eventArgs)
{
int dValue_1 = 0;
short stType = 0;
ADODB.Recordset rj = default(ADODB.Recordset);
// ERROR: Not supported in C#: OnErrorStatement
if (!string.IsNullOrEmpty(_txtKey_1.Text)) {
if (string.IsNullOrEmpty(_txtKey_0.Text)) {
Interaction.MsgBox("Keyboard Name is a required filed", MsgBoxStyle.ApplicationModal + MsgBoxStyle.Exclamation + MsgBoxStyle.OkOnly, "Preset Tender");
return;
} else {
if (g_Enough == true) {
} else {
modRecordSet.cnnDB.Execute("UPDATE Keyboard Set keyboard_Name = '" + Strings.Replace(_txtKey_0.Text, "'", "''") + "', keyboard_Description = '" + Strings.Replace(_txtKey_0.Text, "'", "''") + "' WHERE keyboardID = " + grsKey_ID + ";");
modRecordSet.cnnDB.Execute("UPDATE tblPresetTender SET tblDescription ='" + Strings.Replace(_txtKey_0.Text, "'", "''") + "',tblActivated = " + Conversion.Val(Convert.ToString(this.chkKey.CheckState)) + " WHERE tblKey = " + grsKey_ID + ";");
}
}
}
if (!string.IsNullOrEmpty(_txtFloat_0.Text)) {
dValue_1 = Convert.ToInt32(Convert.ToDouble(Strings.FormatNumber(_txtFloat_3.Text)) * 100);
if (!string.IsNullOrEmpty(this.cbmChangeType.Text)) {
if (this.cbmChangeType.Text == "Coin")
stType = 0;
else
stType = 1;
modRecordSet.cnnDB.Execute("UPDATE [Float] Set Float.Float_Type = " + stType + ", Float.Float_Name = '" + Strings.Replace(this._txtFloat_0.Text, "'", "''") + "', Float.Float_Disabled = " + Conversion.Val(Convert.ToString(this.chkDisable.CheckState)) + ", Float.Float_Pack = " + Convert.ToInt32(_txtFloat_1.Text) + " WHERE Float.Float_Unit = " + g_FloatU + ";");
} else {
modRecordSet.cnnDB.Execute("UPDATE [Float] Set Float.Float_Name = '" + Strings.Replace(this._txtFloat_0.Text, "'", "''") + "', Float.Float_Disabled = " + Conversion.Val(Convert.ToString(this.chkDisable.CheckState)) + ", Float.Float_Pack = " + Convert.ToInt32(_txtFloat_1.Text) + " WHERE Float.Float_Unit = " + g_FloatU + ";");
}
if (g_Default == dValue_1) {
} else if (dValue_1 == 0) {
} else {
rj = modRecordSet.getRS(ref "SELECT * FROM [Float] WHERE Float.Float_Unit = " + dValue_1 + ";");
if (rj.RecordCount) {
Interaction.MsgBox("Denomination with this Float Unit/Amount exist already, New Amount would not be updated", MsgBoxStyle.Information + MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly, "New Denomination");
} else {
modRecordSet.cnnDB.Execute("UPDATE [Float] Set Float.Float_Unit = " + dValue_1 + " WHERE Float.Float_Unit = " + g_FloatU + ";");
}
}
}
if (g_FloatU_1 == true) {
if (g_Enough == true) {
} else {
modRecordSet.cnnDB.Execute("UPDATE tblPresetTender SET tblActivated = " + Conversion.Val(Convert.ToString(this.chkKey.CheckState)) + " WHERE tblKey = " + grsKey_ID + ";");
}
}
if (g_NewKy == true) {
modRecordSet.cnnDB.Execute("UPDATE Keyboard Set keyboard_Name = '" + Strings.Replace(_txtKey_0.Text, "'", "''") + "', keyboard_Description = '" + Strings.Replace(_txtKey_0.Text, "'", "''") + "', keyboard_Show = 1 WHERE keyboardID = " + grsKey_ID + ";");
modRecordSet.cnnDB.Execute("UPDATE tblPresetTender SET tblDescription ='" + Strings.Replace(_txtKey_0.Text, "'", "''") + "',tblValue =" + g_FloatU + ", tblActivated = 1 WHERE tblKey = " + grsKey_ID + ";");
g_NewKy = false;
}
this.Close();
}
public void LostFocus1(ref Control lControl, ref int lDecimal)
{
if (string.IsNullOrEmpty(lControl.Text))
return;
if (lDecimal) {
lControl.Text = lControl.Text / 100;
}
//lControl.Text = FormatNumber(lControl.Text, lDecimal)
lControl.Text = Strings.FormatNumber(lControl.Text);
}
private void txtFloat_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int index = 0;
TextBox n = null;
n = (TextBox)eventSender;
index = GetIndex.GetIndexer(ref n, ref txtFloat);
if (index == 1 | index == 3) {
modUtilities.MyGotFocusNumeric(ref txtFloat[index]);
}
}
private void txtFloat_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
int index = 0;
TextBox n = null;
n = (TextBox)eventSender;
index = GetIndex.GetIndexer(ref n, ref txtFloat);
if (index == 1 | index == 3) {
modUtilities.MyKeyPress(ref KeyAscii);
}
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void txtFloat_Leave(System.Object eventSender, System.EventArgs eventArgs)
{
int index = 0;
TextBox n = null;
n = (TextBox)eventSender;
index = GetIndex.GetIndexer(ref n, ref txtFloat);
string g_Defailt = null;
if (index == 1) {
if (string.IsNullOrEmpty(_txtFloat_1.Text)) {
_txtFloat_1.Text = Convert.ToString(g_Defailt2);
}
if (!string.IsNullOrEmpty(_txtFloat_1.Text)) {
if (Convert.ToDouble(Strings.FormatNumber(_txtFloat_1.Text)) == 0) {
_txtFloat_1.Text = Convert.ToString(g_Defailt2);
} else if (Convert.ToInt32(Convert.ToDouble(Strings.FormatNumber(_txtFloat_1.Text)) / 100) == 0) {
_txtFloat_1.Text = Convert.ToString(g_Defailt2);
}
}
LostFocus1(ref _txtFloat_1, ref 2);
}
if (index == 3) {
if (string.IsNullOrEmpty(txtFloat[3].Text)) {
txtFloat[3].Text = Convert.ToString(g_Default);
}
if (!string.IsNullOrEmpty(txtFloat[3].Text)) {
if (Convert.ToDouble(Strings.FormatNumber(txtFloat[3].Text)) == 0) {
txtFloat[3].Text = Convert.ToString(g_Default);
} else if (Convert.ToInt32(Convert.ToDouble(Strings.FormatNumber(txtFloat[3].Text)) / 100) == 0) {
//UPGRADE_WARNING: Couldn't resolve default property of object g_Defailt. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="6A50421D-15FE-4896-8A1B-2EC21E9037B2"'
txtFloat[3].Text = g_Defailt;
}
}
LostFocus1(ref txtFloat[3], ref 2);
}
}
private void frmFloatRepre_Load(object sender, System.EventArgs e)
{
txtFloat.AddRange(new TextBox[] {
_txtFloat_0,
_txtFloat_1,
_txtFloat_2,
_txtFloat_3
});
TextBox tb = new TextBox();
foreach (TextBox tb_loopVariable in txtFloat) {
tb = tb_loopVariable;
tb.Enter += txtFloat_Enter;
tb.KeyPress += txtFloat_KeyPress;
tb.Leave += txtFloat_Leave;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All Rights Reserved. See License.txt in the project root for license information.
using FSLib = Microsoft.FSharp.Compiler.AbstractIL.Internal.Library;
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Threading;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.Build.Utilities;
using VSConstants = Microsoft.VisualStudio.VSConstants;
using Task = Microsoft.VisualStudio.Shell.Task;
namespace Microsoft.VisualStudio.FSharp.ProjectSystem
{
[CLSCompliant(false), ComVisible(true)]
public class ProjectReferenceNode : ReferenceNode
{
/// <summary>
/// Containes either null if project reference is OK or instance of Task with error message if project reference is invalid
/// i.e. project A references project B when target framework version for B is higher that for A
/// </summary>
private Shell.Task projectRefError;
/// <summary>
/// The name of the assembly this refernce represents
/// </summary>
private Guid referencedProjectGuid;
private string referencedProjectName = String.Empty;
private string referencedProjectRelativePath = String.Empty;
private string referencedProjectFullPath = String.Empty;
private BuildDependency buildDependency = null;
/// <summary>
/// This is a reference to the automation object for the referenced project.
/// </summary>
private EnvDTE.Project referencedProject;
private bool referencedProjectIsCached = false;
/// <summary>
/// This state is controlled by the solution events.
/// The state is set to false by OnBeforeUnloadProject.
/// The state is set to true by OnBeforeCloseProject event.
/// </summary>
private bool canRemoveReference = true;
/// <summary>
/// Possibility for solution listener to update the state on the dangling reference.
/// It will be set in OnBeforeUnloadProject then the nopde is invalidated then it is reset to false.
/// </summary>
private bool isNodeValid = false;
private bool enableCaching;
private string cachedReferencedProjectOutputPath;
internal bool EnableCaching
{
get { return enableCaching; }
set
{
if (enableCaching != value)
{
cachedReferencedProjectOutputPath = null;
}
enableCaching = value;
}
}
public override string Url
{
get
{
return this.referencedProjectFullPath;
}
}
public override string SimpleName
{
get
{
return Path.GetFileNameWithoutExtension(this.ReferencedProjectOutputPath);
}
}
public override string Caption
{
get
{
return this.referencedProjectName;
}
}
public Guid ReferencedProjectGuid
{
get
{
return this.referencedProjectGuid;
}
}
/// <summary>
/// Possiblity to shortcut and set the dangling project reference icon.
/// It is ussually manipulated by solution listsneres who handle reference updates.
/// </summary>
public bool IsNodeValid
{
get
{
return this.isNodeValid;
}
set
{
this.isNodeValid = value;
}
}
/// <summary>
/// Controls the state whether this reference can be removed or not. Think of the project unload scenario where the project reference should not be deleted.
/// </summary>
public bool CanRemoveReference
{
get
{
return this.canRemoveReference;
}
set
{
this.canRemoveReference = value;
}
}
public string ReferencedProjectName
{
get { return this.referencedProjectName; }
}
private void InitReferencedProject(IVsSolution solution)
{
IVsHierarchy hier;
var hr = solution.GetProjectOfGuid(ref referencedProjectGuid, out hier);
if (!ErrorHandler.Succeeded(hr))
return; // check if project is missing or non-loaded!
object obj;
hr = hier.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out obj);
if (!ErrorHandler.Succeeded(hr))
return;
EnvDTE.Project prj = obj as EnvDTE.Project;
if (prj == null)
return;
// Skip if has no properties (e.g. "miscellaneous files")
if (prj.Properties == null)
{
return;
}
// Get the full path of the current project.
EnvDTE.Property pathProperty = null;
try
{
pathProperty = prj.Properties.Item("FullPath");
if (null == pathProperty)
{
// The full path should alway be availabe, but if this is not the
// case then we have to skip it.
return;
}
}
catch (ArgumentException)
{
return;
}
string prjPath = pathProperty.Value.ToString();
EnvDTE.Property fileNameProperty = null;
// Get the name of the project file.
try
{
fileNameProperty = prj.Properties.Item("FileName");
if (null == fileNameProperty)
{
// Again, this should never be the case, but we handle it anyway.
return;
}
}
catch (ArgumentException)
{
return;
}
prjPath = System.IO.Path.Combine(prjPath, fileNameProperty.Value.ToString());
// If the full path of this project is the same as the one of this
// reference, then we have found the right project.
if (NativeMethods.IsSamePath(prjPath, referencedProjectFullPath))
{
this.referencedProject = prj;
}
}
/// <summary>
/// Gets the automation object for the referenced project.
/// </summary>
private EnvDTE.Project ReferencedProject
{
get
{
if (!this.referencedProjectIsCached)
{
// Search for the project in the collection of the projects in the
// current solution.
var solution = (IVsSolution)this.ProjectMgr.GetService(typeof(IVsSolution));
if (null == solution)
{
return null;
}
InitReferencedProject(solution);
this.referencedProjectIsCached = true;
}
return this.referencedProject;
}
}
public void DropReferencedProjectCache()
{
referencedProjectIsCached = false;
}
/// <summary>
/// Resets error (if any) associated with current project reference
/// </summary>
public void CleanProjectReferenceErrorState()
{
UIThread.DoOnUIThread(() =>
{
if (projectRefError != null)
{
ProjectMgr.ProjectErrorsTaskListProvider.Tasks.Remove(projectRefError);
projectRefError = null;
}
}
);
}
/// <summary>
/// Creates new error with given text and associates it with current project reference.
/// Old error is removed
/// </summary>
/// <param name="text"></param>
private void SetError(string text)
{
UIThread.DoOnUIThread(() =>
{
// delete existing error if exists
CleanProjectReferenceErrorState();
projectRefError = new Shell.ErrorTask
{
ErrorCategory = Shell.TaskErrorCategory.Warning,
HierarchyItem = ProjectMgr.InteropSafeIVsHierarchy,
Text = text
};
ProjectMgr.ProjectErrorsTaskListProvider.Tasks.Add(projectRefError);
}
);
}
/// <summary>
/// Helper method: creates and set message with ID SR.ProjectReferencesHigherVersionWarning
/// </summary>
private void SetProjectReferencesHigherVersionWarningMessage()
{
var myFrameworkName = GetProjectTargetFrameworkName(ProjectMgr);
var otherFrameworkName = GetProjectTargetFrameworkName(ProjectMgr.Site, referencedProjectGuid);
var msg = string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ProjectReferencesHigherVersionWarning, CultureInfo.CurrentUICulture), referencedProjectName, otherFrameworkName.Version, myFrameworkName.Version);
SetError(msg);
}
/// <summary>
/// Actualizes error associated with this project reference
/// </summary>
public void RefreshProjectReferenceErrorState()
{
UIThread.DoOnUIThread(() =>
{
CleanProjectReferenceErrorState();
switch(CheckFrameworksCompatibility(ProjectMgr, referencedProjectGuid))
{
case FrameworkCompatibility.Ok:
/* This is OK - do nothing */
break;
case FrameworkCompatibility.HigherVersion:
SetProjectReferencesHigherVersionWarningMessage();
break;
case FrameworkCompatibility.DifferentFamily:
{
var myFramework = GetProjectTargetFrameworkName(ProjectMgr);
var otherFramework = GetProjectTargetFrameworkName(ProjectMgr.Site, referencedProjectGuid);
var msg = GetDifferentFamilyErrorMessage(myFramework, referencedProjectName, otherFramework);
SetError(msg);
}
break;
}
}
);
}
public override bool CanBeReferencedFromFSI()
{
return true;
}
public override string GetReferenceForFSI()
{
var path = ReferencedProjectOutputPath; ;
return path != null && File.Exists(path) ? path : null;
}
/// <summary>
/// Gets the full path to the assembly generated by this project.
/// </summary>
public string ReferencedProjectOutputPath
{
get
{
if (EnableCaching)
{
return cachedReferencedProjectOutputPath ?? (cachedReferencedProjectOutputPath = GetReferencedProjectOutputPath());
}
return GetReferencedProjectOutputPath();
}
}
private string GetReferencedProjectOutputPath()
{
// Make sure that the referenced project implements the automation object.
if (null == this.ReferencedProject)
{
return null;
}
// Get the configuration manager from the project.
EnvDTE.ConfigurationManager confManager = this.ReferencedProject.ConfigurationManager;
if (null == confManager)
{
return null;
}
// Get the active configuration.
EnvDTE.Configuration config = null;
try
{
config = confManager.ActiveConfiguration;
}
catch (ArgumentException)
{
// 4951: exeception happens sometimes when ToolBox queries references on worker thread
// (apparently hitting a race or bad state of referenced project's ConfigurationManager)
return null;
}
if (null == config)
{
return null;
}
// Get the output path for the current configuration.
string outputPath = null;
try
{
EnvDTE.Property outputPathProperty = config.Properties.Item("OutputPath");
if (null == outputPathProperty)
{
return null;
}
outputPath = outputPathProperty.Value.ToString();
}
catch (System.Runtime.InteropServices.COMException)
{
// just catch the exception and return null, which means the user will see an empty 'FullPath' field of a ProjectReference property.
return null;
}
// Ususally the output path is relative to the project path, but it is possible
// to set it as an absolute path. If it is not absolute, then evaluate its value
// based on the project directory.
if (!System.IO.Path.IsPathRooted(outputPath))
{
string projectDir = System.IO.Path.GetDirectoryName(referencedProjectFullPath);
outputPath = System.IO.Path.Combine(projectDir, outputPath);
}
// Now get the name of the assembly from the project.
// Some project system throw if the property does not exist. We expect an ArgumentException.
string assemblyName = null;
try
{
assemblyName = this.ReferencedProject.Properties.Item("OutputFileName").Value.ToString();
}
catch (ArgumentException)
{
}
catch (NullReferenceException)
{
}
if (null == assemblyName)
{
try
{
var group = config.OutputGroups.Item("Built");
var files = (object[])group.FileNames;
if (files.Length > 0)
{
assemblyName = (string)files[0];
}
}
catch (InvalidCastException)
{
return null;
}
catch (ArgumentException)
{
return null;
}
catch (NullReferenceException)
{
return null;
}
}
// build the full path adding the name of the assembly to the output path.
outputPath = System.IO.Path.Combine(outputPath, assemblyName);
return outputPath;
}
private Automation.OAProjectReference projectReference;
public override object Object
{
get
{
if (null == projectReference)
{
projectReference = new Automation.OAProjectReference(this);
}
return projectReference;
}
}
/// <summary>
/// Constructor for the ReferenceNode. It is called when the project is reloaded, when the project element representing the refernce exists.
/// </summary>
internal ProjectReferenceNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
this.referencedProjectRelativePath = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectRelativePath), "Could not retrive referenced project path form project file");
string guidString = this.ItemNode.GetMetadata(ProjectFileConstants.Project);
// Continue even if project setttings cannot be read.
try
{
this.referencedProjectGuid = new Guid(guidString);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
this.ProjectMgr.AddBuildDependency(this.buildDependency);
}
finally
{
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "Could not retrive referenced project guidproject file");
this.referencedProjectName = this.ItemNode.GetMetadata(ProjectFileConstants.Name);
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "Could not retrive referenced project name form project file");
}
Uri uri = new Uri(this.ProjectMgr.BaseURI.Uri, this.referencedProjectRelativePath);
if (uri != null)
{
this.referencedProjectFullPath = Microsoft.VisualStudio.Shell.Url.Unescape(uri.LocalPath, true);
}
}
internal ProjectReferenceNode(ProjectNode root, string referencedProjectName, string projectPath, string projectReference)
: base(root)
{
Debug.Assert(root != null && !String.IsNullOrEmpty(referencedProjectName) && !String.IsNullOrEmpty(projectReference)
&& !String.IsNullOrEmpty(projectPath), "Can not add a reference because the input for adding one is invalid.");
this.referencedProjectName = referencedProjectName;
int indexOfSeparator = projectReference.IndexOf('|');
string fileName = String.Empty;
// Unfortunately we cannot use the path part of the projectReference string since it is not resolving correctly relative pathes.
if (indexOfSeparator != -1)
{
string projectGuid = projectReference.Substring(0, indexOfSeparator);
this.referencedProjectGuid = new Guid(projectGuid);
if (indexOfSeparator + 1 < projectReference.Length)
{
string remaining = projectReference.Substring(indexOfSeparator + 1);
indexOfSeparator = remaining.IndexOf('|');
if (indexOfSeparator == -1)
{
fileName = remaining;
}
else
{
fileName = remaining.Substring(0, indexOfSeparator);
}
}
}
Debug.Assert(!String.IsNullOrEmpty(fileName), "Can not add a project reference because the input for adding one is invalid.");
if (!System.IO.Path.IsPathRooted(projectPath))
{
IVsSolution sln = this.ProjectMgr.Site.GetService(typeof(SVsSolution)) as IVsSolution;
string slnDir, slnFile, slnOptsFile;
sln.GetSolutionInfo(out slnDir, out slnFile, out slnOptsFile);
projectPath = Path.Combine(slnDir, projectPath);
}
Uri uri = new Uri(projectPath);
string referenceDir = Path.GetDirectoryName(PackageUtilities.GetPathDistance(this.ProjectMgr.BaseURI.Uri, uri));
Debug.Assert(!String.IsNullOrEmpty(referenceDir), "Can not add a project reference because the input for adding one is invalid.");
string justTheFileName = Path.GetFileName(fileName);
this.referencedProjectRelativePath = Path.Combine(referenceDir, justTheFileName);
this.referencedProjectFullPath = Path.Combine(Path.GetDirectoryName(projectPath), justTheFileName);
this.buildDependency = new BuildDependency(this.ProjectMgr, this.referencedProjectGuid);
}
public override NodeProperties CreatePropertiesObject()
{
return new ProjectReferencesProperties(this);
}
/// <summary>
/// The node is added to the hierarchy and then updates the build dependency list.
/// </summary>
public override bool AddReference()
{
if (this.ProjectMgr == null)
{
return false;
}
IVsSolution vsSolution = this.ProjectMgr.GetService(typeof(SVsSolution)) as IVsSolution;
IVsHierarchy projHier = null;
var hr = vsSolution.GetProjectOfGuid(ref this.referencedProjectGuid, out projHier);
Debug.Assert(hr == VSConstants.S_OK, "GetProjectOfGuid was not able to locate a project from a project reference");
if (projHier != null)
{
var keyOutput = string.Empty;
try
{
keyOutput = this.ProjectMgr.GetKeyOutputForGroup(projHier, ProjectSystemConstants.VS_OUTPUTGROUP_CNAME_Built);
}
catch (Exception e)
{
Debug.Fail("Error getting key output", e.ToString());
}
bool valid = false;
try
{
var ext = Path.GetExtension(keyOutput);
valid = String.Equals(".dll", ext, StringComparison.OrdinalIgnoreCase) || String.Equals(".exe", ext, StringComparison.OrdinalIgnoreCase);
}
catch(ArgumentException)
{
// bad paths are invalid
}
if (!valid)
{
IVsUIShell shell = this.ProjectMgr.Site.GetService(typeof(SVsUIShell)) as IVsUIShell;
Guid dummy = Guid.NewGuid();
int result;
string text = string.Format(SR.GetString(SR.ProjectRefOnlyExeOrDll), this.Caption);
if (!Utilities.IsInAutomationFunction(this.ProjectMgr.Site))
{
shell.ShowMessageBox(0, ref dummy, null, text, null, 0, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_CRITICAL, 1, out result);
}
return false;
}
}
bool success = base.AddReference();
if (success)
{
this.ProjectMgr.AddBuildDependency(this.buildDependency);
}
return success;
}
/// <summary>
/// Overridden method. The method updates the build dependency list before removing the node from the hierarchy.
/// </summary>
public override void Remove(bool removeFromStorage, bool promptSave = true)
{
if (this.ProjectMgr == null || !this.canRemoveReference)
{
return;
}
this.ProjectMgr.RemoveBuildDependency(this.buildDependency);
base.Remove(removeFromStorage, promptSave);
// current reference is removed - delete associated error from list
CleanProjectReferenceErrorState();
}
/// <summary>
/// Links a reference node to the project file.
/// </summary>
public override void BindReferenceData()
{
Debug.Assert(!String.IsNullOrEmpty(this.referencedProjectName), "The referencedProjectName field has not been initialized");
Debug.Assert(this.referencedProjectGuid != Guid.Empty, "The referencedProjectName field has not been initialized");
this.ItemNode = new ProjectElement(this.ProjectMgr, this.referencedProjectRelativePath, ProjectFileConstants.ProjectReference);
this.ItemNode.SetMetadata(ProjectFileConstants.Name, this.referencedProjectName);
this.ItemNode.SetMetadata(ProjectFileConstants.Project, this.referencedProjectGuid.ToString("B"));
this.ItemNode.SetMetadata(ProjectFileConstants.Private, true.ToString());
if (CheckFrameworksCompatibility(ProjectMgr, referencedProjectGuid) == FrameworkCompatibility.HigherVersion)
{
// we are referencing assembly that targets higher framework version than we are - set error
SetProjectReferencesHigherVersionWarningMessage();
}
}
/// <summary>
/// Defines whether this node is valid node for painting the refererence icon.
/// </summary>
/// <returns></returns>
public override bool CanShowDefaultIcon()
{
if (this.referencedProjectGuid == Guid.Empty || this.ProjectMgr == null || this.ProjectMgr.IsClosed || this.isNodeValid)
{
return false;
}
// For multitargeting, we need to find the target framework moniker for the
// reference we are adding, and display a warning icon if the reference targets a higher
// framework then what we have.
IVsSolution vsSolution = this.ProjectMgr.GetService(typeof(SVsSolution)) as IVsSolution;
IVsHierarchy projHier = null;
var hr = vsSolution.GetProjectOfGuid(this.ReferencedProjectGuid, out projHier);
//Debug.Assert(hr == VSConstants.S_OK, "GetProjectOfGuid was not able to locate a project from a project reference");
if (hr == VSConstants.S_OK)
{
object otargetFrameworkMoniker = null;
hr = projHier.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out otargetFrameworkMoniker);
if (!ErrorHandler.Succeeded(hr))
{
// Safety check
return false;
}
if (hr == VSConstants.S_OK)
{
var thisFrameworkName = new System.Runtime.Versioning.FrameworkName(GetTargetFrameworkMoniker());
var frameworkName = new System.Runtime.Versioning.FrameworkName((string)otargetFrameworkMoniker);
if (thisFrameworkName.Version < frameworkName.Version)
{
return false;
}
}
}
IVsHierarchy hierarchy = null;
hierarchy = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, this.referencedProjectGuid);
if (hierarchy == null)
{
return false;
}
//If the Project is unloaded return false
if (this.ReferencedProject == null)
{
return false;
}
return (!String.IsNullOrEmpty(this.referencedProjectFullPath) && FSLib.Shim.FileSystem.SafeExists(this.referencedProjectFullPath));
}
/// <summary>
/// Checks if a project reference can be added to the hierarchy. It calls base to see if the reference is not already there, then checks for circular references.
/// </summary>
/// <returns></returns>
internal override AddReferenceCheckResult CheckIfCanAddReference()
{
// When this method is called this refererence has not yet been added to the hierarchy, only instantiated.
var checkResult = base.CheckIfCanAddReference();
if (!checkResult.Ok)
return checkResult;
if (this.IsThisProjectReferenceInCycle())
{
return AddReferenceCheckResult.Failed(
String.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ProjectContainsCircularReferences, CultureInfo.CurrentUICulture), this.referencedProjectName)
);
}
switch (CheckFrameworksCompatibility(ProjectMgr, referencedProjectGuid))
{
case FrameworkCompatibility.Ok:
return AddReferenceCheckResult.Success;
case FrameworkCompatibility.HigherVersion:
// if project tries to target another project with higher framework version - allow to do this - we'll set up error later in BindReferenceData
return AddReferenceCheckResult.Success;
case FrameworkCompatibility.DifferentFamily:
var myFrameworkName = GetProjectTargetFrameworkName(ProjectMgr);
var otherFrameworkName = GetProjectTargetFrameworkName(ProjectMgr.Site, referencedProjectGuid);
var errorMessage = GetDifferentFamilyErrorMessage(myFrameworkName, referencedProjectName, otherFrameworkName);
return AddReferenceCheckResult.Failed(errorMessage);
default:
System.Diagnostics.Debug.Assert(false);
throw new InvalidOperationException("impossible");
}
}
private bool IsThisProjectReferenceInCycle()
{
return IsReferenceInCycle(this.referencedProjectGuid);
}
private bool IsReferenceInCycle(Guid projectGuid)
{
// use same logic as C#:
// vsproject\langbuild\langref.cpp
// BOOL CLanguageReferences::IsCircularReference(CLangReference *pclref, BOOL fCalculateDependencies)
int isCircular = 0;
IVsHierarchy otherHier = VsShellUtilities.GetHierarchy(this.ProjectMgr.Site, projectGuid);
IVsSolutionBuildManager2 vsSBM = this.ProjectMgr.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager2;
vsSBM.CalculateProjectDependencies();
vsSBM.QueryProjectDependency(otherHier, this.ProjectMgr.InteropSafeIVsHierarchy, out isCircular);
return isCircular != 0;
}
public override Guid GetBrowseLibraryGuid()
{
if (this.Url.EndsWith(".csproj"))
{
return VSProjectConstants.guidCSharpBrowseLibrary;
}
else if (this.Url.EndsWith(".vbproj"))
{
return VSProjectConstants.guidVBBrowseLibrary;
}
else
{
// TODO: Need to determine a generic way of finding browse library guids other than hardcoding
// those for .csproj and .vbproj
CCITracing.AddTraceLog("Unknown project type");
return Guid.Empty;
}
}
/// <summary>
/// Checks the compatibility of target frameworks for given projects
/// </summary>
private static FrameworkCompatibility CheckFrameworksCompatibility(ProjectNode thisProject, Guid referencedProjectGuid)
{
// copying logic from C#'s project system, langref.cpp: IsProjectReferenceReferenceable()
var otherFrameworkName = GetProjectTargetFrameworkName(thisProject.Site, referencedProjectGuid);
if (otherFrameworkName == null)
return FrameworkCompatibility.Ok;
if (String.Compare(otherFrameworkName.Identifier, ".NETPortable", StringComparison.OrdinalIgnoreCase) == 0)
{
// we always allow references to projects that are targeted to the Portable/".NETPortable" fx family
return FrameworkCompatibility.Ok;
}
if (String.Compare(otherFrameworkName.Identifier, ".NETStandard", StringComparison.OrdinalIgnoreCase) == 0)
{
// we always allow references to projects that are targeted to the ".NETStandard" family
return FrameworkCompatibility.Ok;
}
var myFrameworkName = GetProjectTargetFrameworkName(thisProject);
if (String.Compare(otherFrameworkName.Identifier, myFrameworkName.Identifier, StringComparison.OrdinalIgnoreCase) == 0)
{
// same family, compare version
if (myFrameworkName.Version.CompareTo(otherFrameworkName.Version) >= 0)
{
return FrameworkCompatibility.Ok;
}
else
{
// trying to reference a higher version
return FrameworkCompatibility.HigherVersion;
}
}
else
{
// different family, e.g. immersive v .NET v Silverlight
return FrameworkCompatibility.DifferentFamily;
}
}
/// <summary>
/// Returns target framework for the given project Guid
/// </summary>
private static System.Runtime.Versioning.FrameworkName GetProjectTargetFrameworkName(System.IServiceProvider serviceProvider, Guid referencedProjectGuid)
{
var hierarchy = VsShellUtilities.GetHierarchy(serviceProvider, referencedProjectGuid);
if (hierarchy == null)
return null;
object otherTargetFrameworkMonikerObj;
int hr = hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out otherTargetFrameworkMonikerObj);
if (!ErrorHandler.Succeeded(hr))
return null;
string targetFrameworkMoniker = (string)otherTargetFrameworkMonikerObj;
return new System.Runtime.Versioning.FrameworkName(targetFrameworkMoniker);
}
/// <summary>
/// Returns target framework for the given project node
/// </summary>
/// <param name="projectNode"></param>
/// <returns></returns>
private static System.Runtime.Versioning.FrameworkName GetProjectTargetFrameworkName(ProjectNode projectNode)
{
string targetFrameworkMoniker = projectNode.GetTargetFrameworkMoniker();
return new System.Runtime.Versioning.FrameworkName(targetFrameworkMoniker);
}
private static string GetDifferentFamilyErrorMessage(System.Runtime.Versioning.FrameworkName currentFrameworkName, string referencedProjectName, System.Runtime.Versioning.FrameworkName otherFrameworkName)
{
return string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ProjectReferencesDifferentFramework, CultureInfo.CurrentUICulture), referencedProjectName, currentFrameworkName.Identifier, otherFrameworkName.Identifier);
}
enum FrameworkCompatibility
{
Ok,
DifferentFamily,
HigherVersion
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using IndexReader = Lucene.Net.Index.IndexReader;
using PriorityQueue = Lucene.Net.Util.PriorityQueue;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
using Query = Lucene.Net.Search.Query;
namespace Lucene.Net.Search.Spans
{
/// <summary>Matches the union of its clauses.</summary>
[Serializable]
public class SpanOrQuery:SpanQuery, System.ICloneable
{
private class AnonymousClassSpans : Spans
{
public AnonymousClassSpans(Lucene.Net.Index.IndexReader reader, SpanOrQuery enclosingInstance)
{
InitBlock(reader, enclosingInstance);
}
private void InitBlock(Lucene.Net.Index.IndexReader reader, SpanOrQuery enclosingInstance)
{
this.reader = reader;
this.enclosingInstance = enclosingInstance;
}
private Lucene.Net.Index.IndexReader reader;
private SpanOrQuery enclosingInstance;
public SpanOrQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
private SpanQueue queue = null;
private bool InitSpanQueue(int target)
{
queue = new SpanQueue(enclosingInstance, Enclosing_Instance.clauses.Count);
System.Collections.IEnumerator i = Enclosing_Instance.clauses.GetEnumerator();
while (i.MoveNext())
{
Spans spans = ((SpanQuery) i.Current).GetSpans(reader);
if (((target == - 1) && spans.Next()) || ((target != - 1) && spans.SkipTo(target)))
{
queue.Put(spans);
}
}
return queue.Size() != 0;
}
public override bool Next()
{
if (queue == null)
{
return InitSpanQueue(- 1);
}
if (queue.Size() == 0)
{
// all done
return false;
}
if (Top().Next())
{
// move to next
queue.AdjustTop();
return true;
}
queue.Pop(); // exhausted a clause
return queue.Size() != 0;
}
private Spans Top()
{
return (Spans) queue.Top();
}
public override bool SkipTo(int target)
{
if (queue == null)
{
return InitSpanQueue(target);
}
bool skipCalled = false;
while (queue.Size() != 0 && Top().Doc() < target)
{
if (Top().SkipTo(target))
{
queue.AdjustTop();
}
else
{
queue.Pop();
}
skipCalled = true;
}
if (skipCalled)
{
return queue.Size() != 0;
}
return Next();
}
public override int Doc()
{
return Top().Doc();
}
public override int Start()
{
return Top().Start();
}
public override int End()
{
return Top().End();
}
// TODO: Remove warning after API has been finalized
public override System.Collections.Generic.ICollection<byte[]> GetPayload()
{
System.Collections.Generic.ICollection<byte[]> result = null;
Spans theTop = Top();
if (theTop != null && theTop.IsPayloadAvailable())
{
result = theTop.GetPayload();
}
return result;
}
// TODO: Remove warning after API has been finalized
public override bool IsPayloadAvailable()
{
Spans top = Top();
return top != null && top.IsPayloadAvailable();
}
public override System.String ToString()
{
return "spans(" + Enclosing_Instance + ")@" + ((queue == null)?"START":(queue.Size() > 0?(Doc() + ":" + Start() + "-" + End()):"END"));
}
}
private SupportClass.EquatableList<SpanQuery> clauses;
private System.String field;
/// <summary>Construct a SpanOrQuery merging the provided clauses. </summary>
public SpanOrQuery(SpanQuery[] clauses)
{
// copy clauses array into an ArrayList
this.clauses = new SupportClass.EquatableList<SpanQuery>(clauses.Length);
for (int i = 0; i < clauses.Length; i++)
{
SpanQuery clause = clauses[i];
if (i == 0)
{
// check field
field = clause.GetField();
}
else if (!clause.GetField().Equals(field))
{
throw new System.ArgumentException("Clauses must have same field.");
}
this.clauses.Add(clause);
}
}
/// <summary>Return the clauses whose spans are matched. </summary>
public virtual SpanQuery[] GetClauses()
{
return (SpanQuery[]) clauses.ToArray();
}
public override System.String GetField()
{
return field;
}
/// <summary>Returns a collection of all terms matched by this query.</summary>
/// <deprecated> use extractTerms instead
/// </deprecated>
/// <seealso cref="ExtractTerms(Set)">
/// </seealso>
[Obsolete("use ExtractTerms instead")]
public override System.Collections.ICollection GetTerms()
{
System.Collections.ArrayList terms = new System.Collections.ArrayList();
System.Collections.IEnumerator i = clauses.GetEnumerator();
while (i.MoveNext())
{
SpanQuery clause = (SpanQuery) i.Current;
terms.AddRange(clause.GetTerms());
}
return terms;
}
public override void ExtractTerms(System.Collections.Hashtable terms)
{
System.Collections.IEnumerator i = clauses.GetEnumerator();
while (i.MoveNext())
{
SpanQuery clause = (SpanQuery) i.Current;
clause.ExtractTerms(terms);
}
}
public override System.Object Clone()
{
int sz = clauses.Count;
SpanQuery[] newClauses = new SpanQuery[sz];
for (int i = 0; i < sz; i++)
{
SpanQuery clause = (SpanQuery) clauses[i];
newClauses[i] = (SpanQuery) clause.Clone();
}
SpanOrQuery soq = new SpanOrQuery(newClauses);
soq.SetBoost(GetBoost());
return soq;
}
public override Query Rewrite(IndexReader reader)
{
SpanOrQuery clone = null;
for (int i = 0; i < clauses.Count; i++)
{
SpanQuery c = (SpanQuery) clauses[i];
SpanQuery query = (SpanQuery) c.Rewrite(reader);
if (query != c)
{
// clause rewrote: must clone
if (clone == null)
clone = (SpanOrQuery) this.Clone();
clone.clauses[i] = query;
}
}
if (clone != null)
{
return clone; // some clauses rewrote
}
else
{
return this; // no clauses rewrote
}
}
public override System.String ToString(System.String field)
{
System.Text.StringBuilder buffer = new System.Text.StringBuilder();
buffer.Append("spanOr([");
System.Collections.IEnumerator i = clauses.GetEnumerator();
int j = 0;
while (i.MoveNext())
{
j++;
SpanQuery clause = (SpanQuery) i.Current;
buffer.Append(clause.ToString(field));
if (j < clauses.Count)
{
buffer.Append(", ");
}
}
buffer.Append("])");
buffer.Append(ToStringUtils.Boost(GetBoost()));
return buffer.ToString();
}
public override bool Equals(System.Object o)
{
if (this == o)
return true;
if (o == null || GetType() != o.GetType())
return false;
SpanOrQuery that = (SpanOrQuery) o;
if (!clauses.Equals(that.clauses))
return false;
if (!(clauses.Count == 0) && !field.Equals(that.field))
return false;
return GetBoost() == that.GetBoost();
}
public override int GetHashCode()
{
int h = clauses.GetHashCode();
h ^= ((h << 10) | (SupportClass.Number.URShift(h, 23)));
h ^= System.Convert.ToInt32(GetBoost());
return h;
}
private class SpanQueue:PriorityQueue
{
private void InitBlock(SpanOrQuery enclosingInstance)
{
this.enclosingInstance = enclosingInstance;
}
private SpanOrQuery enclosingInstance;
public SpanOrQuery Enclosing_Instance
{
get
{
return enclosingInstance;
}
}
public SpanQueue(SpanOrQuery enclosingInstance, int size)
{
InitBlock(enclosingInstance);
Initialize(size);
}
public override bool LessThan(System.Object o1, System.Object o2)
{
Spans spans1 = (Spans) o1;
Spans spans2 = (Spans) o2;
if (spans1.Doc() == spans2.Doc())
{
if (spans1.Start() == spans2.Start())
{
return spans1.End() < spans2.End();
}
else
{
return spans1.Start() < spans2.Start();
}
}
else
{
return spans1.Doc() < spans2.Doc();
}
}
}
public override Spans GetSpans(IndexReader reader)
{
if (clauses.Count == 1)
// optimize 1-clause case
return ((SpanQuery) clauses[0]).GetSpans(reader);
return new AnonymousClassSpans(reader, this);
}
}
}
| |
using Shouldly;
using System;
using Xunit;
namespace StructureMap.Testing.Pipeline
{
public class Address
{
}
public class AddressDTO
{
}
public class Continuation
{
}
public class AddressFlattener : IFlattener<Address>
{
public object ToDto(object input)
{
var dto = createDTO((Address)input);
return dto;
}
private object createDTO(Address input)
{
// creates the AddressDTO object from the
// Address object passed in
throw new NotImplementedException();
}
}
public interface IFlattener
{
object ToDto(object input);
}
public interface IFlattener<T> : IFlattener
{
}
public class PassthroughFlattener<T> : IFlattener<T>
{
public object ToDto(object input)
{
return input;
}
}
public class when_accessing_a_type_registered_as_an_open_generics_type
{
public when_accessing_a_type_registered_as_an_open_generics_type()
{
container = new Container(x =>
{
// Define the basic open type for IFlattener<>
x.For(typeof(IFlattener<>)).Use(typeof(PassthroughFlattener<>));
// Explicitly Register a specific closed type for Address
x.For<IFlattener<Address>>().Use<AddressFlattener>();
});
}
private Container container;
[Fact]
public void asking_for_a_closed_type_that_is_explicitly_registered_returns_the_explicitly_defined_type()
{
container.GetInstance<IFlattener<Address>>()
.ShouldBeOfType<AddressFlattener>();
}
[Fact]
public void asking_for_a_closed_type_that_is_not_explicitly_registered_will_close_the_open_type_template()
{
container.GetInstance<IFlattener<Continuation>>()
.ShouldBeOfType<PassthroughFlattener<Continuation>>();
}
[Fact]
public void throws_exception_if_passed_a_type_that_is_not_an_open_generic_type()
{
var ex = Exception<StructureMapConfigurationException>.ShouldBeThrownBy(() =>
{
container.ForGenericType(typeof(string)).WithParameters().GetInstanceAs<IFlattener>();
});
ex.Title.ShouldBe("Type 'System.String' is not an open generic type");
}
[Fact]
public void using_the_generics_helper_expression()
{
var flattener1 = container.ForGenericType(typeof(IFlattener<>))
.WithParameters(typeof(Address)).GetInstanceAs<IFlattener>();
flattener1.ShouldBeOfType<AddressFlattener>();
var flattener2 = container.ForGenericType(typeof(IFlattener<>))
.WithParameters(typeof(Continuation)).GetInstanceAs<IFlattener>();
flattener2.ShouldBeOfType<PassthroughFlattener<Continuation>>();
}
}
public class ObjectFlattener
{
private readonly IContainer _container;
// You can inject the IContainer itself into an object by the way...
public ObjectFlattener(IContainer container)
{
_container = container;
}
// This method can "flatten" any object
public object Flatten(object input)
{
var flattener = _container.ForGenericType(typeof(IFlattener<>))
.WithParameters(input.GetType())
.GetInstanceAs<IFlattener>();
return flattener.ToDto(input);
}
}
public class FindAddressController
{
public Address FindAddress(long id)
{
return null;
}
public Continuation WhatShouldTheUserDoNext()
{
return null;
}
}
public class when_getting_a_closed_type_from_an_open_generic_type_by_providing_an_input_parameter
{
[Fact]
public void fetch_the_object()
{
var container =
new Container(
x => { x.For<IHandler<Shipment>>().Use<ShipmentHandler>(); });
var shipment = new Shipment();
var handler = container
.ForObject(shipment)
.GetClosedTypeOf(typeof(IHandler<>))
.As<IHandler>();
handler.ShouldBeOfType<ShipmentHandler>().Shipment.ShouldBeTheSameAs(shipment);
}
}
public class when_getting_a_closed_type_from_an_open_generic_type_by_providing_an_input_parameter_from_ObjectFactory
{
[Fact]
public void fetch_the_object()
{
var container = new Container(
x => x.For<IHandler<Shipment>>().Use<ShipmentHandler>());
var shipment = new Shipment();
var handler =
container.ForObject(shipment).GetClosedTypeOf(typeof(IHandler<>)).As<IHandler>();
handler.ShouldBeOfType<ShipmentHandler>().Shipment.ShouldBeTheSameAs(shipment);
}
}
public class when_getting_all_closed_type_from_an_open_generic_type_by_providing_an_input_parameter
{
[Fact]
public void fetch_the_objects()
{
var container = new Container(x =>
{
x.For<IHandler<Shipment>>().Use<ShipmentHandler>();
x.For<IHandler<Shipment>>().Add<ShipmentHandler2>();
});
var shipment = new Shipment();
var handlers = container
.ForObject(shipment)
.GetAllClosedTypesOf(typeof(IHandler<>))
.As<IHandler>();
handlers[0].ShouldBeOfType<ShipmentHandler>();
handlers[1].ShouldBeOfType<ShipmentHandler2>();
}
}
public class Shipment
{
}
public interface IHandler<T> : IHandler
{
}
public interface IHandler
{
}
public class ShipmentHandler : IHandler<Shipment>
{
private readonly Shipment _shipment;
public ShipmentHandler(Shipment shipment)
{
_shipment = shipment;
}
public Shipment Shipment
{
get { return _shipment; }
}
}
public class ShipmentHandler2 : IHandler<Shipment>
{
private readonly Shipment _shipment;
public ShipmentHandler2(Shipment shipment)
{
_shipment = shipment;
}
public Shipment Shipment
{
get { return _shipment; }
}
}
}
| |
// ---------------------------------------------------------------------------
// <copyright file="ExtendedPropertyCollection.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// ---------------------------------------------------------------------------
//-----------------------------------------------------------------------
// <summary>Defines the ExtendedPropertyCollection class.</summary>
//-----------------------------------------------------------------------
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
/// <summary>
/// Represents a collection of extended properties.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class ExtendedPropertyCollection : ComplexPropertyCollection<ExtendedProperty>, ICustomUpdateSerializer
{
/// <summary>
/// Creates the complex property.
/// </summary>
/// <param name="xmlElementName">Name of the XML element.</param>
/// <returns>Complex property instance.</returns>
internal override ExtendedProperty CreateComplexProperty(string xmlElementName)
{
return new ExtendedProperty();
}
/// <summary>
/// Creates the default complex property.
/// </summary>
/// <returns></returns>
internal override ExtendedProperty CreateDefaultComplexProperty()
{
return new ExtendedProperty();
}
/// <summary>
/// Gets the name of the collection item XML element.
/// </summary>
/// <param name="complexProperty">The complex property.</param>
/// <returns>XML element name.</returns>
internal override string GetCollectionItemXmlElementName(ExtendedProperty complexProperty)
{
// This method is unused in this class, so just return null.
return null;
}
/// <summary>
/// Loads from XML.
/// </summary>
/// <param name="reader">The reader.</param>
/// <param name="localElementName">Name of the local element.</param>
internal override void LoadFromXml(EwsServiceXmlReader reader, string localElementName)
{
ExtendedProperty extendedProperty = new ExtendedProperty();
extendedProperty.LoadFromXml(reader, reader.LocalName);
this.InternalAdd(extendedProperty);
}
/// <summary>
/// Writes to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="xmlElementName">Name of the XML element.</param>
internal override void WriteToXml(EwsServiceXmlWriter writer, string xmlElementName)
{
foreach (ExtendedProperty extendedProperty in this)
{
extendedProperty.WriteToXml(writer, XmlElementNames.ExtendedProperty);
}
}
/// <summary>
/// Internals to json.
/// </summary>
/// <param name="service">The service.</param>
/// <returns></returns>
internal override object InternalToJson(ExchangeService service)
{
List<object> values = new List<object>();
foreach (ExtendedProperty extendedProperty in this)
{
values.Add(extendedProperty.InternalToJson(service));
}
return values.ToArray();
}
/// <summary>
/// Gets existing or adds new extended property.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <returns>ExtendedProperty.</returns>
private ExtendedProperty GetOrAddExtendedProperty(ExtendedPropertyDefinition propertyDefinition)
{
ExtendedProperty extendedProperty;
if (!this.TryGetProperty(propertyDefinition, out extendedProperty))
{
extendedProperty = new ExtendedProperty(propertyDefinition);
this.InternalAdd(extendedProperty);
}
return extendedProperty;
}
/// <summary>
/// Sets an extended property.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="value">The value.</param>
internal void SetExtendedProperty(ExtendedPropertyDefinition propertyDefinition, object value)
{
ExtendedProperty extendedProperty = this.GetOrAddExtendedProperty(propertyDefinition);
extendedProperty.Value = value;
}
/// <summary>
/// Removes a specific extended property definition from the collection.
/// </summary>
/// <param name="propertyDefinition">The definition of the extended property to remove.</param>
/// <returns>True if the property matching the extended property definition was successfully removed from the collection, false otherwise.</returns>
internal bool RemoveExtendedProperty(ExtendedPropertyDefinition propertyDefinition)
{
EwsUtilities.ValidateParam(propertyDefinition, "propertyDefinition");
ExtendedProperty extendedProperty;
if (this.TryGetProperty(propertyDefinition, out extendedProperty))
{
return this.InternalRemove(extendedProperty);
}
else
{
return false;
}
}
/// <summary>
/// Tries to get property.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="extendedProperty">The extended property.</param>
/// <returns>True of property exists in collection.</returns>
private bool TryGetProperty(ExtendedPropertyDefinition propertyDefinition, out ExtendedProperty extendedProperty)
{
extendedProperty = this.Items.Find((prop) => prop.PropertyDefinition.Equals(propertyDefinition));
return extendedProperty != null;
}
/// <summary>
/// Tries to get property value.
/// </summary>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="propertyValue">The property value.</param>
/// <typeparam name="T">Type of expected property value.</typeparam>
/// <returns>True if property exists in collection.</returns>
internal bool TryGetValue<T>(ExtendedPropertyDefinition propertyDefinition, out T propertyValue)
{
ExtendedProperty extendedProperty;
if (this.TryGetProperty(propertyDefinition, out extendedProperty))
{
// Verify that the type parameter and property definition's type are compatible.
if (!typeof(T).IsAssignableFrom(propertyDefinition.Type))
{
string errorMessage = string.Format(
Strings.PropertyDefinitionTypeMismatch,
EwsUtilities.GetPrintableTypeName(propertyDefinition.Type),
EwsUtilities.GetPrintableTypeName(typeof(T)));
throw new ArgumentException(errorMessage, "propertyDefinition");
}
propertyValue = (T)extendedProperty.Value;
return true;
}
else
{
propertyValue = default(T);
return false;
}
}
#region ICustomXmlUpdateSerializer Members
/// <summary>
/// Writes the update to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="ewsObject">The ews object.</param>
/// <param name="propertyDefinition">Property definition.</param>
/// <returns>
/// True if property generated serialization.
/// </returns>
bool ICustomUpdateSerializer.WriteSetUpdateToXml(
EwsServiceXmlWriter writer,
ServiceObject ewsObject,
PropertyDefinition propertyDefinition)
{
List<ExtendedProperty> propertiesToSet = new List<ExtendedProperty>();
propertiesToSet.AddRange(this.AddedItems);
propertiesToSet.AddRange(this.ModifiedItems);
foreach (ExtendedProperty extendedProperty in propertiesToSet)
{
writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetSetFieldXmlElementName());
extendedProperty.PropertyDefinition.WriteToXml(writer);
writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetXmlElementName());
extendedProperty.WriteToXml(writer, XmlElementNames.ExtendedProperty);
writer.WriteEndElement();
writer.WriteEndElement();
}
foreach (ExtendedProperty extendedProperty in this.RemovedItems)
{
writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName());
extendedProperty.PropertyDefinition.WriteToXml(writer);
writer.WriteEndElement();
}
return true;
}
/// <summary>
/// Writes the set update to json.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ewsObject">The ews object.</param>
/// <param name="propertyDefinition">The property definition.</param>
/// <param name="updates">The updates.</param>
/// <returns></returns>
bool ICustomUpdateSerializer.WriteSetUpdateToJson(
ExchangeService service,
ServiceObject ewsObject,
PropertyDefinition propertyDefinition,
List<JsonObject> updates)
{
List<ExtendedProperty> propertiesToSet = new List<ExtendedProperty>();
propertiesToSet.AddRange(this.AddedItems);
propertiesToSet.AddRange(this.ModifiedItems);
foreach (ExtendedProperty extendedProperty in propertiesToSet)
{
updates.Add(
PropertyBag.CreateJsonSetUpdate(
extendedProperty,
service,
ewsObject));
}
foreach (ExtendedProperty extendedProperty in this.RemovedItems)
{
updates.Add(PropertyBag.CreateJsonDeleteUpdate(extendedProperty.PropertyDefinition, service, ewsObject));
}
return true;
}
/// <summary>
/// Writes the deletion update to XML.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="ewsObject">The ews object.</param>
/// <returns>
/// True if property generated serialization.
/// </returns>
bool ICustomUpdateSerializer.WriteDeleteUpdateToXml(EwsServiceXmlWriter writer, ServiceObject ewsObject)
{
foreach (ExtendedProperty extendedProperty in this.Items)
{
writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName());
extendedProperty.PropertyDefinition.WriteToXml(writer);
writer.WriteEndElement();
}
return true;
}
/// <summary>
/// Writes the delete update to json.
/// </summary>
/// <param name="service">The service.</param>
/// <param name="ewsObject">The ews object.</param>
/// <param name="updates">The updates.</param>
/// <returns></returns>
bool ICustomUpdateSerializer.WriteDeleteUpdateToJson(ExchangeService service, ServiceObject ewsObject, List<JsonObject> updates)
{
foreach (ExtendedProperty extendedProperty in this.Items)
{
updates.Add(PropertyBag.CreateJsonDeleteUpdate(extendedProperty.PropertyDefinition, service, ewsObject));
}
return true;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void CompareGreaterThanInt16()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanInt16();
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();
// 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 works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanInt16
{
private const int VectorSize = 16;
private const int Op1ElementCount = VectorSize / sizeof(Int16);
private const int Op2ElementCount = VectorSize / sizeof(Int16);
private const int RetElementCount = VectorSize / sizeof(Int16);
private static Int16[] _data1 = new Int16[Op1ElementCount];
private static Int16[] _data2 = new Int16[Op2ElementCount];
private static Vector128<Int16> _clsVar1;
private static Vector128<Int16> _clsVar2;
private Vector128<Int16> _fld1;
private Vector128<Int16> _fld2;
private SimpleBinaryOpTest__DataTable<Int16, Int16, Int16> _dataTable;
static SimpleBinaryOpTest__CompareGreaterThanInt16()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
}
public SimpleBinaryOpTest__CompareGreaterThanInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), VectorSize);
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (short)(random.Next(short.MinValue, short.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Int16, Int16, Int16>(_data1, _data2, new Int16[RetElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.CompareGreaterThan(
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.CompareGreaterThan(
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.CompareGreaterThan), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.CompareGreaterThan(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr);
var result = Sse2.CompareGreaterThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Int16*)(_dataTable.inArray2Ptr));
var result = Sse2.CompareGreaterThan(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__CompareGreaterThanInt16();
var result = Sse2.CompareGreaterThan(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.CompareGreaterThan(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<Int16> left, Vector128<Int16> right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Int16[] inArray1 = new Int16[Op1ElementCount];
Int16[] inArray2 = new Int16[Op2ElementCount];
Int16[] outArray = new Int16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int16[] left, Int16[] right, Int16[] result, [CallerMemberName] string method = "")
{
if (result[0] != ((left[0] > right[0]) ? unchecked((short)(-1)) : 0))
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != ((left[i] > right[i]) ? unchecked((short)(-1)) : 0))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.CompareGreaterThan)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Utils;
using osu.Framework.Testing;
using osu.Game.Beatmaps;
using osu.Game.Configuration;
using osu.Game.Graphics.UserInterface;
using osu.Game.Overlays.Mods;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.UI;
using osuTK.Input;
namespace osu.Game.Tests.Visual.UserInterface
{
public class TestSceneModSettings : OsuManualInputManagerTestScene
{
private TestModSelectOverlay modSelect;
private readonly Mod testCustomisableMod = new TestModCustomisable1();
private readonly Mod testCustomisableAutoOpenMod = new TestModCustomisable2();
[SetUp]
public void SetUp() => Schedule(() =>
{
SelectedMods.Value = Array.Empty<Mod>();
Ruleset.Value = new TestRulesetInfo();
});
[Test]
public void TestButtonShowsOnCustomisableMod()
{
createModSelect();
openModSelect();
AddAssert("button disabled", () => !modSelect.CustomiseButton.Enabled.Value);
AddUntilStep("wait for button load", () => modSelect.ButtonsLoaded);
AddStep("select mod", () => modSelect.SelectMod(testCustomisableMod));
AddAssert("button enabled", () => modSelect.CustomiseButton.Enabled.Value);
AddStep("open Customisation", () => modSelect.CustomiseButton.TriggerClick());
AddStep("deselect mod", () => modSelect.SelectMod(testCustomisableMod));
AddAssert("controls hidden", () => modSelect.ModSettingsContainer.State.Value == Visibility.Hidden);
}
[Test]
public void TestButtonShowsOnModAlreadyAdded()
{
AddStep("set active mods", () => SelectedMods.Value = new List<Mod> { testCustomisableMod });
createModSelect();
AddAssert("mods still active", () => SelectedMods.Value.Count == 1);
openModSelect();
AddAssert("button enabled", () => modSelect.CustomiseButton.Enabled.Value);
}
[Test]
public void TestCustomisationMenuVisibility()
{
createModSelect();
openModSelect();
AddAssert("Customisation closed", () => modSelect.ModSettingsContainer.State.Value == Visibility.Hidden);
AddStep("select mod", () => modSelect.SelectMod(testCustomisableAutoOpenMod));
AddAssert("Customisation opened", () => modSelect.ModSettingsContainer.State.Value == Visibility.Visible);
AddStep("deselect mod", () => modSelect.SelectMod(testCustomisableAutoOpenMod));
AddAssert("Customisation closed", () => modSelect.ModSettingsContainer.State.Value == Visibility.Hidden);
}
[Test]
public void TestModSettingsUnboundWhenCopied()
{
OsuModDoubleTime original = null;
OsuModDoubleTime copy = null;
AddStep("create mods", () =>
{
original = new OsuModDoubleTime();
copy = (OsuModDoubleTime)original.DeepClone();
});
AddStep("change property", () => original.SpeedChange.Value = 2);
AddAssert("original has new value", () => Precision.AlmostEquals(2.0, original.SpeedChange.Value));
AddAssert("copy has original value", () => Precision.AlmostEquals(1.5, copy.SpeedChange.Value));
}
[Test]
public void TestMultiModSettingsUnboundWhenCopied()
{
MultiMod original = null;
MultiMod copy = null;
AddStep("create mods", () =>
{
original = new MultiMod(new OsuModDoubleTime());
copy = (MultiMod)original.DeepClone();
});
AddStep("change property", () => ((OsuModDoubleTime)original.Mods[0]).SpeedChange.Value = 2);
AddAssert("original has new value", () => Precision.AlmostEquals(2.0, ((OsuModDoubleTime)original.Mods[0]).SpeedChange.Value));
AddAssert("copy has original value", () => Precision.AlmostEquals(1.5, ((OsuModDoubleTime)copy.Mods[0]).SpeedChange.Value));
}
[Test]
public void TestCustomisationMenuNoClickthrough()
{
createModSelect();
openModSelect();
AddStep("change mod settings menu width to full screen", () => modSelect.SetModSettingsWidth(1.0f));
AddStep("select cm2", () => modSelect.SelectMod(testCustomisableAutoOpenMod));
AddAssert("Customisation opened", () => modSelect.ModSettingsContainer.State.Value == Visibility.Visible);
AddStep("hover over mod behind settings menu", () => InputManager.MoveMouseTo(modSelect.GetModButton(testCustomisableMod)));
AddAssert("Mod is not considered hovered over", () => !modSelect.GetModButton(testCustomisableMod).IsHovered);
AddStep("left click mod", () => InputManager.Click(MouseButton.Left));
AddAssert("only cm2 is active", () => SelectedMods.Value.Count == 1);
AddStep("right click mod", () => InputManager.Click(MouseButton.Right));
AddAssert("only cm2 is active", () => SelectedMods.Value.Count == 1);
}
private void createModSelect()
{
AddStep("create mod select", () =>
{
Child = modSelect = new TestModSelectOverlay
{
Origin = Anchor.BottomCentre,
Anchor = Anchor.BottomCentre,
SelectedMods = { BindTarget = SelectedMods }
};
});
}
private void openModSelect()
{
AddStep("open", () => modSelect.Show());
AddUntilStep("wait for ready", () => modSelect.State.Value == Visibility.Visible && modSelect.ButtonsLoaded);
}
private class TestModSelectOverlay : UserModSelectOverlay
{
public new VisibilityContainer ModSettingsContainer => base.ModSettingsContainer;
public new TriangleButton CustomiseButton => base.CustomiseButton;
public bool ButtonsLoaded => ModSectionsContainer.Children.All(c => c.ModIconsLoaded);
public ModButton GetModButton(Mod mod)
{
return ModSectionsContainer.ChildrenOfType<ModButton>().Single(b => b.Mods.Any(m => m.GetType() == mod.GetType()));
}
public void SelectMod(Mod mod) =>
GetModButton(mod).SelectNext(1);
public void SetModSettingsWidth(float newWidth) =>
ModSettingsContainer.Parent.Width = newWidth;
}
public class TestRulesetInfo : RulesetInfo
{
public override Ruleset CreateInstance() => new TestCustomisableModRuleset();
public TestRulesetInfo()
{
Available = true;
}
public class TestCustomisableModRuleset : Ruleset
{
public override IEnumerable<Mod> GetModsFor(ModType type)
{
if (type == ModType.Conversion)
{
return new Mod[]
{
new TestModCustomisable1(),
new TestModCustomisable2()
};
}
return Array.Empty<Mod>();
}
public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => throw new NotImplementedException();
public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => throw new NotImplementedException();
public override DifficultyCalculator CreateDifficultyCalculator(WorkingBeatmap beatmap) => throw new NotImplementedException();
public override string Description { get; } = "test";
public override string ShortName { get; } = "tst";
}
}
private class TestModCustomisable1 : TestModCustomisable
{
public override string Name => "Customisable Mod 1";
public override string Acronym => "CM1";
}
private class TestModCustomisable2 : TestModCustomisable
{
public override string Name => "Customisable Mod 2";
public override string Acronym => "CM2";
public override bool RequiresConfiguration => true;
}
private abstract class TestModCustomisable : Mod, IApplicableMod
{
public override double ScoreMultiplier => 1.0;
public override string Description => "This is a customisable test mod.";
public override ModType Type => ModType.Conversion;
[SettingSource("Sample float", "Change something for a mod")]
public BindableFloat SliderBindable { get; } = new BindableFloat
{
MinValue = 0,
MaxValue = 10,
Default = 5,
Value = 7
};
[SettingSource("Sample bool", "Clicking this changes a setting")]
public BindableBool TickBindable { get; } = new BindableBool();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Text;
using Debug = System.Diagnostics.Debug;
namespace Internal.TypeSystem
{
/// <summary>
/// Represents a bitmap of GC pointers within a memory region divided into
/// pointer-sized cells.
/// </summary>
public partial struct GCPointerMap : IEquatable<GCPointerMap>
{
// Each bit in this array represents a pointer-sized cell.
private int[] _gcFlags;
private int _numCells;
/// <summary>
/// Gets a value indicating whether this map is initialized.
/// </summary>
public bool IsInitialized
{
get
{
return _gcFlags != null;
}
}
/// <summary>
/// Gets the size (in cells) of the pointer map.
/// </summary>
public int Size
{
get
{
return _numCells;
}
}
/// <summary>
/// Gets the number of continuous runs of GC pointers within the map.
/// </summary>
public int NumSeries
{
get
{
int numSeries = 0;
for (int i = 0; i < _numCells; i++)
{
if (this[i])
{
numSeries++;
while (++i < _numCells && this[i]) ;
}
}
return numSeries;
}
}
/// <summary>
/// Returns true if the map is all pointers
/// </summary>
public bool IsAllGCPointers
{
get
{
for (int i = 0; i < _numCells; i++)
{
if (!this[i])
return false;
}
return true;
}
}
public bool this[int index]
{
get
{
return (_gcFlags[index >> 5] & (1 << (index & 0x1F))) != 0;
}
}
public GCPointerMap(int[] gcFlags, int numCells)
{
Debug.Assert(numCells <= gcFlags.Length << 5);
_gcFlags = gcFlags;
_numCells = numCells;
}
public BitEnumerator GetEnumerator()
{
return new BitEnumerator(_gcFlags, 0, _numCells);
}
public override bool Equals(object obj)
{
return obj is GCPointerMap && Equals((GCPointerMap)obj);
}
public bool Equals(GCPointerMap other)
{
if (_numCells != other._numCells)
return false;
for (int i = 0; i < _gcFlags.Length; i++)
if (_gcFlags[i] != other._gcFlags[i])
return false;
return true;
}
public override int GetHashCode()
{
int hashCode = 0;
for (int i = 0; i < _gcFlags.Length; i++)
hashCode ^= _gcFlags[i];
return hashCode;
}
public override string ToString()
{
var sb = new StringBuilder(_numCells);
foreach (var bit in this)
sb.Append(bit ? '1' : '0');
return sb.ToString();
}
}
/// <summary>
/// Utility class to assist in building <see cref="GCPointerMap"/>.
/// </summary>
public struct GCPointerMapBuilder
{
// Each bit in this array represents a pointer-sized cell.
// Bits start at the least significant bit.
private int[] _gcFlags;
private int _pointerSize;
// Both of these are in bytes.
private int _delta;
private int _limit;
public GCPointerMapBuilder(int numBytes, int pointerSize)
{
// Don't care about the remainder - the remainder is not big enough to hold a GC pointer.
int numPointerSizedCells = numBytes / pointerSize;
if (numPointerSizedCells > 0)
{
// Given the number of cells, how many Int32's do we need to represent them?
// (It's one bit per cell, but this time we need to round up.)
_gcFlags = new int[((numPointerSizedCells - 1) >> 5) + 1];
}
else
{
// Not big enough to fit even a single pointer.
_gcFlags = Array.Empty<int>();
}
_pointerSize = pointerSize;
_delta = 0;
_limit = numBytes;
}
public void MarkGCPointer(int offset)
{
Debug.Assert(offset >= 0);
int absoluteOffset = _delta + offset;
Debug.Assert(absoluteOffset % _pointerSize == 0);
Debug.Assert(absoluteOffset <= (_limit - _pointerSize));
int cellIndex = absoluteOffset / _pointerSize;
_gcFlags[cellIndex >> 5] |= 1 << (cellIndex & 0x1F);
}
public GCPointerMapBuilder GetInnerBuilder(int offset, int size)
{
Debug.Assert(offset >= 0);
int absoluteOffset = _delta + offset;
Debug.Assert(absoluteOffset + size <= _limit);
return new GCPointerMapBuilder
{
_gcFlags = this._gcFlags,
_pointerSize = this._pointerSize,
_delta = absoluteOffset,
_limit = absoluteOffset + size
};
}
public GCPointerMap ToGCMap()
{
Debug.Assert(_delta == 0);
return new GCPointerMap(_gcFlags, _limit / _pointerSize);
}
public BitEnumerator GetEnumerator()
{
int numCells = (_limit - _delta) / _pointerSize;
int startCell = _delta / _pointerSize;
return new BitEnumerator(_gcFlags, startCell, numCells);
}
public override string ToString()
{
var sb = new StringBuilder();
foreach (var bit in this)
sb.Append(bit ? '1' : '0');
return sb.ToString();
}
}
public struct BitEnumerator
{
private int[] _buffer;
private int _limitBit;
private int _currentBit;
public BitEnumerator(int[] buffer, int startBit, int numBits)
{
Debug.Assert(startBit >= 0 && numBits >= 0);
Debug.Assert(startBit + numBits <= buffer.Length << 5);
_buffer = buffer;
_currentBit = startBit - 1;
_limitBit = startBit + numBits;
}
public bool Current
{
get
{
return (_buffer[_currentBit >> 5] & (1 << (_currentBit & 0x1F))) != 0;
}
}
public bool MoveNext()
{
_currentBit++;
return _currentBit < _limitBit;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Input;
using Xamarin.Forms.Internals;
using Xamarin.Forms.Platform;
namespace Xamarin.Forms
{
[RenderWith(typeof(_ButtonRenderer))]
public class Button : View, IFontElement, IButtonController
{
public static readonly BindableProperty CommandProperty = BindableProperty.Create("Command", typeof(ICommand), typeof(Button), null, propertyChanged: (bo, o, n) => ((Button)bo).OnCommandChanged());
public static readonly BindableProperty CommandParameterProperty = BindableProperty.Create("CommandParameter", typeof(object), typeof(Button), null,
propertyChanged: (bindable, oldvalue, newvalue) => ((Button)bindable).CommandCanExecuteChanged(bindable, EventArgs.Empty));
public static readonly BindableProperty ContentLayoutProperty =
BindableProperty.Create("ContentLayout", typeof(ButtonContentLayout), typeof(Button), new ButtonContentLayout(ButtonContentLayout.ImagePosition.Left, DefaultSpacing));
public static readonly BindableProperty TextProperty = BindableProperty.Create("Text", typeof(string), typeof(Button), null,
propertyChanged: (bindable, oldVal, newVal) => ((Button)bindable).InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged));
public static readonly BindableProperty TextColorProperty = BindableProperty.Create("TextColor", typeof(Color), typeof(Button), Color.Default);
public static readonly BindableProperty FontProperty = BindableProperty.Create("Font", typeof(Font), typeof(Button), default(Font), propertyChanged: FontStructPropertyChanged);
public static readonly BindableProperty FontFamilyProperty = BindableProperty.Create("FontFamily", typeof(string), typeof(Button), default(string), propertyChanged: SpecificFontPropertyChanged);
public static readonly BindableProperty FontSizeProperty = BindableProperty.Create("FontSize", typeof(double), typeof(Button), -1.0, propertyChanged: SpecificFontPropertyChanged,
defaultValueCreator: bindable => Device.GetNamedSize(NamedSize.Default, (Button)bindable));
public static readonly BindableProperty FontAttributesProperty = BindableProperty.Create("FontAttributes", typeof(FontAttributes), typeof(Button), FontAttributes.None,
propertyChanged: SpecificFontPropertyChanged);
public static readonly BindableProperty BorderWidthProperty = BindableProperty.Create("BorderWidth", typeof(double), typeof(Button), 0d);
public static readonly BindableProperty BorderColorProperty = BindableProperty.Create("BorderColor", typeof(Color), typeof(Button), Color.Default);
public static readonly BindableProperty BorderRadiusProperty = BindableProperty.Create("BorderRadius", typeof(int), typeof(Button), 5);
public static readonly BindableProperty ImageProperty = BindableProperty.Create("Image", typeof(FileImageSource), typeof(Button), default(FileImageSource),
propertyChanging: (bindable, oldvalue, newvalue) => ((Button)bindable).OnSourcePropertyChanging((ImageSource)oldvalue, (ImageSource)newvalue),
propertyChanged: (bindable, oldvalue, newvalue) => ((Button)bindable).OnSourcePropertyChanged((ImageSource)oldvalue, (ImageSource)newvalue));
bool _cancelEvents;
const double DefaultSpacing = 10;
public Color BorderColor
{
get { return (Color)GetValue(BorderColorProperty); }
set { SetValue(BorderColorProperty, value); }
}
public int BorderRadius
{
get { return (int)GetValue(BorderRadiusProperty); }
set { SetValue(BorderRadiusProperty, value); }
}
public double BorderWidth
{
get { return (double)GetValue(BorderWidthProperty); }
set { SetValue(BorderWidthProperty, value); }
}
public ButtonContentLayout ContentLayout
{
get { return (ButtonContentLayout)GetValue(ContentLayoutProperty); }
set { SetValue(ContentLayoutProperty, value); }
}
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public Font Font
{
get { return (Font)GetValue(FontProperty); }
set { SetValue(FontProperty, value); }
}
public FileImageSource Image
{
get { return (FileImageSource)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
public string Text
{
get { return (string)GetValue(TextProperty); }
set { SetValue(TextProperty, value); }
}
public Color TextColor
{
get { return (Color)GetValue(TextColorProperty); }
set { SetValue(TextColorProperty, value); }
}
bool IsEnabledCore
{
set { SetValueCore(IsEnabledProperty, value); }
}
void IButtonController.SendClicked()
{
ICommand cmd = Command;
if (cmd != null)
cmd.Execute(CommandParameter);
EventHandler handler = Clicked;
if (handler != null)
handler(this, EventArgs.Empty);
}
public FontAttributes FontAttributes
{
get { return (FontAttributes)GetValue(FontAttributesProperty); }
set { SetValue(FontAttributesProperty, value); }
}
public string FontFamily
{
get { return (string)GetValue(FontFamilyProperty); }
set { SetValue(FontFamilyProperty, value); }
}
[TypeConverter(typeof(FontSizeConverter))]
public double FontSize
{
get { return (double)GetValue(FontSizeProperty); }
set { SetValue(FontSizeProperty, value); }
}
public event EventHandler Clicked;
protected override void OnBindingContextChanged()
{
FileImageSource image = Image;
if (image != null)
SetInheritedBindingContext(image, BindingContext);
base.OnBindingContextChanged();
}
protected override void OnPropertyChanging(string propertyName = null)
{
if (propertyName == CommandProperty.PropertyName)
{
ICommand cmd = Command;
if (cmd != null)
cmd.CanExecuteChanged -= CommandCanExecuteChanged;
}
base.OnPropertyChanging(propertyName);
}
void CommandCanExecuteChanged(object sender, EventArgs eventArgs)
{
ICommand cmd = Command;
if (cmd != null)
IsEnabledCore = cmd.CanExecute(CommandParameter);
}
static void FontStructPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var button = (Button)bindable;
if (button._cancelEvents)
return;
button.InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
button._cancelEvents = true;
if (button.Font == Font.Default)
{
button.FontFamily = null;
button.FontSize = Device.GetNamedSize(NamedSize.Default, button);
button.FontAttributes = FontAttributes.None;
}
else
{
button.FontFamily = button.Font.FontFamily;
if (button.Font.UseNamedSize)
{
button.FontSize = Device.GetNamedSize(button.Font.NamedSize, button.GetType(), true);
}
else
{
button.FontSize = button.Font.FontSize;
}
button.FontAttributes = button.Font.FontAttributes;
}
button._cancelEvents = false;
}
void OnCommandChanged()
{
if (Command != null)
{
Command.CanExecuteChanged += CommandCanExecuteChanged;
CommandCanExecuteChanged(this, EventArgs.Empty);
}
else
IsEnabledCore = true;
}
void OnSourceChanged(object sender, EventArgs eventArgs)
{
OnPropertyChanged(ImageProperty.PropertyName);
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
}
void OnSourcePropertyChanged(ImageSource oldvalue, ImageSource newvalue)
{
if (newvalue != null)
{
newvalue.SourceChanged += OnSourceChanged;
SetInheritedBindingContext(newvalue, BindingContext);
}
InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
}
void OnSourcePropertyChanging(ImageSource oldvalue, ImageSource newvalue)
{
if (oldvalue != null)
oldvalue.SourceChanged -= OnSourceChanged;
}
static void SpecificFontPropertyChanged(BindableObject bindable, object oldValue, object newValue)
{
var button = (Button)bindable;
if (button._cancelEvents)
return;
button.InvalidateMeasureInternal(InvalidationTrigger.MeasureChanged);
button._cancelEvents = true;
if (button.FontFamily != null)
{
button.Font = Font.OfSize(button.FontFamily, button.FontSize).WithAttributes(button.FontAttributes);
}
else
{
button.Font = Font.SystemFontOfSize(button.FontSize, button.FontAttributes);
}
button._cancelEvents = false;
}
[DebuggerDisplay("Image Position = {Position}, Spacing = {Spacing}")]
[TypeConverter(typeof(ButtonContentTypeConverter))]
public sealed class ButtonContentLayout
{
public enum ImagePosition
{
Left,
Top,
Right,
Bottom
}
public ButtonContentLayout(ImagePosition position, double spacing)
{
Position = position;
Spacing = spacing;
}
public ImagePosition Position { get; }
public double Spacing { get; }
public override string ToString()
{
return $"Image Position = {Position}, Spacing = {Spacing}";
}
}
public sealed class ButtonContentTypeConverter : TypeConverter
{
public override object ConvertFromInvariantString(string value)
{
if (value == null)
{
throw new InvalidOperationException($"Cannot convert null into {typeof(ButtonContentLayout)}");
}
string[] parts = value.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 1 && parts.Length != 2)
{
throw new InvalidOperationException($"Cannot convert \"{value}\" into {typeof(ButtonContentLayout)}");
}
double spacing = DefaultSpacing;
var position = ButtonContentLayout.ImagePosition.Left;
var spacingFirst = char.IsDigit(parts[0][0]);
int positionIndex = spacingFirst ? (parts.Length == 2 ? 1 : -1) : 0;
int spacingIndex = spacingFirst ? 0 : (parts.Length == 2 ? 1 : -1);
if (spacingIndex > -1)
{
spacing = double.Parse(parts[spacingIndex]);
}
if (positionIndex > -1)
{
position =
(ButtonContentLayout.ImagePosition)Enum.Parse(typeof(ButtonContentLayout.ImagePosition), parts[positionIndex], true);
}
return new ButtonContentLayout(position, spacing);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using PSDocs.Configuration;
using PSDocs.Pipeline.Output;
using PSDocs.Processor;
using PSDocs.Resources;
using System;
using System.IO;
using System.Management.Automation;
using System.Text;
namespace PSDocs.Pipeline
{
internal delegate bool ShouldProcess(string target, string action);
public static class PipelineBuilder
{
/// <summary>
/// Invoke-PSDocument.
/// </summary>
public static IInvokePipelineBuilder Invoke(Source[] source, IPSDocumentOption option, PSCmdlet commandRuntime, EngineIntrinsics executionContext)
{
var hostContext = new HostContext(commandRuntime, executionContext);
var builder = new InvokePipelineBuilder(source, hostContext);
builder.Configure(option);
return builder;
}
public static IGetPipelineBuilder Get(Source[] source, IPSDocumentOption option, PSCmdlet commandRuntime, EngineIntrinsics executionContext)
{
var hostContext = new HostContext(commandRuntime, executionContext);
var builder = new GetPipelineBuilder(source, hostContext);
builder.Configure(option);
return builder;
}
public static SourcePipelineBuilder Source(IPSDocumentOption option, PSCmdlet commandRuntime, EngineIntrinsics executionContext)
{
var hostContext = new HostContext(commandRuntime, executionContext);
var builder = new SourcePipelineBuilder(hostContext);
//builder.Configure(option);
return builder;
}
}
public interface IPipelineBuilder
{
IPipelineBuilder Configure(IPSDocumentOption option);
IPipeline Build();
}
/// <summary>
/// Objects that follow the pipeline lifecycle.
/// </summary>
public interface IPipelineDisposable : IDisposable
{
void Begin();
[System.Diagnostics.CodeAnalysis.SuppressMessage("Naming", "CA1716:Identifiers should not match keywords", Justification = "Matches PowerShell pipeline.")]
void End();
}
public interface IPipeline : IPipelineDisposable
{
void Process(PSObject sourceObject);
}
internal abstract class PipelineBuilderBase : IPipelineBuilder
{
protected readonly Source[] Source;
protected readonly PSDocumentOption Option;
protected readonly IPipelineWriter Writer;
protected readonly ShouldProcess ShouldProcess;
protected Action<IDocumentResult, bool> OutputVisitor;
protected VisitTargetObject VisitTargetObject;
private static readonly ShouldProcess EmptyShouldProcess = (target, action) => true;
internal PipelineBuilderBase(Source[] source, HostContext hostContext)
{
Option = new PSDocumentOption();
Source = source;
Writer = new HostPipelineWriter(hostContext);
ShouldProcess = hostContext == null ? EmptyShouldProcess : hostContext.ShouldProcess;
OutputVisitor = (o, enumerate) => WriteToString(o, enumerate, Writer);
VisitTargetObject = PipelineReceiverActions.PassThru;
}
public virtual IPipelineBuilder Configure(IPSDocumentOption option)
{
Option.Configuration = new ConfigurationOption(option.Configuration);
Option.Document = DocumentOption.Combine(option.Document, DocumentOption.Default);
Option.Execution = ExecutionOption.Combine(option.Execution, ExecutionOption.Default);
Option.Input = InputOption.Combine(option.Input, InputOption.Default);
Option.Markdown = MarkdownOption.Combine(option.Markdown, MarkdownOption.Default);
Option.Output = OutputOption.Combine(option.Output, OutputOption.Default);
if (!string.IsNullOrEmpty(Option.Output.Path))
OutputVisitor = (o, enumerate) => WriteToFile(o, Option, Writer, ShouldProcess);
ConfigureCulture();
return this;
}
public abstract IPipeline Build();
/// <summary>
/// Require sources for pipeline execution.
/// </summary>
/// <returns>Returns true when the condition is not met.</returns>
protected bool RequireSources()
{
if (Source == null || Source.Length == 0)
{
Writer.WarnSourcePathNotFound();
return true;
}
return false;
}
/// <summary>
/// Require culture for pipeline exeuction.
/// </summary>
/// <returns>Returns true when the condition is not met.</returns>
protected bool RequireCulture()
{
if (Option.Output.Culture == null || Option.Output.Culture.Length == 0)
{
Writer.ErrorInvariantCulture();
return true;
}
return false;
}
protected virtual PipelineContext PrepareContext()
{
return new PipelineContext(GetOptionContext(), PrepareStream(), Writer, OutputVisitor, null, null);
}
protected virtual OptionContext GetOptionContext()
{
return new OptionContext(Option);
}
protected virtual PipelineStream PrepareStream()
{
return new PipelineStream(null, null);
}
private static void WriteToFile(IDocumentResult result, PSDocumentOption option, IPipelineWriter writer, ShouldProcess shouldProcess)
{
// Calculate paths
var fileName = string.Concat(result.InstanceName, result.Extension);
var outputPath = PSDocumentOption.GetRootedPath(result.OutputPath);
var filePath = Path.Combine(outputPath, fileName);
var parentPath = Directory.GetParent(filePath);
if (!parentPath.Exists && shouldProcess(target: parentPath.FullName, action: PSDocsResources.ShouldCreatePath))
Directory.CreateDirectory(path: parentPath.FullName);
if (shouldProcess(target: outputPath, action: PSDocsResources.ShouldWriteFile))
{
var encoding = GetEncoding(option.Markdown.Encoding.Value);
File.WriteAllText(filePath, result.ToString(), encoding);
// Write file info instead
var fileInfo = new FileInfo(filePath);
writer.WriteObject(fileInfo, false);
}
}
private static void WriteToString(IDocumentResult result, bool enumerate, IPipelineWriter writer)
{
writer.WriteObject(result.ToString(), enumerate);
}
private static Encoding GetEncoding(MarkdownEncoding encoding)
{
switch (encoding)
{
case MarkdownEncoding.UTF7:
return Encoding.UTF7;
case MarkdownEncoding.UTF8:
return Encoding.UTF8;
case MarkdownEncoding.ASCII:
return Encoding.ASCII;
case MarkdownEncoding.Unicode:
return Encoding.Unicode;
case MarkdownEncoding.UTF32:
return Encoding.UTF32;
default:
return new UTF8Encoding(false);
}
}
private void ConfigureCulture()
{
if (Option.Output.Culture == null || Option.Output.Culture.Length == 0)
{
// Fallback to current culture
var current = PSDocumentOption.GetCurrentCulture();
if (current == null || string.IsNullOrEmpty(current.Name))
return;
Option.Output.Culture = new string[] { current.Name };
}
}
protected void AddVisitTargetObjectAction(VisitTargetObjectAction action)
{
// Nest the previous write action in the new supplied action
// Execution chain will be: action -> previous -> previous..n
var previous = VisitTargetObject;
VisitTargetObject = (targetObject) => action(targetObject, previous);
}
}
internal abstract class PipelineBase : IDisposable
{
protected readonly PipelineContext Context;
protected readonly Source[] Source;
// Track whether Dispose has been called.
private bool _Disposed;
protected PipelineBase(PipelineContext context, Source[] source)
{
Context = context;
Source = source;
}
public virtual void Begin()
{
// Do nothing
}
public virtual void Process(PSObject sourceObject)
{
// Do nothing
}
public virtual void End()
{
// Do nothing
}
#region IDisposable
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!_Disposed)
{
if (disposing)
{
Context.Dispose();
}
_Disposed = true;
}
}
#endregion IDisposable
}
}
| |
// 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.
//
// 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.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// JobOperations operations.
/// </summary>
public partial interface IJobOperations
{
/// <summary>
/// Gets lifetime summary statistics for all of the jobs in the
/// specified account.
/// </summary>
/// <remarks>
/// Statistics are aggregated across all jobs that have ever existed in
/// the account, from account creation to the last update time of the
/// statistics.
/// </remarks>
/// <param name='jobGetAllLifetimeStatisticsOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<JobStatistics,JobGetAllLifetimeStatisticsHeaders>> GetAllLifetimeStatisticsWithHttpMessagesAsync(JobGetAllLifetimeStatisticsOptions jobGetAllLifetimeStatisticsOptions = default(JobGetAllLifetimeStatisticsOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes a job.
/// </summary>
/// <remarks>
/// Deleting a job also deletes all tasks that are part of that job,
/// and all job statistics. This also overrides the retention period
/// for task data; that is, if the job contains tasks which are still
/// retained on compute nodes, the Batch services deletes those tasks'
/// working directories and all their contents.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to delete.
/// </param>
/// <param name='jobDeleteOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobDeleteHeaders>> DeleteWithHttpMessagesAsync(string jobId, JobDeleteOptions jobDeleteOptions = default(JobDeleteOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets information about the specified job.
/// </summary>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobGetOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CloudJob,JobGetHeaders>> GetWithHttpMessagesAsync(string jobId, JobGetOptions jobGetOptions = default(JobGetOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This replaces only the job properties specified in the request. For
/// example, if the job has constraints, and a request does not specify
/// the constraints element, then the job keeps the existing
/// constraints.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobPatchParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobPatchOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobPatchHeaders>> PatchWithHttpMessagesAsync(string jobId, JobPatchParameter jobPatchParameter, JobPatchOptions jobPatchOptions = default(JobPatchOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Updates the properties of the specified job.
/// </summary>
/// <remarks>
/// This fully replaces all the updateable properties of the job. For
/// example, if the job has constraints associated with it and if
/// constraints is not specified with this request, then the Batch
/// service will remove the existing constraints.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job whose properties you want to update.
/// </param>
/// <param name='jobUpdateParameter'>
/// The parameters for the request.
/// </param>
/// <param name='jobUpdateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobUpdateHeaders>> UpdateWithHttpMessagesAsync(string jobId, JobUpdateParameter jobUpdateParameter, JobUpdateOptions jobUpdateOptions = default(JobUpdateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Disables the specified job, preventing new tasks from running.
/// </summary>
/// <remarks>
/// The Batch Service immediately moves the job to the disabling state.
/// Batch then uses the disableTasks parameter to determine what to do
/// with the currently running tasks of the job. The job remains in the
/// disabling state until the disable operation is completed and all
/// tasks have been dealt with according to the disableTasks option;
/// the job then moves to the disabled state. No new tasks are started
/// under the job until it moves back to active state. If you try to
/// disable a job that is in any state other than active, disabling, or
/// disabled, the request fails with status code 409.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to disable.
/// </param>
/// <param name='disableTasks'>
/// What to do with active tasks associated with the job. requeue -
/// Terminate running tasks and requeue them. The tasks will run again
/// when the job is enabled. terminate - Terminate running tasks. The
/// tasks will not run again. wait - Allow currently running tasks to
/// complete. Possible values include: 'requeue', 'terminate', 'wait'
/// </param>
/// <param name='jobDisableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobDisableHeaders>> DisableWithHttpMessagesAsync(string jobId, DisableJobOption disableTasks, JobDisableOptions jobDisableOptions = default(JobDisableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Enables the specified job, allowing new tasks to run.
/// </summary>
/// <remarks>
/// When you call this API, the Batch service sets a disabled job to
/// the enabling state. After the this operation is completed, the job
/// moves to the active state, and scheduling of new tasks under the
/// job resumes. The Batch service does not allow a task to remain in
/// the active state for more than 7 days. Therefore, if you enable a
/// job containing active tasks which were added more than 7 days ago,
/// those tasks will not run.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to enable.
/// </param>
/// <param name='jobEnableOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobEnableHeaders>> EnableWithHttpMessagesAsync(string jobId, JobEnableOptions jobEnableOptions = default(JobEnableOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Terminates the specified job, marking it as completed.
/// </summary>
/// <remarks>
/// When a Terminate Job request is received, the Batch service sets
/// the job to the terminating state. The Batch service then terminates
/// any active or running tasks associated with the job, and runs any
/// required Job Release tasks. The job then moves into the completed
/// state.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job to terminate.
/// </param>
/// <param name='terminateReason'>
/// The text you want to appear as the job's TerminateReason. The
/// default is 'UserTerminate'.
/// </param>
/// <param name='jobTerminateOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobTerminateHeaders>> TerminateWithHttpMessagesAsync(string jobId, string terminateReason = default(string), JobTerminateOptions jobTerminateOptions = default(JobTerminateOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Adds a job to the specified account.
/// </summary>
/// <remarks>
/// The Batch service supports two ways to control the work done as
/// part of a job. In the first approach, the user specifies a Job
/// Manager task. The Batch service launches this task when it is ready
/// to start the job. The Job Manager task controls all other tasks
/// that run under this job, by using the Task APIs. In the second
/// approach, the user directly controls the execution of tasks under
/// an active job, by using the Task APIs. Also note: when naming jobs,
/// avoid including sensitive information such as user names or secret
/// project names. This information may appear in telemetry logs
/// accessible to Microsoft Support engineers.
/// </remarks>
/// <param name='job'>
/// The job to be added.
/// </param>
/// <param name='jobAddOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<JobAddHeaders>> AddWithHttpMessagesAsync(JobAddParameter job, JobAddOptions jobAddOptions = default(JobAddOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='jobListOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListHeaders>> ListWithHttpMessagesAsync(JobListOptions jobListOptions = default(JobListOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the jobs that have been created under the specified job
/// schedule.
/// </summary>
/// <param name='jobScheduleId'>
/// The ID of the job schedule from which you want to get a list of
/// jobs.
/// </param>
/// <param name='jobListFromJobScheduleOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleWithHttpMessagesAsync(string jobScheduleId, JobListFromJobScheduleOptions jobListFromJobScheduleOptions = default(JobListFromJobScheduleOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// task for the specified job across the compute nodes where the job
/// has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on
/// all compute nodes that have run the Job Preparation or Job Release
/// task. This includes nodes which have since been removed from the
/// pool.
/// </remarks>
/// <param name='jobId'>
/// The ID of the job.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusWithHttpMessagesAsync(string jobId, JobListPreparationAndReleaseTaskStatusOptions jobListPreparationAndReleaseTaskStatusOptions = default(JobListPreparationAndReleaseTaskStatusOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the jobs in the specified account.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListHeaders>> ListNextWithHttpMessagesAsync(string nextPageLink, JobListNextOptions jobListNextOptions = default(JobListNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the jobs that have been created under the specified job
/// schedule.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListFromJobScheduleNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<CloudJob>,JobListFromJobScheduleHeaders>> ListFromJobScheduleNextWithHttpMessagesAsync(string nextPageLink, JobListFromJobScheduleNextOptions jobListFromJobScheduleNextOptions = default(JobListFromJobScheduleNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the execution status of the Job Preparation and Job Release
/// task for the specified job across the compute nodes where the job
/// has run.
/// </summary>
/// <remarks>
/// This API returns the Job Preparation and Job Release task status on
/// all compute nodes that have run the Job Preparation or Job Release
/// task. This includes nodes which have since been removed from the
/// pool.
/// </remarks>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='jobListPreparationAndReleaseTaskStatusNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// 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>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<JobPreparationAndReleaseTaskExecutionInformation>,JobListPreparationAndReleaseTaskStatusHeaders>> ListPreparationAndReleaseTaskStatusNextWithHttpMessagesAsync(string nextPageLink, JobListPreparationAndReleaseTaskStatusNextOptions jobListPreparationAndReleaseTaskStatusNextOptions = default(JobListPreparationAndReleaseTaskStatusNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using System.Text;
namespace OpenSim.Framework.Serialization
{
/// <summary>
/// Temporary code to do the bare minimum required to read a tar archive for our purposes
/// </summary>
public class TarArchiveReader
{
public enum TarEntryType
{
TYPE_UNKNOWN = 0,
TYPE_NORMAL_FILE = 1,
TYPE_HARD_LINK = 2,
TYPE_SYMBOLIC_LINK = 3,
TYPE_CHAR_SPECIAL = 4,
TYPE_BLOCK_SPECIAL = 5,
TYPE_DIRECTORY = 6,
TYPE_FIFO = 7,
TYPE_CONTIGUOUS_FILE = 8,
}
/// <summary>
/// Binary reader for the underlying stream
/// </summary>
protected BinaryReader m_br;
/// <summary>
/// Used to trim off null chars
/// </summary>
protected static char[] m_nullCharArray = new char[] { '\0' };
/// <summary>
/// Used to trim off space chars
/// </summary>
protected static char[] m_spaceCharArray = new char[] { ' ' };
/// <summary>
/// Generate a tar reader which reads from the given stream.
/// </summary>
/// <param name="s"></param>
public TarArchiveReader(Stream s)
{
m_br = new BinaryReader(s);
}
/// <summary>
/// Read the next entry in the tar file.
/// </summary>
/// <param name="filePath"></param>
/// <returns>the data for the entry. Returns null if there are no more entries</returns>
public byte[] ReadEntry(out string filePath, out TarEntryType entryType)
{
filePath = String.Empty;
entryType = TarEntryType.TYPE_UNKNOWN;
TarHeader header = ReadHeader();
if (null == header)
return null;
entryType = header.EntryType;
filePath = header.FilePath;
return ReadData(header.FileSize);
}
/// <summary>
/// Read the next 512 byte chunk of data as a tar header.
/// </summary>
/// <returns>A tar header struct. null if we have reached the end of the archive.</returns>
protected TarHeader ReadHeader()
{
byte[] header = m_br.ReadBytes(512);
// If there are no more bytes in the stream, return null header
if (header.Length == 0)
return null;
// If we've reached the end of the archive we'll be in null block territory, which means
// the next byte will be 0
if (header[0] == 0)
return null;
TarHeader tarHeader = new TarHeader();
// If we're looking at a GNU tar long link then extract the long name and pull up the next header
if (header[156] == (byte)'L')
{
int longNameLength = ConvertOctalBytesToDecimal(header, 124, 11);
tarHeader.FilePath = Encoding.ASCII.GetString(ReadData(longNameLength));
header = m_br.ReadBytes(512);
}
else
{
tarHeader.FilePath = Encoding.ASCII.GetString(header, 0, 100);
tarHeader.FilePath = tarHeader.FilePath.Trim(m_nullCharArray);
}
tarHeader.FileSize = ConvertOctalBytesToDecimal(header, 124, 11);
switch (header[156])
{
case 0:
tarHeader.EntryType = TarEntryType.TYPE_NORMAL_FILE;
break;
case (byte)'0':
tarHeader.EntryType = TarEntryType.TYPE_NORMAL_FILE;
break;
case (byte)'1':
tarHeader.EntryType = TarEntryType.TYPE_HARD_LINK;
break;
case (byte)'2':
tarHeader.EntryType = TarEntryType.TYPE_SYMBOLIC_LINK;
break;
case (byte)'3':
tarHeader.EntryType = TarEntryType.TYPE_CHAR_SPECIAL;
break;
case (byte)'4':
tarHeader.EntryType = TarEntryType.TYPE_BLOCK_SPECIAL;
break;
case (byte)'5':
tarHeader.EntryType = TarEntryType.TYPE_DIRECTORY;
break;
case (byte)'6':
tarHeader.EntryType = TarEntryType.TYPE_FIFO;
break;
case (byte)'7':
tarHeader.EntryType = TarEntryType.TYPE_CONTIGUOUS_FILE;
break;
}
return tarHeader;
}
/// <summary>
/// Read data following a header
/// </summary>
/// <param name="fileSize"></param>
/// <returns></returns>
protected byte[] ReadData(int fileSize)
{
byte[] data = m_br.ReadBytes(fileSize);
// Read the rest of the empty padding in the 512 byte block
if (fileSize % 512 != 0)
{
int paddingLeft = 512 - (fileSize % 512);
m_br.ReadBytes(paddingLeft);
}
return data;
}
public void Close()
{
m_br.Close();
}
/// <summary>
/// Convert octal bytes to a decimal representation
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static int ConvertOctalBytesToDecimal(byte[] bytes, int startIndex, int count)
{
// Trim leading white space: ancient tars do that instead
// of leading 0s :-( don't ask. really.
string oString = Encoding.ASCII.GetString(bytes, startIndex, count).TrimStart(m_spaceCharArray);
int d = 0;
foreach (char c in oString)
{
d <<= 3;
d |= c - '0';
}
return d;
}
}
public class TarHeader
{
public string FilePath;
public int FileSize;
public TarArchiveReader.TarEntryType EntryType;
}
}
| |
using System;
using Xwt.Drawing;
namespace Xwt.GoogleMaterialDesignIcons
{
public class ActionIcons
{
static Image GetIcon (string id)
{
string resourceId = typeof(ActionIcons).Assembly.FullName.Split (',') [0] + ".Resources.Action." + id + "32px.png";
return Image.FromResource (typeof(ActionIcons), resourceId);
}
public static Image Rotation3d { get { return GetIcon (ActionIconId.Rotation3d); } }
public static Image Accessibility { get { return GetIcon (ActionIconId.Accessibility); } }
public static Image Accessible { get { return GetIcon (ActionIconId.Accessible); } }
public static Image AccountBalance { get { return GetIcon (ActionIconId.AccountBalance); } }
public static Image AccountBalanceWallet { get { return GetIcon (ActionIconId.AccountBalanceWallet); } }
public static Image AccountBox { get { return GetIcon (ActionIconId.AccountBox); } }
public static Image AccountCircle { get { return GetIcon (ActionIconId.AccountCircle); } }
public static Image AddShoppingCart { get { return GetIcon (ActionIconId.AddShoppingCart); } }
public static Image Alarm { get { return GetIcon (ActionIconId.Alarm); } }
public static Image AlarmAdd { get { return GetIcon (ActionIconId.AlarmAdd); } }
public static Image AlarmOff { get { return GetIcon (ActionIconId.AlarmOff); } }
public static Image AlarmOn { get { return GetIcon (ActionIconId.AlarmOn); } }
public static Image AllOut { get { return GetIcon (ActionIconId.AllOut); } }
public static Image Android { get { return GetIcon (ActionIconId.Android); } }
public static Image Announcement { get { return GetIcon (ActionIconId.Announcement); } }
public static Image AspectRatio { get { return GetIcon (ActionIconId.AspectRatio); } }
public static Image Assessment { get { return GetIcon (ActionIconId.Assessment); } }
public static Image Assignment { get { return GetIcon (ActionIconId.Assignment); } }
public static Image AssignmentInd { get { return GetIcon (ActionIconId.AssignmentInd); } }
public static Image AssignmentLate { get { return GetIcon (ActionIconId.AssignmentLate); } }
public static Image AssignmentReturn { get { return GetIcon (ActionIconId.AssignmentReturn); } }
public static Image AssignmentReturned { get { return GetIcon (ActionIconId.AssignmentReturned); } }
public static Image AssignmentTurnedIn { get { return GetIcon (ActionIconId.AssignmentTurnedIn); } }
public static Image Autorenew { get { return GetIcon (ActionIconId.Autorenew); } }
public static Image Backup { get { return GetIcon (ActionIconId.Backup); } }
public static Image Book { get { return GetIcon (ActionIconId.Book); } }
public static Image Bookmark { get { return GetIcon (ActionIconId.Bookmark); } }
public static Image BookmarkBorder { get { return GetIcon (ActionIconId.BookmarkBorder); } }
public static Image BugReport { get { return GetIcon (ActionIconId.BugReport); } }
public static Image Build { get { return GetIcon (ActionIconId.Build); } }
public static Image Cached { get { return GetIcon (ActionIconId.Cached); } }
public static Image CardGiftcard { get { return GetIcon (ActionIconId.CardGiftcard); } }
public static Image CardMembership { get { return GetIcon (ActionIconId.CardMembership); } }
public static Image CardTravel { get { return GetIcon (ActionIconId.CardTravel); } }
public static Image ChangeHistory { get { return GetIcon (ActionIconId.ChangeHistory); } }
public static Image CheckCircle { get { return GetIcon (ActionIconId.CheckCircle); } }
public static Image ChromeReaderMode { get { return GetIcon (ActionIconId.ChromeReaderMode); } }
public static Image Class { get { return GetIcon (ActionIconId.Class); } }
public static Image Code { get { return GetIcon (ActionIconId.Code); } }
public static Image CompareArrows { get { return GetIcon (ActionIconId.CompareArrows); } }
public static Image Copyright { get { return GetIcon (ActionIconId.Copyright); } }
public static Image CreditCard { get { return GetIcon (ActionIconId.CreditCard); } }
public static Image Dashboard { get { return GetIcon (ActionIconId.Dashboard); } }
public static Image DateRange { get { return GetIcon (ActionIconId.DateRange); } }
public static Image Delete { get { return GetIcon (ActionIconId.Delete); } }
public static Image DeleteForever { get { return GetIcon (ActionIconId.DeleteForever); } }
public static Image Description { get { return GetIcon (ActionIconId.Description); } }
public static Image Dns { get { return GetIcon (ActionIconId.Dns); } }
public static Image Done { get { return GetIcon (ActionIconId.Done); } }
public static Image DoneAll { get { return GetIcon (ActionIconId.DoneAll); } }
public static Image DonutLarge { get { return GetIcon (ActionIconId.DonutLarge); } }
public static Image DonutSmall { get { return GetIcon (ActionIconId.DonutSmall); } }
public static Image EuroSymbol { get { return GetIcon (ActionIconId.EuroSymbol); } }
public static Image Event { get { return GetIcon (ActionIconId.Event); } }
public static Image EventSeat { get { return GetIcon (ActionIconId.EventSeat); } }
public static Image ExitToApp { get { return GetIcon (ActionIconId.ExitToApp); } }
public static Image Explore { get { return GetIcon (ActionIconId.Explore); } }
public static Image Extension { get { return GetIcon (ActionIconId.Extension); } }
public static Image Face { get { return GetIcon (ActionIconId.Face); } }
public static Image Favorite { get { return GetIcon (ActionIconId.Favorite); } }
public static Image FavoriteBorder { get { return GetIcon (ActionIconId.FavoriteBorder); } }
public static Image Feedback { get { return GetIcon (ActionIconId.Feedback); } }
public static Image FindInPage { get { return GetIcon (ActionIconId.FindInPage); } }
public static Image FindReplace { get { return GetIcon (ActionIconId.FindReplace); } }
public static Image Fingerprint { get { return GetIcon (ActionIconId.Fingerprint); } }
public static Image FlightLand { get { return GetIcon (ActionIconId.FlightLand); } }
public static Image FlightTakeoff { get { return GetIcon (ActionIconId.FlightTakeoff); } }
public static Image FlipToBack { get { return GetIcon (ActionIconId.FlipToBack); } }
public static Image FlipToFront { get { return GetIcon (ActionIconId.FlipToFront); } }
public static Image Gavel { get { return GetIcon (ActionIconId.Gavel); } }
public static Image GetApp { get { return GetIcon (ActionIconId.GetApp); } }
public static Image Grade { get { return GetIcon (ActionIconId.Grade); } }
public static Image GroupWork { get { return GetIcon (ActionIconId.GroupWork); } }
public static Image GTranslate { get { return GetIcon (ActionIconId.GTranslate); } }
public static Image Help { get { return GetIcon (ActionIconId.Help); } }
public static Image HighlightOff { get { return GetIcon (ActionIconId.HighlightOff); } }
public static Image History { get { return GetIcon (ActionIconId.History); } }
public static Image Home { get { return GetIcon (ActionIconId.Home); } }
public static Image HourglassEmpty { get { return GetIcon (ActionIconId.HourglassEmpty); } }
public static Image HourglassFull { get { return GetIcon (ActionIconId.HourglassFull); } }
public static Image Http { get { return GetIcon (ActionIconId.Http); } }
public static Image Https { get { return GetIcon (ActionIconId.Https); } }
public static Image ImportantDevices { get { return GetIcon (ActionIconId.ImportantDevices); } }
public static Image Info { get { return GetIcon (ActionIconId.Info); } }
public static Image InfoOutline { get { return GetIcon (ActionIconId.InfoOutline); } }
public static Image Input { get { return GetIcon (ActionIconId.Input); } }
public static Image InvertColors { get { return GetIcon (ActionIconId.InvertColors); } }
public static Image Label { get { return GetIcon (ActionIconId.Label); } }
public static Image LabelOutline { get { return GetIcon (ActionIconId.LabelOutline); } }
public static Image Language { get { return GetIcon (ActionIconId.Language); } }
public static Image Launch { get { return GetIcon (ActionIconId.Launch); } }
public static Image LightbulbOutline { get { return GetIcon (ActionIconId.LightbulbOutline); } }
public static Image LineStyle { get { return GetIcon (ActionIconId.LineStyle); } }
public static Image LineWeight { get { return GetIcon (ActionIconId.LineWeight); } }
public static Image List { get { return GetIcon (ActionIconId.List); } }
public static Image Lock { get { return GetIcon (ActionIconId.Lock); } }
public static Image LockOpen { get { return GetIcon (ActionIconId.LockOpen); } }
public static Image LockOutline { get { return GetIcon (ActionIconId.LockOutline); } }
public static Image Loyalty { get { return GetIcon (ActionIconId.Loyalty); } }
public static Image MarkunreadMailbox { get { return GetIcon (ActionIconId.MarkunreadMailbox); } }
public static Image Motorcycle { get { return GetIcon (ActionIconId.Motorcycle); } }
public static Image NoteAdd { get { return GetIcon (ActionIconId.NoteAdd); } }
public static Image Opacity { get { return GetIcon (ActionIconId.Opacity); } }
public static Image OpenInBrowser { get { return GetIcon (ActionIconId.OpenInBrowser); } }
public static Image OpenInNew { get { return GetIcon (ActionIconId.OpenInNew); } }
public static Image OpenWith { get { return GetIcon (ActionIconId.OpenWith); } }
public static Image Pageview { get { return GetIcon (ActionIconId.Pageview); } }
public static Image PanTool { get { return GetIcon (ActionIconId.PanTool); } }
public static Image Payment { get { return GetIcon (ActionIconId.Payment); } }
public static Image PermCameraMic { get { return GetIcon (ActionIconId.PermCameraMic); } }
public static Image PermContactCalendar { get { return GetIcon (ActionIconId.PermContactCalendar); } }
public static Image PermDataSetting { get { return GetIcon (ActionIconId.PermDataSetting); } }
public static Image PermDeviceInformation { get { return GetIcon (ActionIconId.PermDeviceInformation); } }
public static Image PermIdentity { get { return GetIcon (ActionIconId.PermIdentity); } }
public static Image PermMedia { get { return GetIcon (ActionIconId.PermMedia); } }
public static Image PermPhoneMsg { get { return GetIcon (ActionIconId.PermPhoneMsg); } }
public static Image PermScanWifi { get { return GetIcon (ActionIconId.PermScanWifi); } }
public static Image Pets { get { return GetIcon (ActionIconId.Pets); } }
public static Image PictureInPicture { get { return GetIcon (ActionIconId.PictureInPicture); } }
public static Image PictureInPictureAlt { get { return GetIcon (ActionIconId.PictureInPictureAlt); } }
public static Image PlayForWork { get { return GetIcon (ActionIconId.PlayForWork); } }
public static Image Polymer { get { return GetIcon (ActionIconId.Polymer); } }
public static Image PowerSettingsNew { get { return GetIcon (ActionIconId.PowerSettingsNew); } }
public static Image PregnantWoman { get { return GetIcon (ActionIconId.PregnantWoman); } }
public static Image Print { get { return GetIcon (ActionIconId.Print); } }
public static Image QueryBuilder { get { return GetIcon (ActionIconId.QueryBuilder); } }
public static Image QuestionAnswer { get { return GetIcon (ActionIconId.QuestionAnswer); } }
public static Image Receipt { get { return GetIcon (ActionIconId.Receipt); } }
public static Image RecordVoiceOver { get { return GetIcon (ActionIconId.RecordVoiceOver); } }
public static Image Redeem { get { return GetIcon (ActionIconId.Redeem); } }
public static Image RemoveShoppingCart { get { return GetIcon (ActionIconId.RemoveShoppingCart); } }
public static Image ReportProblem { get { return GetIcon (ActionIconId.ReportProblem); } }
public static Image Restore { get { return GetIcon (ActionIconId.Restore); } }
public static Image RestorePage { get { return GetIcon (ActionIconId.RestorePage); } }
public static Image Room { get { return GetIcon (ActionIconId.Room); } }
public static Image RoundedCorner { get { return GetIcon (ActionIconId.RoundedCorner); } }
public static Image Rowing { get { return GetIcon (ActionIconId.Rowing); } }
public static Image Schedule { get { return GetIcon (ActionIconId.Schedule); } }
public static Image Search { get { return GetIcon (ActionIconId.Search); } }
public static Image Settings { get { return GetIcon (ActionIconId.Settings); } }
public static Image SettingsApplications { get { return GetIcon (ActionIconId.SettingsApplications); } }
public static Image SettingsBackupRestore { get { return GetIcon (ActionIconId.SettingsBackupRestore); } }
public static Image SettingsBluetooth { get { return GetIcon (ActionIconId.SettingsBluetooth); } }
public static Image SettingsBrightness { get { return GetIcon (ActionIconId.SettingsBrightness); } }
public static Image SettingsCell { get { return GetIcon (ActionIconId.SettingsCell); } }
public static Image SettingsEthernet { get { return GetIcon (ActionIconId.SettingsEthernet); } }
public static Image SettingsInputAntenna { get { return GetIcon (ActionIconId.SettingsInputAntenna); } }
public static Image SettingsInputComponent { get { return GetIcon (ActionIconId.SettingsInputComponent); } }
public static Image SettingsInputComposite { get { return GetIcon (ActionIconId.SettingsInputComposite); } }
public static Image SettingsInputHdmi { get { return GetIcon (ActionIconId.SettingsInputHdmi); } }
public static Image SettingsInputSvideo { get { return GetIcon (ActionIconId.SettingsInputSvideo); } }
public static Image SettingsOverscan { get { return GetIcon (ActionIconId.SettingsOverscan); } }
public static Image SettingsPhone { get { return GetIcon (ActionIconId.SettingsPhone); } }
public static Image SettingsPower { get { return GetIcon (ActionIconId.SettingsPower); } }
public static Image SettingsRemote { get { return GetIcon (ActionIconId.SettingsRemote); } }
public static Image SettingsVoice { get { return GetIcon (ActionIconId.SettingsVoice); } }
public static Image Shop { get { return GetIcon (ActionIconId.Shop); } }
public static Image ShoppingBasket { get { return GetIcon (ActionIconId.ShoppingBasket); } }
public static Image ShoppingCart { get { return GetIcon (ActionIconId.ShoppingCart); } }
public static Image ShopTwo { get { return GetIcon (ActionIconId.ShopTwo); } }
public static Image SpeakerNotes { get { return GetIcon (ActionIconId.SpeakerNotes); } }
public static Image SpeakerNotesOff { get { return GetIcon (ActionIconId.SpeakerNotesOff); } }
public static Image Spellcheck { get { return GetIcon (ActionIconId.Spellcheck); } }
public static Image Stars { get { return GetIcon (ActionIconId.Stars); } }
public static Image Store { get { return GetIcon (ActionIconId.Store); } }
public static Image Subject { get { return GetIcon (ActionIconId.Subject); } }
public static Image SupervisorAccount { get { return GetIcon (ActionIconId.SupervisorAccount); } }
public static Image SwapHoriz { get { return GetIcon (ActionIconId.SwapHoriz); } }
public static Image SwapVert { get { return GetIcon (ActionIconId.SwapVert); } }
public static Image SwapVerticalCircle { get { return GetIcon (ActionIconId.SwapVerticalCircle); } }
public static Image SystemUpdateAlt { get { return GetIcon (ActionIconId.SystemUpdateAlt); } }
public static Image Tab { get { return GetIcon (ActionIconId.Tab); } }
public static Image TabUnselected { get { return GetIcon (ActionIconId.TabUnselected); } }
public static Image Theaters { get { return GetIcon (ActionIconId.Theaters); } }
public static Image ThumbDown { get { return GetIcon (ActionIconId.ThumbDown); } }
public static Image ThumbsUpDown { get { return GetIcon (ActionIconId.ThumbsUpDown); } }
public static Image ThumbUp { get { return GetIcon (ActionIconId.ThumbUp); } }
public static Image Timeline { get { return GetIcon (ActionIconId.Timeline); } }
public static Image Toc { get { return GetIcon (ActionIconId.Toc); } }
public static Image Today { get { return GetIcon (ActionIconId.Today); } }
public static Image Toll { get { return GetIcon (ActionIconId.Toll); } }
public static Image TouchApp { get { return GetIcon (ActionIconId.TouchApp); } }
public static Image TrackChanges { get { return GetIcon (ActionIconId.TrackChanges); } }
public static Image Translate { get { return GetIcon (ActionIconId.Translate); } }
public static Image TrendingDown { get { return GetIcon (ActionIconId.TrendingDown); } }
public static Image TrendingFlat { get { return GetIcon (ActionIconId.TrendingFlat); } }
public static Image TrendingUp { get { return GetIcon (ActionIconId.TrendingUp); } }
public static Image TurnedIn { get { return GetIcon (ActionIconId.TurnedIn); } }
public static Image TurnedInNot { get { return GetIcon (ActionIconId.TurnedInNot); } }
public static Image Update { get { return GetIcon (ActionIconId.Update); } }
public static Image VerifiedUser { get { return GetIcon (ActionIconId.VerifiedUser); } }
public static Image ViewAgenda { get { return GetIcon (ActionIconId.ViewAgenda); } }
public static Image ViewArray { get { return GetIcon (ActionIconId.ViewArray); } }
public static Image ViewCarousel { get { return GetIcon (ActionIconId.ViewCarousel); } }
public static Image ViewColumn { get { return GetIcon (ActionIconId.ViewColumn); } }
public static Image ViewDay { get { return GetIcon (ActionIconId.ViewDay); } }
public static Image ViewHeadline { get { return GetIcon (ActionIconId.ViewHeadline); } }
public static Image ViewList { get { return GetIcon (ActionIconId.ViewList); } }
public static Image ViewModule { get { return GetIcon (ActionIconId.ViewModule); } }
public static Image ViewQuilt { get { return GetIcon (ActionIconId.ViewQuilt); } }
public static Image ViewStream { get { return GetIcon (ActionIconId.ViewStream); } }
public static Image ViewWeek { get { return GetIcon (ActionIconId.ViewWeek); } }
public static Image Visibility { get { return GetIcon (ActionIconId.Visibility); } }
public static Image VisibilityOff { get { return GetIcon (ActionIconId.VisibilityOff); } }
public static Image WatchLater { get { return GetIcon (ActionIconId.WatchLater); } }
public static Image Work { get { return GetIcon (ActionIconId.Work); } }
public static Image YoutubeSearchedFor { get { return GetIcon (ActionIconId.YoutubeSearchedFor); } }
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections;
using System.Text.RegularExpressions;
using Microsoft.Win32;
namespace Project31.CoreServices
{
/// <summary>
/// A referrer chain holds a table of referrers for urls
/// </summary>
[Serializable]
public class SearchReferrerChain
{
/// <summary>
/// The namespace that holds the referrer chain
/// </summary>
public static string REFERRER_NAMESPACE = "Project31";
/// <summary>
/// The name that holds the referrer chain
/// </summary>
public static string REFERRER_NAME = "ReferrerChain";
/// <summary>
/// Constructs a new referrer chain
/// </summary>
private SearchReferrerChain()
{
}
private static SearchReferrerChain singleton = new SearchReferrerChain();
public static SearchReferrerChain Instance
{
get
{
return singleton;
}
}
private static ExplorerUrlTracker explorerUrlTracker = new ExplorerUrlTracker();
/// <summary>
/// Adds an entry to the referrerChain. Note that entries are only added to the referrer chain
/// if they are either a search or parented by something already in the referrer chain.
/// </summary>
/// <param name="url">The url to add</param>
/// <param name="referrer">The url's referrer</param>
public void Add(string url, string referrer)
{
if (referrer == null)
referrer = string.Empty;
// Add the item if it is a search or a descendant of a search
if (IsSearchUrl(url))
explorerUrlTracker.AddUrl(new ExplorerUrlTracker.UrlInfo(url, null));
else if ( ContainsReferrer(referrer) )
explorerUrlTracker.AddUrl(new ExplorerUrlTracker.UrlInfo(url, referrer));
}
/// <summary>
/// Finds a search spec for a given url.
/// </summary>
/// <param name="url">The url to find the search spec for</param>
/// <returns>The matching searc spec, null if no search spec could be found.</returns>
public SearchSpec FindSearchSpec(string url)
{
string parent = FindParent(url, m_urlList.Length - 1);
// Only return a search spec if the url isn't itself a search
if (parent != url)
return GetSearchSpec(parent);
else
return null;
}
/// <summary>
/// Tests the url against the system provided search descriptors and returns the first matching
/// search spec (if any).
/// </summary>
/// <param name="url">The url to test</param>
/// <returns>The first matching spec, null if no search spec could be matched</returns>
private SearchSpec GetSearchSpec(string url)
{
SearchSpec searchSpec = null;
foreach (SearchDescriptor searchDescriptor in SearchDescriptors)
{
if (IsSearchUrl(url, searchDescriptor))
{
string keywords = (string)UrlHelper.GetQueryParams(url)[searchDescriptor.KeyWordQueryParam];
searchSpec = new SearchSpec();
searchSpec.SearchProviderName = searchDescriptor.SearchProviderName;
searchSpec.SearchUrl = url;
searchSpec.Keywords = keywords.Split('+');
break;
}
}
return searchSpec;
}
/// <summary>
/// Determines if the url is a search url
/// </summary>
/// <param name="url">the url to test</param>
/// <returns>true if the url is a search url, otherwise false</returns>
private bool IsSearchUrl(string url)
{
if (GetSearchSpec(url) != null)
return true;
else
return false;
}
/// <summary>
/// Determines if a search url is a specific search
/// </summary>
/// <param name="url">The url to test</param>
/// <param name="searchDescriptor">The search descriptor to use to determine if the url
/// is a search</param>
/// <returns>true if the url is a search, otherwise false</returns>
private bool IsSearchUrl(string url, SearchDescriptor searchDescriptor)
{
Hashtable t = UrlHelper.GetQueryParams(url);
Uri uri = new Uri(url);
if (uri.GetLeftPart(UriPartial.Path).IndexOf(searchDescriptor.BaseUrlMatch) > -1
&& UrlHelper.GetQueryParams(url).ContainsKey(searchDescriptor.KeyWordQueryParam))
return true;
else
return false;
}
/// <summary>
/// Finds the parent of the url
/// </summary>
/// <param name="url">The url to find the parent of</param>
/// <param name="startingIndex">The location in the referrers to start looking (reverse lookup)</param>
/// <returns>The parent url</returns>
private string FindParent(string url, int startingIndex)
{
string referrer = string.Empty;
int urlIndex = GetUrlIndex(url, startingIndex);
if (urlIndex > -1)
referrer = m_urlList[urlIndex].Referrer;
if (referrer == string.Empty)
return url;
else
return FindParent(referrer, urlIndex);
}
/// <summary>
/// Searches the referrer list for a specific url. Note that this searches
/// backwards through the list from the given starting index.
/// </summary>
/// <param name="url">The url to locate</param>
/// <param name="startingIndex">The index in the referrers at which to start looking</param>
/// <returns>The index to the url, -1 if the url couldn't be found</returns>
private int GetUrlIndex(string url, int startingIndex)
{
int urlIndex = -1;
for (int i = startingIndex; i > -1; i--)
{
if (m_urlList[i].Url == url)
{
urlIndex = i;
break;
}
}
return urlIndex;
}
/// <summary>
/// Determines whether the referrer list contains a specific referrer
/// </summary>
/// <param name="referrer">The refrerrer</param>
/// <returns>true if it contains the referrer, otherwise false</returns>
private bool ContainsReferrer(string referrer)
{
bool containsReferrer = false;
foreach (ExplorerUrlTracker.UrlInfo urlInfo in m_urlList)
{
if (urlInfo.Url == referrer)
{
containsReferrer = true;
break;
}
}
return containsReferrer;
}
/// <summary>
/// The list of referrers
/// </summary>
private ExplorerUrlTracker.UrlInfo[] m_urlList
{
get
{
return explorerUrlTracker.GetUrlHistory();
}
}
/// <summary>
/// The search descriptors to use when matching
/// </summary>
private SearchDescriptor[] SearchDescriptors
{
get
{
if (m_searchDescriptors == null)
m_searchDescriptors = GetSearchDescriptors();
return m_searchDescriptors;
}
}
private SearchDescriptor[] m_searchDescriptors;
/// <summary>
/// Retrieves the search descriptors
/// </summary>
/// <returns></returns>
private SearchDescriptor[] GetSearchDescriptors()
{
return new SearchDescriptor[]
{
new SearchDescriptor("Google", @"google.com", @"q"),
new SearchDescriptor("Teoma", @"teoma.com/search", @"q"),
new SearchDescriptor("AllTheWeb", @"alltheweb.com/search", @"q"),
new SearchDescriptor("Lycos", @"lycos.com", @"query"),
new SearchDescriptor("EBay", @"ebay.com/search", @"query"),
new SearchDescriptor("Yahoo", @"yahoo.com", @"p"),
new SearchDescriptor("Overture", @"overture.com/d/search", @"Keywords"),
new SearchDescriptor("Alta Vista", @"altavista.com/web/results", @"q"),
new SearchDescriptor("DayPop", @"daypop.com/search", @"q")
};
}
}
/// <summary>
/// A Search Descriptor provides the information to process
/// a url and determine whether it is a search (and parse keywords)
/// </summary>
[Serializable]
internal class SearchDescriptor
{
/// <summary>
/// constructs a new search descriptor
/// </summary>
/// <param name="name">The human readable name of the search engine</param>
/// <param name="baseUrlMatch">The portion of the url that will determine a
/// match (in combination with the keywordqueryparam)</param>
/// <param name="keyWordQueryParam">The queryparam that holds the keywords</param>
public SearchDescriptor(string name, string baseUrlMatch, string keyWordQueryParam)
{
m_searchProviderName = name;
m_baseUrlMatch = baseUrlMatch;
m_keyWordQueryParam = keyWordQueryParam;
}
/// <summary>
/// The human readable name of the search engine
/// </summary>
public string SearchProviderName
{
get
{
return m_searchProviderName;
}
}
private string m_searchProviderName;
/// <summary>
/// The portion of the url that will determine a
/// match (in combination with the keywordqueryparam)
/// </summary>
public string BaseUrlMatch
{
get
{
return m_baseUrlMatch;
}
}
private string m_baseUrlMatch;
/// <summary>
/// The queryparam that holds the keywords
/// </summary>
public string KeyWordQueryParam
{
get
{
return m_keyWordQueryParam;
}
}
private string m_keyWordQueryParam;
}
}
| |
/// Copyright (C) 2012-2014 Soomla Inc.
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
using UnityEngine;
using System.Collections.Generic;
using System;
using System.Runtime.InteropServices;
namespace Soomla.Store
{
/// <summary>
/// This class holds the store's meta data including:
/// virtual currencies definitions,
/// virtual currency packs definitions,
/// virtual goods definitions,
/// virtual categories definitions, and
/// virtual non-consumable items definitions
/// </summary>
public class StoreInfo
{
protected const string TAG = "SOOMLA StoreInfo"; // used for Log error messages
static StoreInfo _instance = null;
static StoreInfo instance {
get {
if(_instance == null) {
#if UNITY_ANDROID && !UNITY_EDITOR
_instance = new StoreInfoAndroid();
#elif UNITY_IOS && !UNITY_EDITOR
_instance = new StoreInfoIOS();
#else
_instance = new StoreInfo();
#endif
}
return _instance;
}
}
/// <summary>
/// Initializes <c>StoreInfo</c>.
/// On first initialization, when the database doesn't have any previous version of the store
/// metadata, <c>StoreInfo</c> gets loaded from the given <c>IStoreAssets</c>.
/// After the first initialization, <c>StoreInfo</c> will be initialized from the database.
///
/// IMPORTANT: If you want to override the current <c>StoreInfo</c>, you'll have to bump
/// the version of your implementation of <c>IStoreAssets</c> in order to remove the
/// metadata when the application loads. Bumping the version is done by returning a higher
/// number in <c>IStoreAssets</c>'s <c>getVersion</c>.
/// </summary>
/// <param name="storeAssets">your game's economy</param>
public static void Initialize(IStoreAssets storeAssets) {
// SoomlaUtils.LogDebug(TAG, "Adding currency");
JSONObject currencies = new JSONObject(JSONObject.Type.ARRAY);
foreach(VirtualCurrency vi in storeAssets.GetCurrencies()) {
currencies.Add(vi.toJSONObject());
}
// SoomlaUtils.LogDebug(TAG, "Adding packs");
JSONObject packs = new JSONObject(JSONObject.Type.ARRAY);
foreach(VirtualCurrencyPack vi in storeAssets.GetCurrencyPacks()) {
packs.Add(vi.toJSONObject());
}
// SoomlaUtils.LogDebug(TAG, "Adding goods");
JSONObject suGoods = new JSONObject(JSONObject.Type.ARRAY);
JSONObject ltGoods = new JSONObject(JSONObject.Type.ARRAY);
JSONObject eqGoods = new JSONObject(JSONObject.Type.ARRAY);
JSONObject upGoods = new JSONObject(JSONObject.Type.ARRAY);
JSONObject paGoods = new JSONObject(JSONObject.Type.ARRAY);
foreach(VirtualGood g in storeAssets.GetGoods()){
if (g is SingleUseVG) {
suGoods.Add(g.toJSONObject());
} else if (g is EquippableVG) {
eqGoods.Add(g.toJSONObject());
} else if (g is UpgradeVG) {
upGoods.Add(g.toJSONObject());
} else if (g is LifetimeVG) {
ltGoods.Add(g.toJSONObject());
} else if (g is SingleUsePackVG) {
paGoods.Add(g.toJSONObject());
}
}
JSONObject goods = new JSONObject(JSONObject.Type.OBJECT);
goods.AddField(JSONConsts.STORE_GOODS_SU, suGoods);
goods.AddField(JSONConsts.STORE_GOODS_LT, ltGoods);
goods.AddField(JSONConsts.STORE_GOODS_EQ, eqGoods);
goods.AddField(JSONConsts.STORE_GOODS_UP, upGoods);
goods.AddField(JSONConsts.STORE_GOODS_PA, paGoods);
// SoomlaUtils.LogDebug(TAG, "Adding categories");
JSONObject categories = new JSONObject(JSONObject.Type.ARRAY);
foreach(VirtualCategory vi in storeAssets.GetCategories()) {
categories.Add(vi.toJSONObject());
}
// SoomlaUtils.LogDebug(TAG, "Adding nonConsumables");
JSONObject nonConsumables = new JSONObject(JSONObject.Type.ARRAY);
foreach(NonConsumableItem vi in storeAssets.GetNonConsumableItems()) {
nonConsumables.Add(vi.toJSONObject());
}
// SoomlaUtils.LogDebug(TAG, "Preparing StoreAssets JSONObject");
JSONObject storeAssetsObj = new JSONObject(JSONObject.Type.OBJECT);
storeAssetsObj.AddField(JSONConsts.STORE_CATEGORIES, categories);
storeAssetsObj.AddField(JSONConsts.STORE_CURRENCIES, currencies);
storeAssetsObj.AddField(JSONConsts.STORE_CURRENCYPACKS, packs);
storeAssetsObj.AddField(JSONConsts.STORE_GOODS, goods);
storeAssetsObj.AddField(JSONConsts.STORE_NONCONSUMABLES, nonConsumables);
string storeAssetsJSON = storeAssetsObj.print();
instance._initialize(storeAssets.GetVersion(), storeAssetsJSON);
}
/// <summary>
/// Gets the item with the given <c>itemId</c>.
/// </summary>
/// <param name="itemId">Item id.</param>
/// <exception cref="VirtualItemNotFoundException">Exception is thrown if item is not found.</exception>
/// <returns>Item with the given id.</returns>
public static VirtualItem GetItemByItemId(string itemId) {
SoomlaUtils.LogDebug(TAG, "Trying to fetch an item with itemId: " + itemId);
return instance._getItemByItemId(itemId);
}
/// <summary>
/// Gets the purchasable item with the given <c>productId</c>.
/// </summary>
/// <param name="productId">Product id.</param>
/// <exception cref="VirtualItemNotFoundException">Exception is thrown if item is not found.</exception>
/// <returns>Purchasable virtual item with the given id.</returns>
public static PurchasableVirtualItem GetPurchasableItemWithProductId(string productId) {
return instance._getPurchasableItemWithProductId(productId);
}
/// <summary>
/// Gets the category that the virtual good with the given <c>goodItemId</c> belongs to.
/// </summary>
/// <param name="goodItemId">Item id.</param>
/// <exception cref="VirtualItemNotFoundException">Exception is thrown if category is not found.</exception>
/// <returns>Category that the item with given id belongs to.</returns>
public static VirtualCategory GetCategoryForVirtualGood(string goodItemId) {
return instance._getCategoryForVirtualGood(goodItemId);
}
/// <summary>
/// Gets the first upgrade for virtual good with the given <c>goodItemId</c>.
/// </summary>
/// <param name="goodItemId">Item id.</param>
/// <returns>The first upgrade for virtual good with the given id.</returns>
public static UpgradeVG GetFirstUpgradeForVirtualGood(string goodItemId) {
return instance._getFirstUpgradeForVirtualGood(goodItemId);
}
/// <summary>
/// Gets the last upgrade for the virtual good with the given <c>goodItemId</c>.
/// </summary>
/// <param name="goodItemId">item id</param>
/// <returns>last upgrade for virtual good with the given id</returns>
public static UpgradeVG GetLastUpgradeForVirtualGood(string goodItemId) {
return instance._getLastUpgradeForVirtualGood(goodItemId);
}
/// <summary>
/// Gets all the upgrades for the virtual good with the given <c>goodItemId</c>.
/// </summary>
/// <param name="goodItemId">Item id.</param>
/// <returns>All upgrades for virtual good with the given id.</returns>
public static List<UpgradeVG> GetUpgradesForVirtualGood(string goodItemId) {
SoomlaUtils.LogDebug(TAG, "Trying to fetch upgrades for " + goodItemId);
return instance._getUpgradesForVirtualGood(goodItemId);
}
/// <summary>
/// Fetches the virtual currencies of your game.
/// </summary>
/// <returns>The virtual currencies.</returns>
public static List<VirtualCurrency> GetVirtualCurrencies() {
SoomlaUtils.LogDebug(TAG, "Trying to fetch currencies");
return instance._getVirtualCurrencies();
}
/// <summary>
/// Fetches the virtual goods of your game.
/// </summary>
/// <returns>All virtual goods.</returns>
public static List<VirtualGood> GetVirtualGoods() {
SoomlaUtils.LogDebug(TAG, "Trying to fetch goods");
return instance._getVirtualGoods();
}
/// <summary>
/// Fetches the virtual currency packs of your game.
/// </summary>
/// <returns>All virtual currency packs.</returns>
public static List<VirtualCurrencyPack> GetVirtualCurrencyPacks() {
SoomlaUtils.LogDebug(TAG, "Trying to fetch packs");
return instance._getVirtualCurrencyPacks();
}
/// <summary>
/// Fetches the non consumable items of your game.
/// </summary>
/// <returns>All non consumable items.</returns>
public static List<NonConsumableItem> GetNonConsumableItems() {
SoomlaUtils.LogDebug(TAG, "Trying to fetch noncons");
return instance._getNonConsumableItems();
}
/// <summary>
/// Fetches the virtual categories of your game.
/// </summary>
/// <returns>All virtual categories.</returns>
public static List<VirtualCategory> GetVirtualCategories() {
SoomlaUtils.LogDebug(TAG, "Trying to fetch categories");
return instance._getVirtualCategories();
}
virtual protected void _initialize(int version, string storeAssetsJSON) {
}
virtual protected VirtualItem _getItemByItemId(string itemId) {
return null;
}
virtual protected PurchasableVirtualItem _getPurchasableItemWithProductId(string productId) {
return null;
}
virtual protected VirtualCategory _getCategoryForVirtualGood(string goodItemId) {
return null;
}
virtual protected UpgradeVG _getFirstUpgradeForVirtualGood(string goodItemId) {
return null;
}
virtual protected UpgradeVG _getLastUpgradeForVirtualGood(string goodItemId) {
return null;
}
virtual protected List<UpgradeVG> _getUpgradesForVirtualGood(string goodItemId) {
return new List<UpgradeVG>();
}
virtual protected List<VirtualCurrency> _getVirtualCurrencies() {
return new List<VirtualCurrency>();
}
virtual protected List<VirtualGood> _getVirtualGoods() {
return new List<VirtualGood>();
}
virtual protected List<VirtualCurrencyPack> _getVirtualCurrencyPacks() {
return new List<VirtualCurrencyPack>();
}
virtual protected List<NonConsumableItem> _getNonConsumableItems() {
return new List<NonConsumableItem>();
}
virtual protected List<VirtualCategory> _getVirtualCategories() {
return new List<VirtualCategory>();
}
}
}
| |
/* Copyright notice and license
Copyright 2007-2010 WebDriver committers
Copyright 2007-2010 Google Inc.
Portions copyright 2007 ThoughtWorks, Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Collections.ObjectModel;
using System.Text.RegularExpressions;
using OpenQA.Selenium.Internal;
namespace OpenQA.Selenium
{
/// <summary>
/// Provides a mechanism by which to find elements within a document.
/// </summary>
/// <remarks>It is possible to create your own locating mechanisms for finding documents.
/// In order to do this,subclass this class and override the protected methods. However,
/// it is expected that that all subclasses rely on the basic finding mechanisms provided
/// through static methods of this class. An example of this can be found in OpenQA.Support.ByIdOrName
/// </remarks>
public class By
{
private FindElementDelegate findElementMethod;
private FindElementsDelegate findElementsMethod;
private string description = "OpenQA.Selenium.By";
private delegate IWebElement FindElementDelegate(ISearchContext context);
private delegate ReadOnlyCollection<IWebElement> FindElementsDelegate(ISearchContext context);
/// <summary>
/// Gets a mechanism to find elements by their ID.
/// </summary>
/// <param name="idToFind">The ID to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Id(string idToFind)
{
if (idToFind == null)
{
throw new ArgumentNullException("idToFind", "Cannot find elements with a null id attribute.");
}
By by = new By();
by.findElementMethod = (ISearchContext context) => ((IFindsById) context).FindElementById(idToFind);
by.findElementsMethod = (ISearchContext context) => ((IFindsById) context).FindElementsById(idToFind);
by.description = "By.Id: " + idToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their link text.
/// </summary>
/// <param name="linkTextToFind">The link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By LinkText(string linkTextToFind)
{
if (linkTextToFind == null)
{
throw new ArgumentNullException("linkTextToFind", "Cannot find elements when link text is null.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByLinkText) context).FindElementByLinkText(linkTextToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByLinkText) context).FindElementsByLinkText(linkTextToFind);
by.description = "By.LinkText: " + linkTextToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their name.
/// </summary>
/// <param name="nameToFind">The name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By Name(string nameToFind)
{
if (nameToFind == null)
{
throw new ArgumentNullException("nameToFind", "Cannot find elements when name text is null.");
}
By by = new By();
by.findElementMethod = (ISearchContext context) => ((IFindsByName) context).FindElementByName(nameToFind);
by.findElementsMethod = (ISearchContext context) => ((IFindsByName) context).FindElementsByName(nameToFind);
by.description = "By.Name: " + nameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by an XPath query.
/// </summary>
/// <param name="xpathToFind">The XPath query to use.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By XPath(string xpathToFind)
{
if (xpathToFind == null)
{
throw new ArgumentNullException("xpathToFind", "Cannot find elements when the XPath expression is null.");
}
By by = new By();
by.findElementMethod = (ISearchContext context) => ((IFindsByXPath) context).FindElementByXPath(xpathToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByXPath) context).FindElementsByXPath(xpathToFind);
by.description = "By.XPath: " + xpathToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their CSS class.
/// </summary>
/// <param name="classNameToFind">The CSS class to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
/// <remarks>If an element has many classes then this will match against each of them.
/// For example if the value is "one two onone", then the following values for the
/// className parameter will match: "one" and "two".</remarks>
public static By ClassName(string classNameToFind)
{
if (classNameToFind == null)
{
throw new ArgumentNullException("classNameToFind", "Cannot find elements when the class name expression is null.");
}
if (new Regex(".*\\s+.*").IsMatch(classNameToFind))
{
throw new IllegalLocatorException("Compound class names are not supported. Consider searching for one class name and filtering the results.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByClassName) context).FindElementByClassName(classNameToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByClassName) context).FindElementsByClassName(classNameToFind);
by.description = "By.ClassName[Contains]: " + classNameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by a partial match on their link text.
/// </summary>
/// <param name="partialLinkTextToFind">The partial link text to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By PartialLinkText(string partialLinkTextToFind)
{
By by = new By();
by.findElementMethod =
(ISearchContext context) =>
((IFindsByPartialLinkText) context).FindElementByPartialLinkText(partialLinkTextToFind);
by.findElementsMethod =
(ISearchContext context) =>
((IFindsByPartialLinkText) context).FindElementsByPartialLinkText(partialLinkTextToFind);
by.description = "By.PartialLinkText: " + partialLinkTextToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their tag name.
/// </summary>
/// <param name="tagNameToFind">The tag name to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By TagName(string tagNameToFind)
{
if (tagNameToFind == null)
{
throw new ArgumentNullException("tagNameToFind", "Cannot find elements when name tag name is null.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByTagName) context).FindElementByTagName(tagNameToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByTagName) context).FindElementsByTagName(tagNameToFind);
by.description = "By.TagName: " + tagNameToFind;
return by;
}
/// <summary>
/// Gets a mechanism to find elements by their cascading stylesheet (CSS) selector.
/// </summary>
/// <param name="cssSelectorToFind">The CSS selector to find.</param>
/// <returns>A <see cref="By"/> object the driver can use to find the elements.</returns>
public static By CssSelector(string cssSelectorToFind)
{
if (cssSelectorToFind == null)
{
throw new ArgumentNullException("cssSelectorToFind", "Cannot find elements when name CSS selector is null.");
}
By by = new By();
by.findElementMethod =
(ISearchContext context) => ((IFindsByCssSelector) context).FindElementByCssSelector(cssSelectorToFind);
by.findElementsMethod =
(ISearchContext context) => ((IFindsByCssSelector) context).FindElementsByCssSelector(cssSelectorToFind);
by.description = "By.CssSelector: " + cssSelectorToFind;
return by;
}
/// <summary>
/// Finds the first element matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>The first matching <see cref="IWebElement"/> on the current context.</returns>
public virtual IWebElement FindElement(ISearchContext context)
{
return findElementMethod(context);
}
/// <summary>
/// Finds all elements matching the criteria.
/// </summary>
/// <param name="context">An <see cref="ISearchContext"/> object to use to search for the elements.</param>
/// <returns>A <see cref="ReadOnlyCollection{T}"/> of all <see cref="IWebElement">WebElements</see>
/// matching the current criteria, or an empty list if nothing matches.</returns>
public virtual ReadOnlyCollection<IWebElement> FindElements(ISearchContext context)
{
return findElementsMethod(context);
}
/// <summary>
/// Gets a string representation of the finder.
/// </summary>
/// <returns>The string displaying the finder content.</returns>
public override string ToString()
{
return description;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace System.Reflection.Emit.Tests
{
public class EnumBuilderMethodTests
{
public static IEnumerable<object[]> DefineLiteral_TestData()
{
yield return new object[] { typeof(byte), (byte)0 };
yield return new object[] { typeof(byte), (byte)1 };
yield return new object[] { typeof(sbyte), (sbyte)0 };
yield return new object[] { typeof(sbyte), (sbyte)1 };
yield return new object[] { typeof(ushort), (ushort)0 };
yield return new object[] { typeof(ushort), (ushort)1 };
yield return new object[] { typeof(short), (short)0 };
yield return new object[] { typeof(short), (short)1 };
yield return new object[] { typeof(uint), (uint)0 };
yield return new object[] { typeof(uint), (uint)1 };
yield return new object[] { typeof(int), 0 };
yield return new object[] { typeof(int), 1 };
yield return new object[] { typeof(ulong), (ulong)0 };
yield return new object[] { typeof(ulong), (ulong)1 };
yield return new object[] { typeof(long), (long)0 };
yield return new object[] { typeof(long), (long)1 };
yield return new object[] { typeof(char), (char)0 };
yield return new object[] { typeof(char), (char)1 };
yield return new object[] { typeof(bool), true };
yield return new object[] { typeof(bool), false };
yield return new object[] { typeof(float), 0f };
yield return new object[] { typeof(float), 1.1f };
yield return new object[] { typeof(double), 0d };
yield return new object[] { typeof(double), 1.1d };
}
[Theory]
[MemberData(nameof(DefineLiteral_TestData))]
public void DefineLiteral(Type underlyingType, object literalValue)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType);
FieldBuilder literal = enumBuilder.DefineLiteral("FieldOne", literalValue);
Assert.Equal("FieldOne", literal.Name);
Assert.Equal(enumBuilder.Name, literal.DeclaringType.Name);
Assert.Equal(FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal, literal.Attributes);
Assert.Equal(enumBuilder.AsType(), literal.FieldType);
Type createdEnum = enumBuilder.CreateTypeInfo().AsType();
FieldInfo createdLiteral = createdEnum.GetField("FieldOne");
Assert.Equal(createdEnum, createdLiteral.FieldType);
if (literalValue is bool || literalValue is float || literalValue is double)
{
// EnumBuilder generates invalid data for non-integer enums
Assert.Throws<FormatException>(() => createdLiteral.GetValue(null));
}
else
{
Assert.Equal(Enum.ToObject(createdEnum, literalValue), createdLiteral.GetValue(null));
}
}
[Fact]
public void DefineLiteral_NullLiteralName_ThrowsArgumentNullException()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
AssertExtensions.Throws<ArgumentNullException>("fieldName", () => enumBuilder.DefineLiteral(null, 1));
}
[Theory]
[InlineData("")]
[InlineData("\0")]
[InlineData("\0abc")]
public void DefineLiteral_EmptyLiteralName_ThrowsArgumentException(string literalName)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
AssertExtensions.Throws<ArgumentException>("fieldName", () => enumBuilder.DefineLiteral(literalName, 1));
}
public static IEnumerable<object[]> DefineLiteral_InvalidLiteralValue_ThrowsArgumentException_TestData()
{
yield return new object[] { typeof(int), null };
yield return new object[] { typeof(int), (short)1 };
yield return new object[] { typeof(short), 1 };
yield return new object[] { typeof(float), 1d };
yield return new object[] { typeof(double), 1f };
yield return new object[] { typeof(IntPtr), (IntPtr)1 };
yield return new object[] { typeof(UIntPtr), (UIntPtr)1 };
yield return new object[] { typeof(int).MakePointerType(), 1 };
yield return new object[] { typeof(int).MakeByRefType(), 1 };
yield return new object[] { typeof(int[]), new int[] { 1 } };
yield return new object[] { typeof(int?), 1 };
yield return new object[] { typeof(int?), null };
yield return new object[] { typeof(string), null };
}
[Theory]
[MemberData(nameof(DefineLiteral_InvalidLiteralValue_ThrowsArgumentException_TestData))]
public void DefineLiteral_InvalidLiteralValue_ThrowsArgumentException(Type underlyingType, object literalValue)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType);
Assert.Throws<ArgumentException>(null, () => enumBuilder.DefineLiteral("LiteralName", literalValue));
}
public static IEnumerable<object[]> DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation_TestData()
{
yield return new object[] { typeof(DateTime), DateTime.Now };
yield return new object[] { typeof(string), "" }; ;
}
[Theory]
[MemberData(nameof(DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation_TestData))]
public void DefineLiteral_InvalidLiteralValue_ThrowsTypeLoadExceptionOnCreation(Type underlyingType, object literalValue)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, underlyingType);
FieldBuilder literal = enumBuilder.DefineLiteral("LiteralName", literalValue);
Assert.Throws<TypeLoadException>(() => enumBuilder.CreateTypeInfo());
}
[Fact]
public void IsAssignableFrom()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
Assert.False(enumBuilder.IsAssignableFrom(null));
Assert.True(enumBuilder.IsAssignableFrom(typeof(int).GetTypeInfo()));
Assert.False(enumBuilder.IsAssignableFrom(typeof(short).GetTypeInfo()));
}
[Fact]
public void GetElementType_ThrowsNotSupportedException()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
Assert.Throws<NotSupportedException>(() => enumBuilder.GetElementType());
}
[Fact]
public void MakeArrayType()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakeArrayType();
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal("TestEnum[]", arrayType.Name);
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(260)]
public void MakeArrayType_Int(int rank)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakeArrayType(rank);
string ranks = rank == 1 ? "*" : string.Empty;
for (int i = 1; i < rank; i++)
{
ranks += ",";
}
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal($"TestEnum[{ranks}]", arrayType.Name);
}
[Theory]
[InlineData(0)]
[InlineData(-1)]
public void MakeArrayType_Int_RankLessThanOne_ThrowsIndexOutOfRange(int rank)
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Assert.Throws<IndexOutOfRangeException>(() => enumBuilder.MakeArrayType(rank));
}
[Fact]
public void MakeByRefType()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakeByRefType();
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal("TestEnum&", arrayType.Name);
}
[Fact]
public void MakePointerType()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int), enumName: "TestEnum");
Type arrayType = enumBuilder.MakePointerType();
Assert.Equal(typeof(Array), arrayType.GetTypeInfo().BaseType);
Assert.Equal("TestEnum*", arrayType.Name);
}
[Fact]
public void SetCustomAttribute_ConstructorInfo_ByteArray()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
enumBuilder.CreateTypeInfo().AsType();
ConstructorInfo attributeConstructor = typeof(BoolAttribute).GetConstructor(new Type[] { typeof(bool) });
enumBuilder.SetCustomAttribute(attributeConstructor, new byte[] { 01, 00, 01 });
Attribute[] objVals = (Attribute[])CustomAttributeExtensions.GetCustomAttributes(enumBuilder, true).ToArray();
Assert.Equal(new BoolAttribute(true), objVals[0]);
}
[Fact]
public void SetCustomAttribute_CustomAttributeBuilder()
{
EnumBuilder enumBuilder = Helpers.DynamicEnum(TypeAttributes.Public, typeof(int));
enumBuilder.CreateTypeInfo().AsType();
ConstructorInfo attributeConstructor = typeof(BoolAttribute).GetConstructor(new Type[] { typeof(bool) });
CustomAttributeBuilder attributeBuilder = new CustomAttributeBuilder(attributeConstructor, new object[] { true });
enumBuilder.SetCustomAttribute(attributeBuilder);
object[] objVals = enumBuilder.GetCustomAttributes(true).ToArray();
Assert.Equal(new BoolAttribute(true), objVals[0]);
}
public class BoolAttribute : Attribute
{
private bool _b;
public BoolAttribute(bool myBool) { _b = myBool; }
}
}
}
| |
using System;
using Cosmos.IL2CPU.X86;
using CPU = Cosmos.Assembler.x86;
using Cosmos.Assembler.x86;
using Label = Cosmos.Assembler.Label;
namespace Cosmos.IL2CPU.X86.IL
{
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Beq)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bge)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bgt)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Ble)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Blt)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bne_Un)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bge_Un)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Bgt_Un)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Ble_Un)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Blt_Un)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Brfalse)]
[Cosmos.IL2CPU.OpCode(ILOpCode.Code.Brtrue)]
public class Branch : ILOp
{
public Branch(Cosmos.Assembler.Assembler aAsmblr)
: base(aAsmblr)
{
}
public override void Execute(MethodInfo aMethod, ILOpCode aOpCode)
{
var xIsSingleCompare = true;
switch (aOpCode.OpCode)
{
case ILOpCode.Code.Beq:
case ILOpCode.Code.Bge:
case ILOpCode.Code.Bgt:
case ILOpCode.Code.Bge_Un:
case ILOpCode.Code.Bgt_Un:
case ILOpCode.Code.Ble:
case ILOpCode.Code.Ble_Un:
case ILOpCode.Code.Bne_Un:
case ILOpCode.Code.Blt:
case ILOpCode.Code.Blt_Un:
xIsSingleCompare = false;
break;
}
var xStackContent = aOpCode.StackPopTypes[0];
var xStackContentSize = SizeOfType(xStackContent);
if (xStackContentSize > 8)
{
throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: StackSize > 8 not supported");
}
CPU.ConditionalTestEnum xTestOp;
// all conditions are inverted here?
switch (aOpCode.OpCode)
{
case ILOpCode.Code.Beq:
xTestOp = CPU.ConditionalTestEnum.Zero;
break;
case ILOpCode.Code.Bge:
xTestOp = CPU.ConditionalTestEnum.GreaterThanOrEqualTo;
break;
case ILOpCode.Code.Bgt:
xTestOp = CPU.ConditionalTestEnum.GreaterThan;
break;
case ILOpCode.Code.Ble:
xTestOp = CPU.ConditionalTestEnum.LessThanOrEqualTo;
break;
case ILOpCode.Code.Blt:
xTestOp = CPU.ConditionalTestEnum.LessThan;
break;
case ILOpCode.Code.Bne_Un:
xTestOp = CPU.ConditionalTestEnum.NotEqual;
break;
case ILOpCode.Code.Bge_Un:
xTestOp = CPU.ConditionalTestEnum.AboveOrEqual;
break;
case ILOpCode.Code.Bgt_Un:
xTestOp = CPU.ConditionalTestEnum.Above;
break;
case ILOpCode.Code.Ble_Un:
xTestOp = CPU.ConditionalTestEnum.BelowOrEqual;
break;
case ILOpCode.Code.Blt_Un:
xTestOp = CPU.ConditionalTestEnum.Below;
break;
case ILOpCode.Code.Brfalse:
xTestOp = CPU.ConditionalTestEnum.Zero;
break;
case ILOpCode.Code.Brtrue:
xTestOp = CPU.ConditionalTestEnum.NotZero;
break;
default:
throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Unknown OpCode for conditional branch.");
}
if (!xIsSingleCompare)
{
if (xStackContentSize <= 4)
{
//if (xStackContent.IsFloat)
//{
// throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Comparison of floats (System.Single) is not yet supported!");
//}
//else
//{
new CPU.Pop { DestinationReg = CPU.Registers.EAX };
new CPU.Pop { DestinationReg = CPU.Registers.EBX };
new CPU.Compare { DestinationReg = CPU.Registers.EBX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = xTestOp, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
//}
}
else
{
//if (xStackContent.IsFloat)
//{
// throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Comparison of doubles (System.Double) is not yet supported!");
//}
//else
//{
var xNoJump = GetLabel(aMethod, aOpCode) + "__NoBranch";
// value 2 EBX:EAX
new CPU.Pop { DestinationReg = CPU.Registers.EAX };
new CPU.Pop { DestinationReg = CPU.Registers.EBX };
// value 1 EDX:ECX
new CPU.Pop { DestinationReg = CPU.Registers.ECX };
new CPU.Pop { DestinationReg = CPU.Registers.EDX };
switch (xTestOp)
{
case ConditionalTestEnum.Zero: // Equal
case ConditionalTestEnum.NotEqual: // NotZero
new CPU.Xor { DestinationReg = CPU.Registers.EAX, SourceReg = CPU.Registers.ECX };
new CPU.ConditionalJump { Condition = xTestOp, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.Xor { DestinationReg = CPU.Registers.EBX, SourceReg = CPU.Registers.EDX };
new CPU.ConditionalJump { Condition = xTestOp, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
break;
case ConditionalTestEnum.GreaterThanOrEqualTo:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = xNoJump };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump };
break;
case ConditionalTestEnum.GreaterThan:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = xNoJump };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.BelowOrEqual, DestinationLabel = xNoJump };
break;
case ConditionalTestEnum.LessThanOrEqualTo:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = xNoJump };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.BelowOrEqual, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
break;
case ConditionalTestEnum.LessThan:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.LessThan, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.GreaterThan, DestinationLabel = xNoJump };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
break;
// from here all unsigned
case ConditionalTestEnum.AboveOrEqual:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump };
break;
case ConditionalTestEnum.Above:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.BelowOrEqual, DestinationLabel = xNoJump };
break;
case ConditionalTestEnum.BelowOrEqual:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
break;
case ConditionalTestEnum.Below:
new CPU.Compare { DestinationReg = CPU.Registers.EDX, SourceReg = CPU.Registers.EBX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Above, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.Below, DestinationLabel = xNoJump };
new CPU.Compare { DestinationReg = CPU.Registers.ECX, SourceReg = CPU.Registers.EAX };
new CPU.ConditionalJump { Condition = CPU.ConditionalTestEnum.AboveOrEqual, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
break;
default:
throw new Exception("Unknown OpCode for conditional branch in 64-bit.");
}
new Label(xNoJump);
//}
}
}
else
{
//if (xStackContent.IsFloat)
//{
// throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Simple comparison of floating point numbers is not yet supported!");
//}
//else
//{
// todo: improve code clarity
if (xStackContentSize > 4)
{
throw new Exception("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Simple branches are not yet supported on operands > 4 bytes!");
}
new CPU.Pop { DestinationReg = CPU.Registers.EAX };
if (xTestOp == ConditionalTestEnum.Zero)
{
new CPU.Compare { DestinationReg = CPU.Registers.EAX, SourceValue = 0 };
new CPU.ConditionalJump { Condition = ConditionalTestEnum.Equal, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
}
else if (xTestOp == ConditionalTestEnum.NotZero)
{
new CPU.Compare { DestinationReg = CPU.Registers.EAX, SourceValue = 0 };
new CPU.ConditionalJump { Condition = ConditionalTestEnum.NotEqual, DestinationLabel = AppAssembler.TmpBranchLabel(aMethod, aOpCode) };
}
else
{
throw new NotSupportedException("Cosmos.IL2CPU.x86->IL->Branch.cs->Error: Situation not supported yet! (In the Simple Comparison)");
}
}
//}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.IO.MemoryMappedFiles;
using Xunit;
[Collection("CreateFromFile")]
public class CreateFromFile : MMFTestBase
{
[Fact]
public static void CreateFromFileTestCases()
{
bool bResult = false;
CreateFromFile test = new CreateFromFile();
try
{
bResult = test.RunTest();
}
catch (Exception exc_main)
{
bResult = false;
Console.WriteLine("FAiL! Error in CreateFromFile! Uncaught Exception in main(), exc_main==" + exc_main.ToString());
}
Assert.True(bResult, "One or more test cases failed.");
}
public bool RunTest()
{
try
{
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
if (File.Exists("CreateFromFile_test2.txt"))
File.Delete("CreateFromFile_test2.txt");
String fileText = "Non-empty file for MMF testing.";
File.WriteAllText("CreateFromFile_test2.txt", fileText);
////////////////////////////////////////////////////////////////////////
// CreateFromFile(String)
////////////////////////////////////////////////////////////////////////
// [] fileName
// null fileName
VerifyCreateFromFileException<ArgumentNullException>("Loc001", null);
// existing file
VerifyCreateFromFile("Loc002", "CreateFromFile_test2.txt");
// nonexistent file
if (File.Exists("nonexistent.txt"))
File.Delete("nonexistent.txt");
VerifyCreateFromFileException<FileNotFoundException>("Loc003", "nonexistent.txt");
// FS open
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
VerifyCreateFromFileException<IOException>("Loc004a", "CreateFromFile_test2.txt");
}
// same file - not allowed
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("CreateFromFile_test2.txt"))
{
VerifyCreateFromFileException<IOException>("Loc004b", "CreateFromFile_test2.txt");
}
////////////////////////////////////////////////////////////////////////
// CreateFromFile(String, FileMode)
////////////////////////////////////////////////////////////////////////
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
if (File.Exists("CreateFromFile_test2.txt"))
File.Delete("CreateFromFile_test2.txt");
File.WriteAllText("CreateFromFile_test2.txt", fileText);
// [] fileName
// null fileName
VerifyCreateFromFileException<ArgumentNullException>("Loc101", null, FileMode.Open);
// existing file - open
VerifyCreateFromFile("Loc102a", "CreateFromFile_test2.txt", FileMode.Open);
VerifyCreateFromFile("Loc102b", "CreateFromFile_test2.txt", FileMode.OpenOrCreate);
// existing file - create
// can't create new since it exists
VerifyCreateFromFileException<IOException>("Loc102d", "CreateFromFile_test2.txt", FileMode.CreateNew);
// newly created file - exception with default capacity
VerifyCreateFromFileException<ArgumentException>("Loc102c", "CreateFromFile_test2.txt", FileMode.Create);
VerifyCreateFromFileException<ArgumentException>("Loc102f", "CreateFromFile_test2.txt", FileMode.Truncate);
// append not allowed
VerifyCreateFromFileException<ArgumentException>("Loc102e", "CreateFromFile_test2.txt", FileMode.Append);
// nonexistent file - error
if (File.Exists("nonexistent.txt"))
File.Delete("nonexistent.txt");
VerifyCreateFromFileException<FileNotFoundException>("Loc103a", "nonexistent.txt", FileMode.Open);
// newly created file - exception with default capacity
VerifyCreateFromFileException<ArgumentException>("Loc103b", "CreateFromFile_test1.txt", FileMode.OpenOrCreate);
VerifyCreateFromFileException<ArgumentException>("Loc103c", "CreateFromFile_test1.txt", FileMode.CreateNew);
VerifyCreateFromFileException<ArgumentException>("Loc103d", "CreateFromFile_test1.txt", FileMode.Create);
VerifyCreateFromFileException<ArgumentException>("Loc103e", "CreateFromFile_test2.txt", FileMode.Truncate);
// append not allowed
VerifyCreateFromFileException<ArgumentException>("Loc103f", "CreateFromFile_test2.txt", FileMode.Append);
// empty file - exception with default capacity
using (FileStream fs = new FileStream("CreateFromFile_test1.txt", FileMode.Create))
{
}
VerifyCreateFromFileException<ArgumentException>("Loc104a", "CreateFromFile_test1.txt", FileMode.Open);
VerifyCreateFromFileException<ArgumentException>("Loc104b", "CreateFromFile_test1.txt", FileMode.OpenOrCreate);
VerifyCreateFromFileException<ArgumentException>("Loc104c", "CreateFromFile_test1.txt", FileMode.Create);
VerifyCreateFromFileException<ArgumentException>("Loc104d", "CreateFromFile_test1.txt", FileMode.Truncate);
// can't create new since it exists
VerifyCreateFromFileException<IOException>("Loc104e", "CreateFromFile_test1.txt", FileMode.CreateNew);
// append not allowed
VerifyCreateFromFileException<ArgumentException>("Loc104f", "CreateFromFile_test1.txt", FileMode.Append);
// FS open
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
VerifyCreateFromFileException<IOException>("Loc105a", "CreateFromFile_test2.txt", FileMode.Open);
}
// same file - not allowed
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("CreateFromFile_test2.txt"))
{
VerifyCreateFromFileException<IOException>("Loc105b", "CreateFromFile_test2.txt", FileMode.Open);
}
////////////////////////////////////////////////////////////////////////
// CreateFromFile(String, FileMode, String)
////////////////////////////////////////////////////////////////////////
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
if (File.Exists("CreateFromFile_test2.txt"))
File.Delete("CreateFromFile_test2.txt");
File.WriteAllText("CreateFromFile_test2.txt", fileText);
File.WriteAllText("test3.txt", fileText + fileText);
// [] fileName
// null fileName
VerifyCreateFromFileException<ArgumentNullException>("Loc201", null, FileMode.Open);
// existing file - open
VerifyCreateFromFile("Loc202a", "CreateFromFile_test2.txt", FileMode.Open);
VerifyCreateFromFile("Loc202b", "CreateFromFile_test2.txt", FileMode.OpenOrCreate);
// existing file - create
// can't create new since it exists
VerifyCreateFromFileException<IOException>("Loc202d", "CreateFromFile_test2.txt", FileMode.CreateNew);
// newly created file - exception with default capacity
VerifyCreateFromFileException<ArgumentException>("Loc202c", "CreateFromFile_test2.txt", FileMode.Create);
VerifyCreateFromFileException<ArgumentException>("Loc202f", "CreateFromFile_test2.txt", FileMode.Truncate);
// append not allowed
VerifyCreateFromFileException<ArgumentException>("Loc202e", "CreateFromFile_test2.txt", FileMode.Append);
// nonexistent file - error
if (File.Exists("nonexistent.txt"))
File.Delete("nonexistent.txt");
VerifyCreateFromFileException<FileNotFoundException>("Loc203a", "nonexistent.txt", FileMode.Open);
// newly created file - exception with default capacity
VerifyCreateFromFileException<ArgumentException>("Loc203b", "CreateFromFile_test1.txt", FileMode.OpenOrCreate);
VerifyCreateFromFileException<ArgumentException>("Loc203c", "CreateFromFile_test1.txt", FileMode.CreateNew);
VerifyCreateFromFileException<ArgumentException>("Loc203d", "CreateFromFile_test1.txt", FileMode.Create);
VerifyCreateFromFileException<ArgumentException>("Loc203e", "CreateFromFile_test2.txt", FileMode.Truncate);
// append not allowed
VerifyCreateFromFileException<ArgumentException>("Loc203f", "CreateFromFile_test2.txt", FileMode.Append);
// empty file - exception with default capacity
using (FileStream fs = new FileStream("CreateFromFile_test1.txt", FileMode.Create))
{
}
VerifyCreateFromFileException<ArgumentException>("Loc204a", "CreateFromFile_test1.txt", FileMode.Open);
VerifyCreateFromFileException<ArgumentException>("Loc204b", "CreateFromFile_test1.txt", FileMode.OpenOrCreate);
VerifyCreateFromFileException<ArgumentException>("Loc204c", "CreateFromFile_test1.txt", FileMode.Create);
VerifyCreateFromFileException<ArgumentException>("Loc204d", "CreateFromFile_test1.txt", FileMode.Truncate);
// can't create new since it exists
VerifyCreateFromFileException<IOException>("Loc204e", "CreateFromFile_test1.txt", FileMode.CreateNew);
// append not allowed
VerifyCreateFromFileException<ArgumentException>("Loc204f", "CreateFromFile_test1.txt", FileMode.Append);
// FS open
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
VerifyCreateFromFileException<IOException>("Loc205a", "CreateFromFile_test2.txt", FileMode.Open);
}
// same file - not allowed
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("CreateFromFile_test2.txt"))
{
VerifyCreateFromFileException<IOException>("Loc205b", "CreateFromFile_test2.txt", FileMode.Open);
}
// [] mapName
// mapname > 260 chars
VerifyCreateFromFile("Loc211", "CreateFromFile_test2.txt", FileMode.Open, "CreateFromFile2" + new String('a', 1000));
// null
VerifyCreateFromFile("Loc212", "CreateFromFile_test2.txt", FileMode.Open, null);
// empty string disallowed
VerifyCreateFromFileException<ArgumentException>("Loc213", "CreateFromFile_test2.txt", FileMode.Open, String.Empty);
// all whitespace
VerifyCreateFromFile("Loc214", "CreateFromFile_test2.txt", FileMode.Open, "\t \n\u00A0");
// MMF with this mapname already exists
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("test3.txt", FileMode.Open, "map215"))
{
VerifyCreateFromFileException<IOException>("Loc215", "CreateFromFile_test2.txt", FileMode.Open, "map215");
}
// MMF with this mapname existed, but was closed
VerifyCreateFromFile("Loc216", "CreateFromFile_test2.txt", FileMode.Open, "map215");
// "global/" prefix
VerifyCreateFromFile("Loc217", "CreateFromFile_test2.txt", FileMode.Open, "global/CFF_0");
// "local/" prefix
VerifyCreateFromFile("Loc218", "CreateFromFile_test2.txt", FileMode.Open, "local/CFF_1");
////////////////////////////////////////////////////////////////////////
// CreateFromFile(String, FileMode, String, long)
////////////////////////////////////////////////////////////////////////
// [] fileName
// null fileName
VerifyCreateFromFileException<ArgumentNullException>("Loc301", null, FileMode.Open, "CFF_mapname", 0);
// [] capacity
// newly created file - exception with default capacity
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
VerifyCreateFromFileException<ArgumentException>("Loc311", "CreateFromFile_test1.txt", FileMode.CreateNew, "CFF_mapname211", 0);
// newly created file - valid with >0 capacity
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
VerifyCreateFromFile("Loc312", "CreateFromFile_test1.txt", FileMode.CreateNew, "CFF_mapname312", 1);
// existing file, default capacity
VerifyCreateFromFile("Loc313", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname313", 0);
// existing file, capacity less than file size
File.WriteAllText("CreateFromFile_test2.txt", fileText);
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc314", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname314", 6);
// existing file, capacity equal to file size
File.WriteAllText("CreateFromFile_test2.txt", fileText);
VerifyCreateFromFile("Loc315", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname315", fileText.Length);
// existing file, capacity greater than file size
File.WriteAllText("CreateFromFile_test2.txt", fileText);
VerifyCreateFromFile("Loc316", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname316", 6000);
// negative
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc317", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname317", -1);
// negative
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc318", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname318", -4096);
VerifyCreateFromFileException<IOException>("Loc319b", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname319", Int64.MaxValue); // valid but too large
////////////////////////////////////////////////////////////////////////
// CreateFromFile(String, FileMode, String, long, MemoryMappedFileAccess)
////////////////////////////////////////////////////////////////////////
// [] capacity
// existing file, capacity less than file size, MemoryMappedFileAccess.Read
File.WriteAllText("CreateFromFile_test2.txt", fileText);
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc414", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname414", 6, MemoryMappedFileAccess.Read);
// existing file, capacity equal to file size, MemoryMappedFileAccess.Read
File.WriteAllText("CreateFromFile_test2.txt", fileText);
VerifyCreateFromFile("Loc415", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname415", fileText.Length, MemoryMappedFileAccess.Read);
// existing file, capacity greater than file size, MemoryMappedFileAccess.Read
File.WriteAllText("CreateFromFile_test2.txt", fileText);
VerifyCreateFromFileException<ArgumentException>("Loc416", "CreateFromFile_test2.txt", FileMode.Open, "CFF_mapname416", 6000, MemoryMappedFileAccess.Read);
////////////////////////////////////////////////////////////////////////
// CreateFromFile(FileStream, String, long, MemoryMappedFileAccess,
// MemoryMappedFileSecurity, HandleInheritability, bool)
////////////////////////////////////////////////////////////////////////
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
File.WriteAllText("CreateFromFile_test2.txt", fileText);
File.WriteAllText("test3.txt", fileText + fileText);
// [] fileStream
// null filestream
VerifyCreateFromFileException<ArgumentNullException>("Loc401", null, "map401", 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
// existing file
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc402", fs, "map402", 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// same FS
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fs, "map403a", 8192, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false))
{
VerifyCreateFromFile("Loc403", fs, "map403", 8192, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
}
// closed FS
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
fs.Dispose();
VerifyCreateFromFileException<ObjectDisposedException>("Loc404", fs, "map404", 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, false);
}
// newly created file - exception with default capacity
using (FileStream fs = new FileStream("CreateFromFile_test1.txt", FileMode.CreateNew))
{
VerifyCreateFromFileException<ArgumentException>("Loc405", fs, "map405", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// empty file - exception with default capacity
using (FileStream fs = new FileStream("CreateFromFile_test1.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentException>("Loc406", fs, "map406", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// [] mapName
// mapname > 260 chars
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc411", fs, "CreateFromFile" + new String('a', 1000), 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// null
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc412", fs, null, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// empty string disallowed
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentException>("Loc413", fs, String.Empty, 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// all whitespace
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc414", fs, "\t \n\u00A0", 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// MMF with this mapname already exists
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile("test3.txt", FileMode.Open, "map415"))
{
using (FileStream fs2 = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<IOException>("Loc415", fs2, "map415", 4096, MemoryMappedFileAccess.Read, HandleInheritability.None, false);
}
}
// MMF with this mapname existed, but was closed
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc416", fs, "map415", 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// "global/" prefix
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc417", fs, "global/CFF_2", 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// "local/" prefix
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc418", fs, "local/CFF_3", 4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// [] capacity
// newly created file - exception with default capacity
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
using (FileStream fs = new FileStream("CreateFromFile_test1.txt", FileMode.CreateNew))
{
VerifyCreateFromFileException<ArgumentException>("Loc421", fs, "CFF_mapname421", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// newly created file - valid with >0 capacity
if (File.Exists("CreateFromFile_test1.txt"))
File.Delete("CreateFromFile_test1.txt");
using (FileStream fs = new FileStream("CreateFromFile_test1.txt", FileMode.CreateNew))
{
VerifyCreateFromFile("Loc422", fs, "CFF_mapname422", 1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// existing file, default capacity
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc423", fs, "CFF_mapname423", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// existing file, capacity less than file size
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc424", fs, "CFF_mapname424", 6, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// existing file, capacity equal to file size
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc425", fs, "CFF_mapname425", fileText.Length, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// existing file, capacity greater than file size
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc426", fs, "CFF_mapname426", 6000, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// existing file, capacity greater than file size & access = Read only
File.WriteAllText("CreateFromFile_test2.txt", fileText);
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentException>("Loc426a", fs, "CFF_mapname426a", 6000, MemoryMappedFileAccess.Read, HandleInheritability.None, false);
}
// negative
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc427", fs, "CFF_mapname427", -1, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// negative
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc428", fs, "CFF_mapname428", -4096, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// Int64.MaxValue - cannot exceed local address space
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<IOException>("Loc429", fs, "CFF_mapname429", Int64.MaxValue, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false); // valid but too large
}
// [] access
// Write is disallowed
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.ReadWrite))
{
VerifyCreateFromFileException<ArgumentException>("Loc430", fs, "CFF_mapname430", 0, MemoryMappedFileAccess.Write, HandleInheritability.None, false);
}
// valid access (filestream is ReadWrite)
MemoryMappedFileAccess[] accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.CopyOnWrite,
};
foreach (MemoryMappedFileAccess access in accessList)
{
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.ReadWrite))
{
VerifyCreateFromFile("Loc431_" + access, fs, "CFF_mapname431_" + access, 0, access, HandleInheritability.None, false);
}
}
// invalid access (filestream is ReadWrite)
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.ReadWrite))
{
VerifyCreateFromFileException<UnauthorizedAccessException>("Loc432_" + access, fs, "CFF_mapname432_" + access, 0, access, HandleInheritability.None, false);
}
}
// valid access (filestream is Read only)
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.CopyOnWrite,
};
foreach (MemoryMappedFileAccess access in accessList)
{
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.Read))
{
VerifyCreateFromFile("Loc433_" + access, fs, "CFF_mapname433_" + access, 0, access, HandleInheritability.None, false);
}
}
// invalid access (filestream was Read only)
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.Read))
{
VerifyCreateFromFileException<UnauthorizedAccessException>("Loc434_" + access, fs, "CFF_mapname434_" + access, 0, access, HandleInheritability.None, false);
}
}
// invalid access (filestream is Write only)
accessList = new MemoryMappedFileAccess[] {
MemoryMappedFileAccess.Read,
MemoryMappedFileAccess.ReadWrite,
MemoryMappedFileAccess.CopyOnWrite,
MemoryMappedFileAccess.ReadExecute,
MemoryMappedFileAccess.ReadWriteExecute,
};
foreach (MemoryMappedFileAccess access in accessList)
{
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.Write))
{
VerifyCreateFromFileException<UnauthorizedAccessException>("Loc435_" + access, fs, "CFF_mapname435_" + access, 0, access, HandleInheritability.None, false);
}
}
// invalid enum value
accessList = new MemoryMappedFileAccess[] {
(MemoryMappedFileAccess)(-1),
(MemoryMappedFileAccess)(6),
};
foreach (MemoryMappedFileAccess access in accessList)
{
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open, FileAccess.ReadWrite))
{
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc436_" + ((int)access), fs, "CFF_mapname436_" + ((int)access), 0, access, HandleInheritability.None, false);
}
}
// [] inheritability
// None
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc461", fs, "CFF_mapname461", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// Inheritable
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc462", fs, "CFF_mapname462", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.Inheritable, false);
}
// invalid
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc463", fs, "CFF_mapname463", 0, MemoryMappedFileAccess.ReadWrite, (HandleInheritability)(-1), false);
}
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFileException<ArgumentOutOfRangeException>("Loc464", fs, "CFF_mapname464", 0, MemoryMappedFileAccess.ReadWrite, (HandleInheritability)(2), false);
}
// [] leaveOpen
// false
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc471", fs, "CFF_mapname471", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, false);
}
// true
using (FileStream fs = new FileStream("CreateFromFile_test2.txt", FileMode.Open))
{
VerifyCreateFromFile("Loc472", fs, "CFF_mapname472", 0, MemoryMappedFileAccess.ReadWrite, HandleInheritability.None, true);
}
/// END TEST CASES
if (iCountErrors == 0)
{
return true;
}
else
{
Console.WriteLine("Fail: iCountErrors==" + iCountErrors);
return false;
}
}
catch (Exception ex)
{
Console.WriteLine("ERR999: Unexpected exception in runTest, {0}", ex);
return false;
}
}
/// START HELPER FUNCTIONS
public void VerifyCreateFromFile(String strLoc, String fileName)
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName))
{
VerifyAccess(strLoc, mmf, MemoryMappedFileAccess.ReadWrite, 1);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFileException<EXCTYPE>(String strLoc, String fileName) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFile(String strLoc, String fileName, FileMode fileMode)
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode))
{
VerifyAccess(strLoc, mmf, MemoryMappedFileAccess.ReadWrite, 1);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFileException<EXCTYPE>(String strLoc, String fileName, FileMode fileMode) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFile(String strLoc, String fileName, FileMode fileMode, String mapName)
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode, mapName))
{
VerifyAccess(strLoc, mmf, MemoryMappedFileAccess.ReadWrite, 1);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFileException<EXCTYPE>(String strLoc, String fileName, FileMode fileMode, String mapName) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode, mapName))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFile(String strLoc, String fileName, FileMode fileMode, String mapName, long capacity)
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode, mapName, capacity))
{
VerifyAccess(strLoc, mmf, MemoryMappedFileAccess.ReadWrite, capacity);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFileException<EXCTYPE>(String strLoc, String fileName, FileMode fileMode, String mapName, long capacity) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode, mapName, capacity))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFile(String strLoc, String fileName, FileMode fileMode, String mapName, long capacity, MemoryMappedFileAccess access)
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode, mapName, capacity, access))
{
VerifyAccess(strLoc, mmf, access, capacity);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, HandleInheritability.None);
}
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFileException<EXCTYPE>(String strLoc, String fileName, FileMode fileMode, String mapName, long capacity, MemoryMappedFileAccess access) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileName, fileMode, mapName, capacity, access))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFile(String strLoc, FileStream fileStream, String mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen)
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileStream, mapName, capacity, access, inheritability, leaveOpen))
{
VerifyAccess(strLoc, mmf, access, capacity);
VerifyHandleInheritability(strLoc, mmf.SafeMemoryMappedFileHandle, inheritability);
}
VerifyLeaveOpen(strLoc, fileStream, leaveOpen);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
public void VerifyCreateFromFileException<EXCTYPE>(String strLoc, FileStream fileStream, String mapName, long capacity, MemoryMappedFileAccess access, HandleInheritability inheritability, bool leaveOpen) where EXCTYPE : Exception
{
iCountTestcases++;
try
{
using (MemoryMappedFile mmf = MemoryMappedFile.CreateFromFile(fileStream, mapName, capacity, access, inheritability, leaveOpen))
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: No exception thrown, expected {1}", strLoc, typeof(EXCTYPE));
}
}
catch (EXCTYPE)
{
//Console.WriteLine("{0}: Expected, {1}: {2}", strLoc, ex.GetType(), ex.Message);
}
catch (Exception ex)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: Unexpected exception, {1}", strLoc, ex);
}
}
void VerifyLeaveOpen(String strLoc, FileStream fs, bool expectedOpen)
{
if (fs.CanSeek != expectedOpen)
{
iCountErrors++;
Console.WriteLine("ERROR, {0}: MemoryMappedFile did not respect LeaveOpen. Expected FileStream open={1}, got open={2}", strLoc, expectedOpen, fs.CanSeek);
}
}
}
| |
using System;
using System.Security;
using System.Runtime.InteropServices;
namespace Nvidia.TextureTools
{
#region Enums
#region public enum Format
/// <summary>
/// Compression format.
/// </summary>
public enum Format
{
// No compression.
RGB,
RGBA = RGB,
// DX9 formats.
DXT1,
DXT1a,
DXT3,
DXT5,
DXT5n,
// DX10 formats.
BC1 = DXT1,
BC1a = DXT1a,
BC2 = DXT3,
BC3 = DXT5,
BC3n = DXT5n,
BC4,
BC5,
}
#endregion
#region public enum Quality
/// <summary>
/// Quality modes.
/// </summary>
public enum Quality
{
Fastest,
Normal,
Production,
Highest,
}
#endregion
#region public enum WrapMode
/// <summary>
/// Wrap modes.
/// </summary>
public enum WrapMode
{
Clamp,
Repeat,
Mirror,
}
#endregion
#region public enum TextureType
/// <summary>
/// Texture types.
/// </summary>
public enum TextureType
{
Texture2D,
TextureCube,
}
#endregion
#region public enum InputFormat
/// <summary>
/// Input formats.
/// </summary>
public enum InputFormat
{
BGRA_8UB
}
#endregion
#region public enum MipmapFilter
/// <summary>
/// Mipmap downsampling filters.
/// </summary>
public enum MipmapFilter
{
Box,
Triangle,
Kaiser
}
#endregion
#region public enum ColorTransform
/// <summary>
/// Color transformation.
/// </summary>
public enum ColorTransform
{
None,
Linear
}
#endregion
#region public enum RoundMode
/// <summary>
/// Extents rounding mode.
/// </summary>
public enum RoundMode
{
None,
ToNextPowerOfTwo,
ToNearestPowerOfTwo,
ToPreviousPowerOfTwo
}
#endregion
#region public enum AlphaMode
/// <summary>
/// Alpha mode.
/// </summary>
public enum AlphaMode
{
None,
Transparency,
Premultiplied
}
#endregion
#region public enum Error
/// <summary>
/// Error codes.
/// </summary>
public enum Error
{
InvalidInput,
UserInterruption,
UnsupportedFeature,
CudaError,
Unknown,
FileOpen,
FileWrite,
}
#endregion
#endregion
#region public class InputOptions
/// <summary>
/// Input options.
/// </summary>
public class InputOptions
{
#region Bindings
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static IntPtr nvttCreateInputOptions();
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttDestroyInputOptions(IntPtr inputOptions);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsTextureLayout(IntPtr inputOptions, TextureType type, int w, int h, int d);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttResetInputOptionsTextureLayout(IntPtr inputOptions);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static bool nvttSetInputOptionsMipmapData(IntPtr inputOptions, IntPtr data, int w, int h, int d, int face, int mipmap);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsFormat(IntPtr inputOptions, InputFormat format);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsAlphaMode(IntPtr inputOptions, AlphaMode alphaMode);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsGamma(IntPtr inputOptions, float inputGamma, float outputGamma);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsWrapMode(IntPtr inputOptions, WrapMode mode);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsMipmapFilter(IntPtr inputOptions, MipmapFilter filter);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsMipmapGeneration(IntPtr inputOptions, bool generateMipmaps, int maxLevel);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsKaiserParameters(IntPtr inputOptions, float width, float alpha, float stretch);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsNormalMap(IntPtr inputOptions, bool b);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsConvertToNormalMap(IntPtr inputOptions, bool convert);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsHeightEvaluation(IntPtr inputOptions, float redScale, float greenScale, float blueScale, float alphaScale);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsNormalFilter(IntPtr inputOptions, float small, float medium, float big, float large);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsNormalizeMipmaps(IntPtr inputOptions, bool b);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsColorTransform(IntPtr inputOptions, ColorTransform t);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsLinearTransfrom(IntPtr inputOptions, int channel, float w0, float w1, float w2, float w3);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsMaxExtents(IntPtr inputOptions, int d);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetInputOptionsRoundMode(IntPtr inputOptions, RoundMode mode);
#endregion
internal IntPtr options;
public InputOptions()
{
options = nvttCreateInputOptions();
}
~InputOptions()
{
nvttDestroyInputOptions(options);
}
public void SetTextureLayout(TextureType type, int w, int h, int d)
{
nvttSetInputOptionsTextureLayout(options, type, w, h, d);
}
public void ResetTextureLayout()
{
nvttResetInputOptionsTextureLayout(options);
}
public void SetMipmapData(IntPtr data, int width, int height, int depth, int face, int mipmap)
{
nvttSetInputOptionsMipmapData(options, data, width, height, depth, face, mipmap);
}
public void SetFormat(InputFormat format)
{
nvttSetInputOptionsFormat(options, format);
}
public void SetAlphaMode(AlphaMode alphaMode)
{
nvttSetInputOptionsAlphaMode(options, alphaMode);
}
public void SetGamma(float inputGamma, float outputGamma)
{
nvttSetInputOptionsGamma(options, inputGamma, outputGamma);
}
public void SetWrapMode(WrapMode wrapMode)
{
nvttSetInputOptionsWrapMode(options, wrapMode);
}
public void SetMipmapFilter(MipmapFilter filter)
{
nvttSetInputOptionsMipmapFilter(options, filter);
}
public void SetMipmapGeneration(bool enabled)
{
nvttSetInputOptionsMipmapGeneration(options, enabled, -1);
}
public void SetMipmapGeneration(bool enabled, int maxLevel)
{
nvttSetInputOptionsMipmapGeneration(options, enabled, maxLevel);
}
public void SetKaiserParameters(float width, float alpha, float stretch)
{
nvttSetInputOptionsKaiserParameters(options, width, alpha, stretch);
}
public void SetNormalMap(bool b)
{
nvttSetInputOptionsNormalMap(options, b);
}
public void SetConvertToNormalMap(bool convert)
{
nvttSetInputOptionsConvertToNormalMap(options, convert);
}
public void SetHeightEvaluation(float redScale, float greenScale, float blueScale, float alphaScale)
{
nvttSetInputOptionsHeightEvaluation(options, redScale, greenScale, blueScale, alphaScale);
}
public void SetNormalFilter(float small, float medium, float big, float large)
{
nvttSetInputOptionsNormalFilter(options, small, medium, big, large);
}
public void SetNormalizeMipmaps(bool b)
{
nvttSetInputOptionsNormalizeMipmaps(options, b);
}
public void SetColorTransform(ColorTransform t)
{
nvttSetInputOptionsColorTransform(options, t);
}
public void SetLinearTransfrom(int channel, float w0, float w1, float w2, float w3)
{
nvttSetInputOptionsLinearTransfrom(options, channel, w0, w1, w2, w3);
}
public void SetMaxExtents(int dim)
{
nvttSetInputOptionsMaxExtents(options, dim);
}
public void SetRoundMode(RoundMode mode)
{
nvttSetInputOptionsRoundMode(options, mode);
}
}
#endregion
#region public class CompressionOptions
/// <summary>
/// Compression options.
/// </summary>
public class CompressionOptions
{
#region Bindings
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static IntPtr nvttCreateCompressionOptions();
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttDestroyCompressionOptions(IntPtr compressionOptions);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetCompressionOptionsFormat(IntPtr compressionOptions, Format format);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetCompressionOptionsQuality(IntPtr compressionOptions, Quality quality);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetCompressionOptionsColorWeights(IntPtr compressionOptions, float red, float green, float blue, float alpha);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetCompressionOptionsPixelFormat(IntPtr compressionOptions, uint bitcount, uint rmask, uint gmask, uint bmask, uint amask);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetCompressionOptionsQuantization(IntPtr compressionOptions, bool colorDithering, bool alphaDithering, bool binaryAlpha, int alphaThreshold);
#endregion
internal IntPtr options;
public CompressionOptions()
{
options = nvttCreateCompressionOptions();
}
~CompressionOptions()
{
nvttDestroyCompressionOptions(options);
}
public void SetFormat(Format format)
{
nvttSetCompressionOptionsFormat(options, format);
}
public void SetQuality(Quality quality)
{
nvttSetCompressionOptionsQuality(options, quality);
}
public void SetColorWeights(float red, float green, float blue)
{
nvttSetCompressionOptionsColorWeights(options, red, green, blue, 1.0f);
}
public void SetColorWeights(float red, float green, float blue, float alpha)
{
nvttSetCompressionOptionsColorWeights(options, red, green, blue, alpha);
}
public void SetPixelFormat(uint bitcount, uint rmask, uint gmask, uint bmask, uint amask)
{
nvttSetCompressionOptionsPixelFormat(options, bitcount, rmask, gmask, bmask, amask);
}
public void SetQuantization(bool colorDithering, bool alphaDithering, bool binaryAlpha)
{
nvttSetCompressionOptionsQuantization(options, colorDithering, alphaDithering, binaryAlpha, 127);
}
public void SetQuantization(bool colorDithering, bool alphaDithering, bool binaryAlpha, int alphaThreshold)
{
nvttSetCompressionOptionsQuantization(options, colorDithering, alphaDithering, binaryAlpha, alphaThreshold);
}
}
#endregion
#region public class OutputOptions
/// <summary>
/// Output options.
/// </summary>
public class OutputOptions
{
#region Delegates
public delegate void ErrorHandler(Error error);
private delegate void WriteDataDelegate(IntPtr data, int size);
private delegate void ImageDelegate(int size, int width, int height, int depth, int face, int miplevel);
#endregion
#region Bindings
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static IntPtr nvttCreateOutputOptions();
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttDestroyOutputOptions(IntPtr outputOptions);
[DllImport("nvtt", CharSet = CharSet.Ansi), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetOutputOptionsFileName(IntPtr outputOptions, string fileName);
//[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
//private extern static void nvttSetOutputOptionsErrorHandler(IntPtr outputOptions, ErrorHandler errorHandler);
private void ErrorCallback(Error error)
{
if (Error != null) Error(error);
}
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttSetOutputOptionsOutputHeader(IntPtr outputOptions, bool b);
//[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
//private extern static void nvttSetOutputOptionsOutputHandler(IntPtr outputOptions, WriteDataDelegate writeData, ImageDelegate image);
#endregion
internal IntPtr options;
public OutputOptions()
{
options = nvttCreateOutputOptions();
//nvttSetOutputOptionsErrorHandler(options, new ErrorHandler(ErrorCallback));
}
~OutputOptions()
{
nvttDestroyOutputOptions(options);
}
public void SetFileName(string fileName)
{
nvttSetOutputOptionsFileName(options, fileName);
}
public event ErrorHandler Error;
public void SetOutputHeader(bool b)
{
nvttSetOutputOptionsOutputHeader(options, b);
}
// @@ Add OutputHandler interface.
}
#endregion
#region public static class Compressor
public class Compressor
{
#region Bindings
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static IntPtr nvttCreateCompressor();
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static void nvttDestroyCompressor(IntPtr compressor);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static bool nvttCompress(IntPtr compressor, IntPtr inputOptions, IntPtr compressionOptions, IntPtr outputOptions);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private extern static int nvttEstimateSize(IntPtr compressor, IntPtr inputOptions, IntPtr compressionOptions);
[DllImport("nvtt"), SuppressUnmanagedCodeSecurity]
private static extern IntPtr nvttErrorString(Error error);
#endregion
internal IntPtr compressor;
public Compressor()
{
compressor = nvttCreateCompressor();
}
~Compressor()
{
nvttDestroyCompressor(compressor);
}
public bool Compress(InputOptions input, CompressionOptions compression, OutputOptions output)
{
return nvttCompress(compressor, input.options, compression.options, output.options);
}
public int EstimateSize(InputOptions input, CompressionOptions compression)
{
return nvttEstimateSize(compressor, input.options, compression.options);
}
public static string ErrorString(Error error)
{
return Marshal.PtrToStringAnsi(nvttErrorString(error));
}
}
#endregion
} // Nvidia.TextureTools namespace
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Reflection;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.Versioning;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
using System.Threading;
#if FEATURE_HOST_ASSEMBLY_RESOLVER
namespace System.Runtime.Loader
{
[System.Security.SecuritySafeCritical]
public abstract class AssemblyLoadContext
{
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool OverrideDefaultAssemblyLoadContextForCurrentDomain(IntPtr ptrNativeAssemblyLoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern bool CanUseAppPathAssemblyLoadContextInCurrentDomain();
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InitializeAssemblyLoadContext(IntPtr ptrAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromAssemblyName(IntPtr ptrNativeAssemblyLoadContext, bool fRepresentsTPALoadContext);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr LoadFromStream(IntPtr ptrNativeAssemblyLoadContext, IntPtr ptrAssemblyArray, int iAssemblyArrayLen, IntPtr ptrSymbols, int iSymbolArrayLen, ObjectHandleOnStack retAssembly);
#if FEATURE_MULTICOREJIT
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalSetProfileRoot(string directoryPath);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
internal static extern void InternalStartProfile(string profile, IntPtr ptrNativeAssemblyLoadContext);
#endif // FEATURE_MULTICOREJIT
protected AssemblyLoadContext()
{
// Initialize the ALC representing non-TPA LoadContext
InitializeLoadContext(false);
}
internal AssemblyLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the ALC representing TPA LoadContext
InitializeLoadContext(fRepresentsTPALoadContext);
}
[System.Security.SecuritySafeCritical]
void InitializeLoadContext(bool fRepresentsTPALoadContext)
{
// Initialize the VM side of AssemblyLoadContext if not already done.
GCHandle gchALC = GCHandle.Alloc(this);
IntPtr ptrALC = GCHandle.ToIntPtr(gchALC);
m_pNativeAssemblyLoadContext = InitializeAssemblyLoadContext(ptrALC, fRepresentsTPALoadContext);
// Initialize event handlers to be null by default
Resolving = null;
Unloading = null;
// Since unloading an AssemblyLoadContext is not yet implemented, this is a temporary solution to raise the
// Unloading event on process exit. Register for the current AppDomain's ProcessExit event, and the handler will in
// turn raise the Unloading event.
AppDomain.CurrentDomain.ProcessExit += OnProcessExit;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void LoadFromPath(IntPtr ptrNativeAssemblyLoadContext, string ilPath, string niPath, ObjectHandleOnStack retAssembly);
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetLoadedAssembliesInternal(ObjectHandleOnStack assemblies);
public static Assembly[] GetLoadedAssemblies()
{
Assembly[] assemblies = null;
GetLoadedAssembliesInternal(JitHelpers.GetObjectHandleOnStack(ref assemblies));
return assemblies;
}
// These are helpers that can be used by AssemblyLoadContext derivations.
// They are used to load assemblies in DefaultContext.
public Assembly LoadFromAssemblyPath(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
if (Path.IsRelative(assemblyPath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
}
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, null, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromNativeImagePath(string nativeImagePath, string assemblyPath)
{
if (nativeImagePath == null)
{
throw new ArgumentNullException(nameof(nativeImagePath));
}
if (Path.IsRelative(nativeImagePath))
{
throw new ArgumentException( Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(nativeImagePath));
}
if (assemblyPath != null && Path.IsRelative(assemblyPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(assemblyPath));
}
// Basic validation has succeeded - lets try to load the NI image.
// Ask LoadFile to load the specified assembly in the DefaultContext
RuntimeAssembly loadedAssembly = null;
LoadFromPath(m_pNativeAssemblyLoadContext, assemblyPath, nativeImagePath, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
return loadedAssembly;
}
public Assembly LoadFromStream(Stream assembly)
{
return LoadFromStream(assembly, null);
}
public Assembly LoadFromStream(Stream assembly, Stream assemblySymbols)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
int iAssemblyStreamLength = (int)assembly.Length;
int iSymbolLength = 0;
// Allocate the byte[] to hold the assembly
byte[] arrAssembly = new byte[iAssemblyStreamLength];
// Copy the assembly to the byte array
assembly.Read(arrAssembly, 0, iAssemblyStreamLength);
// Get the symbol stream in byte[] if provided
byte[] arrSymbols = null;
if (assemblySymbols != null)
{
iSymbolLength = (int)assemblySymbols.Length;
arrSymbols = new byte[iSymbolLength];
assemblySymbols.Read(arrSymbols, 0, iSymbolLength);
}
RuntimeAssembly loadedAssembly = null;
unsafe
{
fixed(byte *ptrAssembly = arrAssembly, ptrSymbols = arrSymbols)
{
LoadFromStream(m_pNativeAssemblyLoadContext, new IntPtr(ptrAssembly), iAssemblyStreamLength, new IntPtr(ptrSymbols), iSymbolLength, JitHelpers.GetObjectHandleOnStack(ref loadedAssembly));
}
}
return loadedAssembly;
}
// Custom AssemblyLoadContext implementations can override this
// method to perform custom processing and use one of the protected
// helpers above to load the assembly.
protected abstract Assembly Load(AssemblyName assemblyName);
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static Assembly Resolve(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.ResolveUsingLoad(assemblyName);
}
// This method is invoked by the VM to resolve an assembly reference using the Resolving event
// after trying assembly resolution via Load override and TPA load context without success.
private static Assembly ResolveUsingResolvingEvent(IntPtr gchManagedAssemblyLoadContext, AssemblyName assemblyName)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
// Invoke the AssemblyResolve event callbacks if wired up
return context.ResolveUsingEvent(assemblyName);
}
private Assembly GetFirstResolvedAssembly(AssemblyName assemblyName)
{
Assembly resolvedAssembly = null;
Func<AssemblyLoadContext, AssemblyName, Assembly> assemblyResolveHandler = Resolving;
if (assemblyResolveHandler != null)
{
// Loop through the event subscribers and return the first non-null Assembly instance
Delegate [] arrSubscribers = assemblyResolveHandler.GetInvocationList();
for(int i = 0; i < arrSubscribers.Length; i++)
{
resolvedAssembly = ((Func<AssemblyLoadContext, AssemblyName, Assembly>)arrSubscribers[i])(this, assemblyName);
if (resolvedAssembly != null)
{
break;
}
}
}
return resolvedAssembly;
}
private Assembly ValidateAssemblyNameWithSimpleName(Assembly assembly, string requestedSimpleName)
{
// Get the name of the loaded assembly
string loadedSimpleName = null;
// Derived type's Load implementation is expected to use one of the LoadFrom* methods to get the assembly
// which is a RuntimeAssembly instance. However, since Assembly type can be used build any other artifact (e.g. AssemblyBuilder),
// we need to check for RuntimeAssembly.
RuntimeAssembly rtLoadedAssembly = assembly as RuntimeAssembly;
if (rtLoadedAssembly != null)
{
loadedSimpleName = rtLoadedAssembly.GetSimpleName();
}
// The simple names should match at the very least
if (String.IsNullOrEmpty(loadedSimpleName) || (!requestedSimpleName.Equals(loadedSimpleName, StringComparison.InvariantCultureIgnoreCase)))
throw new InvalidOperationException(Environment.GetResourceString("Argument_CustomAssemblyLoadContextRequestedNameMismatch"));
return assembly;
}
private Assembly ResolveUsingLoad(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
Assembly assembly = Load(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
return assembly;
}
private Assembly ResolveUsingEvent(AssemblyName assemblyName)
{
string simpleName = assemblyName.Name;
// Invoke the AssemblyResolve event callbacks if wired up
Assembly assembly = GetFirstResolvedAssembly(assemblyName);
if (assembly != null)
{
assembly = ValidateAssemblyNameWithSimpleName(assembly, simpleName);
}
// Since attempt to resolve the assembly via Resolving event is the last option,
// throw an exception if we do not find any assembly.
if (assembly == null)
{
throw new FileNotFoundException(Environment.GetResourceString("IO.FileLoad"), simpleName);
}
return assembly;
}
public Assembly LoadFromAssemblyName(AssemblyName assemblyName)
{
// Attempt to load the assembly, using the same ordering as static load, in the current load context.
Assembly loadedAssembly = Assembly.Load(assemblyName, m_pNativeAssemblyLoadContext);
return loadedAssembly;
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr InternalLoadUnmanagedDllFromPath(string unmanagedDllPath);
// This method provides a way for overriders of LoadUnmanagedDll() to load an unmanaged DLL from a specific path in a
// platform-independent way. The DLL is loaded with default load flags.
protected IntPtr LoadUnmanagedDllFromPath(string unmanagedDllPath)
{
if (unmanagedDllPath == null)
{
throw new ArgumentNullException(nameof(unmanagedDllPath));
}
if (unmanagedDllPath.Length == 0)
{
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"), nameof(unmanagedDllPath));
}
if (Path.IsRelative(unmanagedDllPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_AbsolutePathRequired"), nameof(unmanagedDllPath));
}
return InternalLoadUnmanagedDllFromPath(unmanagedDllPath);
}
// Custom AssemblyLoadContext implementations can override this
// method to perform the load of unmanaged native dll
// This function needs to return the HMODULE of the dll it loads
protected virtual IntPtr LoadUnmanagedDll(String unmanagedDllName)
{
//defer to default coreclr policy of loading unmanaged dll
return IntPtr.Zero;
}
// This method is invoked by the VM when using the host-provided assembly load context
// implementation.
private static IntPtr ResolveUnmanagedDll(String unmanagedDllName, IntPtr gchManagedAssemblyLoadContext)
{
AssemblyLoadContext context = (AssemblyLoadContext)(GCHandle.FromIntPtr(gchManagedAssemblyLoadContext).Target);
return context.LoadUnmanagedDll(unmanagedDllName);
}
public static AssemblyLoadContext Default
{
get
{
if (s_DefaultAssemblyLoadContext == null)
{
// Try to initialize the default assembly load context with apppath one if we are allowed to
if (AssemblyLoadContext.CanUseAppPathAssemblyLoadContextInCurrentDomain())
{
// Synchronize access to initializing Default ALC
lock(s_initLock)
{
if (s_DefaultAssemblyLoadContext == null)
{
s_DefaultAssemblyLoadContext = new AppPathAssemblyLoadContext();
}
}
}
}
return s_DefaultAssemblyLoadContext;
}
}
// This will be used to set the AssemblyLoadContext for DefaultContext, for the AppDomain,
// by a host. Once set, the runtime will invoke the LoadFromAssemblyName method against it to perform
// assembly loads for the DefaultContext.
//
// This method will throw if the Default AssemblyLoadContext is already set or the Binding model is already locked.
public static void InitializeDefaultContext(AssemblyLoadContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
// Try to override the default assembly load context
if (!AssemblyLoadContext.OverrideDefaultAssemblyLoadContextForCurrentDomain(context.m_pNativeAssemblyLoadContext))
{
throw new InvalidOperationException(Environment.GetResourceString("AppDomain_BindingModelIsLocked"));
}
// Update the managed side as well.
s_DefaultAssemblyLoadContext = context;
}
// This call opens and closes the file, but does not add the
// assembly to the domain.
[MethodImplAttribute(MethodImplOptions.InternalCall)]
static internal extern AssemblyName nGetFileInformation(String s);
// Helper to return AssemblyName corresponding to the path of an IL assembly
public static AssemblyName GetAssemblyName(string assemblyPath)
{
if (assemblyPath == null)
{
throw new ArgumentNullException(nameof(assemblyPath));
}
String fullPath = Path.GetFullPathInternal(assemblyPath);
return nGetFileInformation(fullPath);
}
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern IntPtr GetLoadContextForAssembly(RuntimeAssembly assembly);
// Returns the load context in which the specified assembly has been loaded
public static AssemblyLoadContext GetLoadContext(Assembly assembly)
{
if (assembly == null)
{
throw new ArgumentNullException(nameof(assembly));
}
AssemblyLoadContext loadContextForAssembly = null;
RuntimeAssembly rtAsm = assembly as RuntimeAssembly;
// We only support looking up load context for runtime assemblies.
if (rtAsm != null)
{
IntPtr ptrAssemblyLoadContext = GetLoadContextForAssembly(rtAsm);
if (ptrAssemblyLoadContext == IntPtr.Zero)
{
// If the load context is returned null, then the assembly was bound using the TPA binder
// and we shall return reference to the active "Default" binder - which could be the TPA binder
// or an overridden CLRPrivBinderAssemblyLoadContext instance.
loadContextForAssembly = AssemblyLoadContext.Default;
}
else
{
loadContextForAssembly = (AssemblyLoadContext)(GCHandle.FromIntPtr(ptrAssemblyLoadContext).Target);
}
}
return loadContextForAssembly;
}
// Set the root directory path for profile optimization.
public void SetProfileOptimizationRoot(string directoryPath)
{
#if FEATURE_MULTICOREJIT
InternalSetProfileRoot(directoryPath);
#endif // FEATURE_MULTICOREJIT
}
// Start profile optimization for the specified profile name.
public void StartProfileOptimization(string profile)
{
#if FEATURE_MULTICOREJIT
InternalStartProfile(profile, m_pNativeAssemblyLoadContext);
#endif // FEATURE_MULTICOREJI
}
private void OnProcessExit(object sender, EventArgs e)
{
var unloading = Unloading;
if (unloading != null)
{
unloading(this);
}
}
public event Func<AssemblyLoadContext, AssemblyName, Assembly> Resolving;
public event Action<AssemblyLoadContext> Unloading;
// Contains the reference to VM's representation of the AssemblyLoadContext
private IntPtr m_pNativeAssemblyLoadContext;
// Each AppDomain contains the reference to its AssemblyLoadContext instance, if one is
// specified by the host. By having the field as a static, we are
// making it an AppDomain-wide field.
private static volatile AssemblyLoadContext s_DefaultAssemblyLoadContext;
// Synchronization primitive for controlling initialization of Default load context
private static readonly object s_initLock = new Object();
// Occurs when an Assembly is loaded
public static event AssemblyLoadEventHandler AssemblyLoad
{
add { AppDomain.CurrentDomain.AssemblyLoad += value; }
remove { AppDomain.CurrentDomain.AssemblyLoad -= value; }
}
// Occurs when resolution of type fails
public static event ResolveEventHandler TypeResolve
{
add { AppDomain.CurrentDomain.TypeResolve += value; }
remove { AppDomain.CurrentDomain.TypeResolve -= value; }
}
// Occurs when resolution of resource fails
public static event ResolveEventHandler ResourceResolve
{
add { AppDomain.CurrentDomain.ResourceResolve += value; }
remove { AppDomain.CurrentDomain.ResourceResolve -= value; }
}
}
[System.Security.SecuritySafeCritical]
class AppPathAssemblyLoadContext : AssemblyLoadContext
{
internal AppPathAssemblyLoadContext() : base(true)
{
}
[System.Security.SecuritySafeCritical]
protected override Assembly Load(AssemblyName assemblyName)
{
// We were loading an assembly into TPA ALC that was not found on TPA list. As a result we are here.
// Returning null will result in the AssemblyResolve event subscribers to be invoked to help resolve the assembly.
return null;
}
}
[System.Security.SecuritySafeCritical]
internal class FileLoadAssemblyLoadContext : AssemblyLoadContext
{
internal FileLoadAssemblyLoadContext() : base(false)
{
}
[System.Security.SecuritySafeCritical]
protected override Assembly Load(AssemblyName assemblyName)
{
return null;
}
}
}
#endif // FEATURE_HOST_ASSEMBLY_RESOLVER
| |
//! \file ImageS25.cs
//! \date Sat Apr 18 17:00:54 2015
//! \brief ShiinaRio S25 multi-image format.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using GameRes.Utility;
namespace GameRes.Formats.ShiinaRio
{
internal class S25MetaData : ImageMetaData
{
public uint FirstOffset;
public bool Incremental;
}
[Export(typeof(ImageFormat))]
public class S25Format : ImageFormat
{
public override string Tag { get { return "S25"; } }
public override string Description { get { return "ShiinaRio image format"; } }
public override uint Signature { get { return 0x00353253; } } // 'S25'
// in current implementation, only the first frame is returned.
// per-frame access is provided by S25Opener class.
public override ImageMetaData ReadMetaData (Stream stream)
{
using (var input = new ArcView.Reader (stream))
{
input.ReadUInt32();
int count = input.ReadInt32();
if (count < 0 || count > 0xfffff)
return null;
uint first_offset = input.ReadUInt32();
if (0 == first_offset)
return null;
input.BaseStream.Position = first_offset;
var info = new S25MetaData();
info.Width = input.ReadUInt32();
info.Height = input.ReadUInt32();
info.OffsetX = input.ReadInt32();
info.OffsetY = input.ReadInt32();
info.FirstOffset = first_offset+0x14;
info.Incremental = 0 != (input.ReadUInt32() & 0x80000000u);
info.BPP = 32;
return info;
}
}
public override ImageData Read (Stream stream, ImageMetaData info)
{
var meta = info as S25MetaData;
if (null == meta)
throw new ArgumentException ("S25Format.Read should be supplied with S25MetaData", "info");
using (var reader = new Reader (stream, meta))
{
var pixels = reader.Unpack();
return ImageData.Create (info, PixelFormats.Bgra32, null, pixels);
}
}
public override void Write (Stream file, ImageData image)
{
throw new NotImplementedException ("S25Format.Write not implemented");
}
internal class Reader : IDisposable
{
BinaryReader m_input;
int m_width;
int m_height;
uint m_origin;
byte[] m_output;
bool m_incremental;
public byte[] Data { get { return m_output; } }
public Reader (Stream file, S25MetaData info)
{
m_width = (int)info.Width;
m_height = (int)info.Height;
m_output = new byte[m_width * m_height * 4];
m_input = new ArcView.Reader (file);
m_origin = info.FirstOffset;
m_incremental = info.Incremental;
}
public byte[] Unpack ()
{
m_input.BaseStream.Position = m_origin;
if (m_incremental)
return UnpackIncremental();
var rows = new uint[m_height];
for (int i = 0; i < rows.Length; ++i)
rows[i] = m_input.ReadUInt32();
var row_buffer = new byte[m_width];
int dst = 0;
for (int y = 0; y < m_height && dst < m_output.Length; ++y)
{
uint row_pos = rows[y];
m_input.BaseStream.Position = row_pos;
int row_length = m_input.ReadUInt16();
row_pos += 2;
if (0 != (row_pos & 1))
{
m_input.ReadByte();
--row_length;
}
if (row_buffer.Length < row_length)
row_buffer = new byte[row_length];
m_input.Read (row_buffer, 0, row_length);
dst = UnpackLine (row_buffer, dst);
}
return m_output;
}
void UpdateRepeatCount (Dictionary<uint, int> rows_count)
{
m_input.BaseStream.Position = 4;
int count = m_input.ReadInt32();
var frames = new List<uint> (count);
for (int i = 0; i < count; ++i)
{
var offset = m_input.ReadUInt32();
if (0 != offset)
frames.Add (offset);
}
foreach (var offset in frames)
{
if (offset+0x14 == m_origin)
continue;
m_input.BaseStream.Position = offset+4;
int height = m_input.ReadInt32();
m_input.BaseStream.Position = offset+0x14;
for (int i = 0; i < height; ++i)
{
var row_offset = m_input.ReadUInt32();
if (rows_count.ContainsKey (row_offset))
++rows_count[row_offset];
}
}
}
byte[] UnpackIncremental ()
{
var rows = new uint[m_height];
var rows_count = new Dictionary<uint, int> (m_height);
for (int i = 0; i < rows.Length; ++i)
{
uint offset = m_input.ReadUInt32();
rows[i] = offset;
if (rows_count.ContainsKey (offset))
++rows_count[offset];
else
rows_count[offset] = 1;
}
UpdateRepeatCount (rows_count);
var input_rows = new Dictionary<uint, byte[]> (m_height);
var input_lines = new byte[m_height][];
for (int y = 0; y < m_height; ++y)
{
uint row_pos = rows[y];
if (input_rows.ContainsKey (row_pos))
{
input_lines[y] = input_rows[row_pos];
continue;
}
var row = ReadLine (row_pos, rows_count[row_pos]);
input_rows[row_pos] = row;
input_lines[y] = row;
}
int dst = 0;
foreach (var line in input_lines)
{
dst = UnpackLine (line, dst);
}
return m_output;
}
int UnpackLine (byte[] line, int dst)
{
int row_pos = 0;
for (int x = m_width; x > 0 && dst < m_output.Length && row_pos < line.Length; )
{
if (0 != (row_pos & 1))
{
++row_pos;
}
int count = LittleEndian.ToUInt16 (line, row_pos);
row_pos += 2;
int method = count >> 13;
int skip = (count >> 11) & 3;
if (0 != skip)
{
row_pos += skip;
}
count &= 0x7ff;
if (0 == count)
{
count = LittleEndian.ToInt32 (line, row_pos);
row_pos += 4;
}
if (count > x) count = x;
x -= count;
byte b, g, r, a;
switch (method)
{
case 2:
for (int i = 0; i < count && row_pos < line.Length; ++i)
{
m_output[dst++] = line[row_pos++];
m_output[dst++] = line[row_pos++];
m_output[dst++] = line[row_pos++];
m_output[dst++] = 0xff;
}
break;
case 3:
b = line[row_pos++];
g = line[row_pos++];
r = line[row_pos++];
for (int i = 0; i < count; ++i)
{
m_output[dst++] = b;
m_output[dst++] = g;
m_output[dst++] = r;
m_output[dst++] = 0xff;
}
break;
case 4:
for (int i = 0; i < count && row_pos < line.Length; ++i)
{
a = line[row_pos++];
m_output[dst++] = line[row_pos++];
m_output[dst++] = line[row_pos++];
m_output[dst++] = line[row_pos++];
m_output[dst++] = a;
}
break;
case 5:
a = line[row_pos++];
b = line[row_pos++];
g = line[row_pos++];
r = line[row_pos++];
for (int i = 0; i < count; ++i)
{
m_output[dst++] = b;
m_output[dst++] = g;
m_output[dst++] = r;
m_output[dst++] = a;
}
break;
default:
dst += count * 4;
break;
}
}
return dst;
}
byte[] ReadLine (uint offset, int repeat)
{
m_input.BaseStream.Position = offset;
int row_length = m_input.ReadUInt16();
if (0 != (offset & 1))
{
m_input.ReadByte();
--row_length;
}
var row = new byte[row_length];
m_input.Read (row, 0, row.Length);
int row_pos = 0;
for (int x = m_width; x > 0; )
{
if (0 != (row_pos & 1))
{
++row_pos;
}
int count = LittleEndian.ToUInt16 (row, row_pos);
row_pos += 2;
int method = count >> 13;
int skip = (count >> 11) & 3;
if (0 != skip)
{
row_pos += skip;
}
count &= 0x7ff;
if (0 == count)
{
count = LittleEndian.ToInt32 (row, row_pos);
row_pos += 4;
}
if (count < 0 || count > x) count = x;
x -= count;
switch (method)
{
case 2:
for (int j = 0; j < repeat; ++j)
{
for (int i = 3; i < count*3 && row_pos+i < row.Length; ++i)
{
row[row_pos+i] += row[row_pos+i-3];
}
}
row_pos += count*3;
break;
case 3:
row_pos += 3;
break;
case 4:
for (int j = 0; j < repeat; ++j)
{
for (int i = 4; i < count*4 && row_pos+i < row.Length; ++i)
{
row[row_pos+i] += row[row_pos+i-4];
}
}
row_pos += count*4;
break;
case 5:
row_pos += 4;
break;
default:
break;
}
}
return row;
}
#region IDisposable Members
bool disposed = false;
public void Dispose ()
{
Dispose (true);
GC.SuppressFinalize (this);
}
protected virtual void Dispose (bool disposing)
{
if (!disposed)
{
if (disposing)
m_input.Dispose();
disposed = true;
}
}
#endregion
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Environment.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System
{
static public partial class Environment
{
#region Enums
public enum SpecialFolder
{
ApplicationData = 26,
CommonApplicationData = 35,
LocalApplicationData = 28,
Cookies = 33,
Desktop = 0,
Favorites = 6,
History = 34,
InternetCache = 32,
Programs = 2,
MyComputer = 17,
MyMusic = 13,
MyPictures = 39,
Recent = 8,
SendTo = 9,
StartMenu = 11,
Startup = 7,
System = 37,
Templates = 21,
DesktopDirectory = 16,
Personal = 5,
MyDocuments = 5,
ProgramFiles = 38,
CommonProgramFiles = 43,
AdminTools = 48,
CDBurning = 59,
CommonAdminTools = 47,
CommonDocuments = 46,
CommonMusic = 53,
CommonOemLinks = 58,
CommonPictures = 54,
CommonStartMenu = 22,
CommonPrograms = 23,
CommonStartup = 24,
CommonDesktopDirectory = 25,
CommonTemplates = 45,
CommonVideos = 55,
Fonts = 20,
MyVideos = 14,
NetworkShortcuts = 19,
PrinterShortcuts = 27,
UserProfile = 40,
CommonProgramFilesX86 = 44,
ProgramFilesX86 = 42,
Resources = 56,
LocalizedResources = 57,
SystemX86 = 41,
Windows = 36,
}
public enum SpecialFolderOption
{
None = 0,
Create = 32768,
DoNotVerify = 16384,
}
#endregion
#region Methods and constructors
public static void Exit(int exitCode)
{
}
public static string ExpandEnvironmentVariables(string name)
{
return default(string);
}
public static void FailFast(string message, Exception exception)
{
}
public static void FailFast(string message)
{
}
public static string[] GetCommandLineArgs()
{
return default(string[]);
}
public static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target)
{
return default(string);
}
public static string GetEnvironmentVariable(string variable)
{
return default(string);
}
public static System.Collections.IDictionary GetEnvironmentVariables()
{
Contract.Ensures(Contract.Result<System.Collections.IDictionary>() != null);
return default(System.Collections.IDictionary);
}
public static System.Collections.IDictionary GetEnvironmentVariables(EnvironmentVariableTarget target)
{
Contract.Ensures(Contract.Result<System.Collections.IDictionary>() != null);
return default(System.Collections.IDictionary);
}
public static string GetFolderPath(Environment.SpecialFolder folder, Environment.SpecialFolderOption option)
{
return default(string);
}
public static string GetFolderPath(Environment.SpecialFolder folder)
{
return default(string);
}
public static string[] GetLogicalDrives()
{
Contract.Ensures(Contract.Result<string[]>() != null);
return default(string[]);
}
public static void SetEnvironmentVariable(string variable, string value)
{
Contract.Ensures(0 <= variable.Length);
Contract.Ensures(variable.Length <= 32766);
}
public static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target)
{
Contract.Ensures(0 <= variable.Length);
Contract.Ensures(variable.Length <= 32766);
}
#endregion
#region Properties and indexers
public static string CommandLine
{
get
{
return default(string);
}
}
public static string CurrentDirectory
{
get
{
return default(string);
}
set
{
}
}
public static int ExitCode
{
get
{
return default(int);
}
set
{
}
}
public static bool HasShutdownStarted
{
get
{
return default(bool);
}
}
public static bool Is64BitOperatingSystem
{
get
{
return default(bool);
}
}
public static bool Is64BitProcess
{
get
{
Contract.Ensures(Contract.Result<bool>() == false);
return default(bool);
}
}
public static string MachineName
{
get
{
return default(string);
}
}
public static string NewLine
{
get
{
Contract.Ensures(Contract.Result<string>() != null);
Contract.Ensures(Contract.Result<string>() == @"
");
return default(string);
}
}
public static OperatingSystem OSVersion
{
get
{
Contract.Ensures(Contract.Result<System.OperatingSystem>() != null);
return default(OperatingSystem);
}
}
public static int ProcessorCount
{
get
{
return default(int);
}
}
public static string StackTrace
{
get
{
return default(string);
}
}
public static string SystemDirectory
{
get
{
return default(string);
}
}
public static int SystemPageSize
{
get
{
return default(int);
}
}
public static int TickCount
{
get
{
return default(int);
}
}
public static string UserDomainName
{
get
{
return default(string);
}
}
public static bool UserInteractive
{
get
{
return default(bool);
}
}
public static string UserName
{
get
{
return default(string);
}
}
public static Version Version
{
get
{
Contract.Ensures(Contract.Result<System.Version>() != null);
return default(Version);
}
}
public static long WorkingSet
{
get
{
return default(long);
}
}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Symbology.dll
// Description: Contains the business logic for symbology layers and symbol categories.
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/4/2008 4:36:35 PM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
//
// ********************************************************************************************************
using System;
using System.Collections.Generic;
using System.Drawing;
using DotSpatial.NTSExtension;
using GeoAPI.Geometries;
namespace DotSpatial.Symbology
{
/// <summary>
/// A Draw Window is a special type of envelope that supports some basic transformations
/// </summary>
public class DrawWindow : Envelope
{
#region Private Variables
private Envelope _geographicView;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of DrawWindow, making the assumption that the map is in Geographic coordinates of decimal degrees
/// </summary>
public DrawWindow()
{
_geographicView = new Envelope(-180, 180, -90, 90);
}
/// <summary>
/// Creates a new draw window with the specified coordinates
/// </summary>
/// <param name="x1">The first x-value.</param>
/// <param name="x2">The second x-value.</param>
/// <param name="y1">The first y-value.</param>
/// <param name="y2">The second y-value.</param>
/// <param name="z1">The first z-value.</param>
/// <param name="z2">The second z-value.</param>
public DrawWindow(double x1, double x2, double y1, double y2, double z1, double z2) :
base(x1, x2, y1, y2)
{
this.InitZ(z1,z2);
_geographicView = new Envelope(x1, x2, y1, y2);
}
/// <summary>
/// Constructs a new DrawWindow based on the specified Envelope. The envelope becomes
/// the GeographicView for this DrawWindow.
/// </summary>
/// <param name="env"></param>
public DrawWindow(Envelope env)
: base(env)
{
_geographicView = env.Clone();
}
#endregion
#region Methods
/// <summary>
/// Replaces the inherited Envelope copy in order to create a copy of the DrawWindow instead
/// </summary>
/// <returns></returns>
public DrawWindow Copy()
{
Envelope env = base.Clone();
DrawWindow dw = new DrawWindow(env) {GeographicView = _geographicView};
return dw;
}
/// <summary>
/// Replaces the inherited clone in order to make a copy of the DrawWindow
/// </summary>
/// <returns></returns>
public new object Clone()
{
return Copy();
}
/// <summary>
/// Converts two dimensions of the specified coordinate into a two dimensional PointF
/// </summary>
/// <param name="inX"></param>
/// <param name="inY"></param>
/// <returns>A PointF</returns>
public PointF ProjToDrawWindow(double inX, double inY)
{
double x = inX - MinX;
double y = inY - MinY;
x = x / Width;
y = y / Height;
return new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
}
/// <summary>
/// Converts two dimensions of the specified coordinate into a two dimensional PointF
/// </summary>
/// <param name="inCoord">Any valid ICoordinate</param>
/// <returns>A PointF</returns>
public PointF ProjToDrawWindow(Coordinate inCoord)
{
double x = inCoord.X - MinX;
double y = inCoord.Y - MinY;
x = x / Width;
y = y / Height;
return new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
}
/// <summary>
/// Converts two dimensions of the specified coordinate into a two dimensional PointF.
/// </summary>
/// <param name="inCoords"></param>
/// <returns></returns>
public PointF[] ProjToDrawWindow(List<Coordinate> inCoords)
{
if (inCoords == null || inCoords.Count == 0) return null;
double minX = MinX;
double minY = MinY;
double w = Width;
double h = Height;
PointF[] result = new PointF[inCoords.Count];
for (int i = 0; i < inCoords.Count; i++)
{
double x = inCoords[i].X - minX;
double y = inCoords[i].Y - minY;
x = x / w;
y = y / h;
result[i] = new PointF(Convert.ToSingle(x), Convert.ToSingle(y));
}
return result;
}
/// <summary>
/// Converts a PointF from the draw window back into the double precision data coordinate.
/// </summary>
/// <param name="inPoint"></param>
/// <returns></returns>
public Coordinate DrawWindowToProj(PointF inPoint)
{
double x = Convert.ToDouble(inPoint);
double y = Convert.ToDouble(inPoint);
x = Width * x + MinX;
y = Height * y + MinY;
return new Coordinate(x, y);
}
/// <summary>
/// Converts an Array of PointF values from the draw window back into the double precision data coordinates.
/// There will be uncertainty based on how zoomed in you are.
/// </summary>
/// <param name="inPoints"></param>
/// <returns></returns>
public List<Coordinate> DrawWindowToProj(PointF[] inPoints)
{
List<Coordinate> result = new List<Coordinate>();
double minX = MinX;
double minY = MinY;
double w = Width;
double h = Height;
foreach (PointF point in inPoints)
{
double x = Convert.ToDouble(point);
double y = Convert.ToDouble(point);
x = w * x + minX;
y = h * y + minY;
result.Add(new Coordinate(x, y));
}
return result;
}
/// <summary>
///
/// </summary>
/// <param name="env"></param>
/// <returns></returns>
public RectangleF ProjToDrawWindow(Envelope env)
{
PointF ul = ProjToDrawWindow(env.MinX, env.MaxY);
PointF lr = ProjToDrawWindow(env.MaxX, env.MinY);
return new RectangleF(ul.X, ul.Y, lr.X - ul.X, ul.Y - lr.Y);
}
/// <summary>
/// Calculates a geographic envelope from the specified window in the DrawWindow coordinates.
/// </summary>
/// <param name="window"></param>
/// <returns></returns>
public Envelope DrawWindowToProj(RectangleF window)
{
PointF lr = new PointF(window.Right, window.Bottom);
return new Envelope(DrawWindowToProj(window.Location), DrawWindowToProj(lr));
}
#endregion
#region Properties
/// <summary>
/// This is the the current extent of the map in geographic coordinates.
/// </summary>
public virtual Envelope GeographicView
{
get { return _geographicView; }
set { _geographicView = value; }
}
/// <summary>
/// Retrieves the MinX value of the GeographicView, in DrawWindow coordinates
/// </summary>
public RectangleF View
{
get
{
return ProjToDrawWindow(_geographicView);
}
}
/// <summary>
/// This calculates the DrawWindowView from the GeographicView
/// </summary>
public virtual RectangleF GetDrawWindowView()
{
return ProjToDrawWindow(_geographicView);
}
#endregion
}
}
| |
#region License
//
// Primitive.cs July 2006
//
// Copyright (C) 2006, Niall Gallagher <niallg@users.sf.net>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
#endregion
#region Using directives
using SimpleFramework.Xml.Strategy;
using SimpleFramework.Xml.Stream;
using System;
#endregion
namespace SimpleFramework.Xml.Core {
/// <summary>
/// The <c>Primitive</c> object is used to provide serialization
/// for primitive objects. This can serialize and deserialize any
/// primitive object and enumerations. Primitive values are converted
/// to text using the <c>String.valueOf</c> method. Enumerated
/// types are converted using the <c>Enum.valueOf</c> method.
/// <p>
/// Text within attributes and elements can contain template variables
/// similar to those found in Apache <cite>Ant</cite>. This allows
/// values such as system properties, environment variables, and user
/// specified mappings to be inserted into the text in place of the
/// template reference variables.
/// </code>
/// <example attribute="${value}>
/// <text>Text with a ${variable}</text>
/// </example>
/// </code>
/// In the above XML element the template variable references will be
/// checked against the <c>Filter</c> object used by the context
/// serialization object. If they corrospond to a filtered value then
/// they are replaced, if not the text remains unchanged.
/// </summary>
/// <seealso>
/// SimpleFramework.Xml.Filter.Filter
/// </seealso>
class Primitive : Converter {
/// <summary>
/// This is used to convert the string values to primitives.
/// </summary>
private readonly PrimitiveFactory factory;
/// <summary>
/// The context object is used to perform text value filtering.
/// </summary>
private readonly Context context;
/// <summary>
/// This the value used to represent a null primitive value.
/// </summary>
private readonly String empty;
/// <summary>
/// This is the type that this primitive expects to represent.
/// </summary>
private readonly Class type;
/// <summary>
/// Constructor for the <c>Primitive</c> object. This is used
/// to convert an XML node to a primitive object and vice versa. To
/// perform deserialization the primitive object requires the context
/// object used for the instance of serialization to performed.
/// </summary>
/// <param name="context">
/// the context object used for the serialization
/// </param>
/// <param name="type">
/// this is the type of primitive this represents
/// </param>
public Primitive(Context context, Type type) {
this(context, type, null);
}
/// <summary>
/// Constructor for the <c>Primitive</c> object. This is used
/// to convert an XML node to a primitive object and vice versa. To
/// perform deserialization the primitive object requires the context
/// object used for the instance of serialization to performed.
/// </summary>
/// <param name="context">
/// the context object used for the serialization
/// </param>
/// <param name="type">
/// this is the type of primitive this represents
/// </param>
/// <param name="empty">
/// this is the value used to represent a null value
/// </param>
public Primitive(Context context, Type type, String empty) {
this.factory = new PrimitiveFactory(context, type);
this.type = type.getType();
this.context = context;
this.empty = empty;
}
/// <summary>
/// This <c>read</c> method will extract the text value from
/// the node and replace any template variables before converting
/// it to a primitive value. This uses the <c>Context</c>
/// object used for this instance of serialization to replace all
/// template variables with values from the context filter.
/// </summary>
/// <param name="node">
/// this is the node to be converted to a primitive
/// </param>
/// <returns>
/// this returns the primitive that has been deserialized
/// </returns>
public Object Read(InputNode node) {
if(node.isElement()) {
return ReadElement(node);
}
return Read(node, type);
}
/// <summary>
/// This <c>read</c> method will extract the text value from
/// the node and replace any template variables before converting
/// it to a primitive value. This uses the <c>Context</c>
/// object used for this instance of serialization to replace all
/// template variables with values from the context filter.
/// </summary>
/// <param name="node">
/// this is the node to be converted to a primitive
/// </param>
/// <param name="value">
/// this is the original primitive value used
/// </param>
/// <returns>
/// this returns the primitive that has been deserialized
/// </returns>
public Object Read(InputNode node, Object value) {
if(value != null) {
throw new PersistenceException("Can not read existing %s", type);
}
return Read(node);
}
/// <summary>
/// This <c>read</c> method will extract the text value from
/// the node and replace any template variables before converting
/// it to a primitive value. This uses the <c>Context</c>
/// object used for this instance of serialization to replace all
/// template variables with values from the context filter.
/// </summary>
/// <param name="node">
/// this is the node to be converted to a primitive
/// </param>
/// <param name="type">
/// this is the type to read the primitive with
/// </param>
/// <returns>
/// this returns the primitive that has been deserialized
/// </returns>
public Object Read(InputNode node, Class type) {
String value = node.getValue();
if(value == null) {
return null;
}
if(empty != null && value.equals(empty)) {
return empty;
}
return ReadTemplate(value, type);
}
/// <summary>
/// This <c>read</c> method will extract the text value from
/// the node and replace any template variables before converting
/// it to a primitive value. This uses the <c>Context</c>
/// object used for this instance of serialization to replace all
/// template variables with values from the context filter.
/// </summary>
/// <param name="node">
/// this is the node to be converted to a primitive
/// </param>
/// <returns>
/// this returns the primitive that has been deserialized
/// </returns>
public Object ReadElement(InputNode node) {
Instance value = factory.GetInstance(node);
if(!value.isReference()) {
return ReadElement(node, value);
}
return value.GetInstance();
}
/// <summary>
/// This <c>read</c> method will extract the text value from
/// the node and replace any template variables before converting
/// it to a primitive value. This uses the <c>Context</c>
/// object used for this instance of serialization to replace all
/// template variables with values from the context filter.
/// </summary>
/// <param name="node">
/// this is the node to be converted to a primitive
/// </param>
/// <param name="value">
/// this is the instance to set the result to
/// </param>
/// <returns>
/// this returns the primitive that has been deserialized
/// </returns>
public Object ReadElement(InputNode node, Instance value) {
Object result = Read(node, type);
if(value != null) {
value.setInstance(result);
}
return result;
}
/// <summary>
/// This <c>read</c> method will extract the text value from
/// the node and replace any template variables before converting
/// it to a primitive value. This uses the <c>Context</c>
/// object used for this instance of serialization to replace all
/// template variables with values from the context filter.
/// </summary>
/// <param name="value">
/// this is the value to be processed as a template
/// </param>
/// <param name="type">
/// this is the type that that the primitive is
/// </param>
/// <returns>
/// this returns the primitive that has been deserialized
/// </returns>
public Object ReadTemplate(String value, Class type) {
String text = context.GetProperty(value);
if(text != null) {
return factory.GetInstance(text, type);
}
return null;
}
/// <summary>
/// This <c>validate</c> method will validate the primitive
/// by checking the node text. If the value is a reference then
/// this will not extract any value from the node. Transformation
/// of the extracted value is not done as it can not account for
/// template variables. Thus any text extracted is valid.
/// </summary>
/// <param name="node">
/// this is the node to be validated as a primitive
/// </param>
/// <returns>
/// this returns the primitive that has been validated
/// </returns>
public bool Validate(InputNode node) {
if(node.isElement()) {
ValidateElement(node);
} else {
node.getValue();
}
return true;
}
/// <summary>
/// This <c>validateElement</c> method validates a primitive
/// by checking the node text. If the value is a reference then
/// this will not extract any value from the node. Transformation
/// of the extracted value is not done as it can not account for
/// template variables. Thus any text extracted is valid.
/// </summary>
/// <param name="node">
/// this is the node to be validated as a primitive
/// </param>
/// <returns>
/// this returns the primitive that has been validated
/// </returns>
public bool ValidateElement(InputNode node) {
Instance type = factory.GetInstance(node);
if(!type.isReference()) {
type.setInstance(null);
}
return true;
}
/// <summary>
/// This <c>write</c> method will serialize the contents of
/// the provided object to the given XML element. This will use
/// the <c>String.valueOf</c> method to convert the object to
/// a string if the object represents a primitive, if however the
/// object represents an enumerated type then the text value is
/// created using <c>Enum.name</c>.
/// </summary>
/// <param name="source">
/// this is the object to be serialized
/// </param>
/// <param name="node">
/// this is the XML element to have its text set
/// </param>
public void Write(OutputNode node, Object source) {
String text = factory.GetText(source);
if(text != null) {
node.setValue(text);
}
}
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace OpenSim.Framework
{
public class LandAccessEntry
{
public UUID AgentID;
public int Expires;
public AccessList Flags;
}
/// <summary>
/// Details of a Parcel of land
/// </summary>
public class LandData
{
// use only one serializer to give the runtime a chance to
// optimize it (it won't do that if you use a new instance
// every time)
private static XmlSerializer serializer = new XmlSerializer(typeof(LandData));
private Vector3 _AABBMax = new Vector3();
private Vector3 _AABBMin = new Vector3();
private int _area = 0;
private uint _auctionID = 0; //Unemplemented. If set to 0, not being auctioned
private UUID _authBuyerID = UUID.Zero; //Unemplemented. Authorized Buyer's UUID
private ParcelCategory _category = ParcelCategory.None; //Unemplemented. Parcel's chosen category
private int _claimDate = 0;
private int _claimPrice = 0; //Unemplemented
private UUID _globalID = UUID.Zero;
private UUID _groupID = UUID.Zero;
private bool _isGroupOwned = false;
private byte[] _bitmap = new byte[512];
private string _description = String.Empty;
/* FT: changed to safer defaults */
private uint _flags = (uint)ParcelFlags.AllowFly | (uint)ParcelFlags.AllowLandmark |
/*(uint)ParcelFlags.AllowAPrimitiveEntry |*/
(uint)ParcelFlags.AllowDeedToGroup | /*(uint)ParcelFlags.AllowTerraform | */
(uint)ParcelFlags.CreateGroupObjects | (uint)ParcelFlags.AllowOtherScripts |
(uint)ParcelFlags.SoundLocal | (uint)ParcelFlags.AllowVoiceChat;
private byte _landingType = 0;
private string _name = "Your Parcel";
private ParcelStatus _status = ParcelStatus.Leased;
private int _localID = 0;
private byte _mediaAutoScale = 0;
private UUID _mediaID = UUID.Zero;
private string _mediaURL = String.Empty;
private string _musicURL = String.Empty;
private UUID _ownerID = UUID.Zero;
private List<LandAccessEntry> _parcelAccessList = new List<LandAccessEntry>();
private float _passHours = 0;
private int _passPrice = 0;
private int _salePrice = 0; //Unemeplemented. Parcels price.
private int _simwideArea = 0;
private int _simwidePrims = 0;
private UUID _snapshotID = UUID.Zero;
private Vector3 _userLocation = new Vector3();
private Vector3 _userLookAt = new Vector3();
private int _otherCleanTime = 0;
private string _mediaType = "none/none";
private string _mediaDescription = "";
private int _mediaHeight = 0;
private int _mediaWidth = 0;
private bool _mediaLoop = false;
private bool _obscureMusic = false;
private bool _obscureMedia = false;
private float _dwell = 0;
/// <summary>
/// Traffic count of parcel
/// </summary>
[XmlIgnore]
public float Dwell
{
get
{
return _dwell;
}
set
{
_dwell = value;
}
}
/// <summary>
/// Whether to obscure parcel media URL
/// </summary>
[XmlIgnore]
public bool ObscureMedia
{
get
{
return _obscureMedia;
}
set
{
_obscureMedia = value;
}
}
/// <summary>
/// Whether to obscure parcel music URL
/// </summary>
[XmlIgnore]
public bool ObscureMusic
{
get
{
return _obscureMusic;
}
set
{
_obscureMusic = value;
}
}
/// <summary>
/// Whether to loop parcel media
/// </summary>
[XmlIgnore]
public bool MediaLoop
{
get
{
return _mediaLoop;
}
set
{
_mediaLoop = value;
}
}
/// <summary>
/// Height of parcel media render
/// </summary>
[XmlIgnore]
public int MediaHeight
{
get
{
return _mediaHeight;
}
set
{
_mediaHeight = value;
}
}
/// <summary>
/// Width of parcel media render
/// </summary>
[XmlIgnore]
public int MediaWidth
{
get
{
return _mediaWidth;
}
set
{
_mediaWidth = value;
}
}
/// <summary>
/// Upper corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMax
{
get
{
return _AABBMax;
}
set
{
_AABBMax = value;
}
}
/// <summary>
/// Lower corner of the AABB for the parcel
/// </summary>
[XmlIgnore]
public Vector3 AABBMin
{
get
{
return _AABBMin;
}
set
{
_AABBMin = value;
}
}
/// <summary>
/// Area in meters^2 the parcel contains
/// </summary>
public int Area
{
get
{
return _area;
}
set
{
_area = value;
}
}
/// <summary>
/// ID of auction (3rd Party Integration) when parcel is being auctioned
/// </summary>
public uint AuctionID
{
get
{
return _auctionID;
}
set
{
_auctionID = value;
}
}
/// <summary>
/// UUID of authorized buyer of parcel. This is UUID.Zero if anyone can buy it.
/// </summary>
public UUID AuthBuyerID
{
get
{
return _authBuyerID;
}
set
{
_authBuyerID = value;
}
}
/// <summary>
/// Category of parcel. Used for classifying the parcel in classified listings
/// </summary>
public ParcelCategory Category
{
get
{
return _category;
}
set
{
_category = value;
}
}
/// <summary>
/// Date that the current owner purchased or claimed the parcel
/// </summary>
public int ClaimDate
{
get
{
return _claimDate;
}
set
{
_claimDate = value;
}
}
/// <summary>
/// The last price that the parcel was sold at
/// </summary>
public int ClaimPrice
{
get
{
return _claimPrice;
}
set
{
_claimPrice = value;
}
}
/// <summary>
/// Global ID for the parcel. (3rd Party Integration)
/// </summary>
public UUID GlobalID
{
get
{
return _globalID;
}
set
{
_globalID = value;
}
}
/// <summary>
/// Unique ID of the Group that owns
/// </summary>
public UUID GroupID
{
get
{
return _groupID;
}
set
{
_groupID = value;
}
}
/// <summary>
/// Returns true if the Land Parcel is owned by a group
/// </summary>
public bool IsGroupOwned
{
get
{
return _isGroupOwned;
}
set
{
_isGroupOwned = value;
}
}
/// <summary>
/// jp2 data for the image representative of the parcel in the parcel dialog
/// </summary>
public byte[] Bitmap
{
get
{
return _bitmap;
}
set
{
_bitmap = value;
}
}
/// <summary>
/// Parcel Description
/// </summary>
public string Description
{
get
{
return _description;
}
set
{
_description = value;
}
}
/// <summary>
/// Parcel settings. Access flags, Fly, NoPush, Voice, Scripts allowed, etc. ParcelFlags
/// </summary>
public uint Flags
{
get
{
return _flags;
}
set
{
_flags = value;
}
}
/// <summary>
/// Determines if people are able to teleport where they please on the parcel or if they
/// get constrainted to a specific point on teleport within the parcel
/// </summary>
public byte LandingType
{
get
{
return _landingType;
}
set
{
_landingType = value;
}
}
/// <summary>
/// Parcel Name
/// </summary>
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
/// <summary>
/// Status of Parcel, Leased, Abandoned, For Sale
/// </summary>
public ParcelStatus Status
{
get
{
return _status;
}
set
{
_status = value;
}
}
/// <summary>
/// Internal ID of the parcel. Sometimes the client will try to use this value
/// </summary>
public int LocalID
{
get
{
return _localID;
}
set
{
_localID = value;
}
}
/// <summary>
/// Determines if we scale the media based on the surface it's on
/// </summary>
public byte MediaAutoScale
{
get
{
return _mediaAutoScale;
}
set
{
_mediaAutoScale = value;
}
}
/// <summary>
/// Texture Guid to replace with the output of the media stream
/// </summary>
public UUID MediaID
{
get
{
return _mediaID;
}
set
{
_mediaID = value;
}
}
/// <summary>
/// URL to the media file to display
/// </summary>
public string MediaURL
{
get
{
return _mediaURL;
}
set
{
_mediaURL = value;
}
}
public string MediaType
{
get
{
return _mediaType;
}
set
{
_mediaType = value;
}
}
/// <summary>
/// URL to the shoutcast music stream to play on the parcel
/// </summary>
public string MusicURL
{
get
{
return _musicURL;
}
set
{
_musicURL = value;
}
}
/// <summary>
/// Owner Avatar or Group of the parcel. Naturally, all land masses must be
/// owned by someone
/// </summary>
public UUID OwnerID
{
get
{
return _ownerID;
}
set
{
_ownerID = value;
}
}
/// <summary>
/// List of access data for the parcel. User data, some bitflags, and a time
/// </summary>
public List<LandAccessEntry> ParcelAccessList
{
get
{
return _parcelAccessList;
}
set
{
_parcelAccessList = value;
}
}
/// <summary>
/// How long in hours a Pass to the parcel is given
/// </summary>
public float PassHours
{
get
{
return _passHours;
}
set
{
_passHours = value;
}
}
/// <summary>
/// Price to purchase a Pass to a restricted parcel
/// </summary>
public int PassPrice
{
get
{
return _passPrice;
}
set
{
_passPrice = value;
}
}
/// <summary>
/// When the parcel is being sold, this is the price to purchase the parcel
/// </summary>
public int SalePrice
{
get
{
return _salePrice;
}
set
{
_salePrice = value;
}
}
/// <summary>
/// Number of meters^2 in the Simulator
/// </summary>
[XmlIgnore]
public int SimwideArea
{
get
{
return _simwideArea;
}
set
{
_simwideArea = value;
}
}
/// <summary>
/// Number of SceneObjectPart in the Simulator
/// </summary>
[XmlIgnore]
public int SimwidePrims
{
get
{
return _simwidePrims;
}
set
{
_simwidePrims = value;
}
}
/// <summary>
/// ID of the snapshot used in the client parcel dialog of the parcel
/// </summary>
public UUID SnapshotID
{
get
{
return _snapshotID;
}
set
{
_snapshotID = value;
}
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the location
/// that the user will be redirected to
/// </summary>
public Vector3 UserLocation
{
get
{
return _userLocation;
}
set
{
_userLocation = value;
}
}
/// <summary>
/// When teleporting is restricted to a certain point, this is the rotation
/// that the user will be positioned
/// </summary>
public Vector3 UserLookAt
{
get
{
return _userLookAt;
}
set
{
_userLookAt = value;
}
}
/// <summary>
/// Autoreturn number of minutes to return SceneObjectGroup that are owned by someone who doesn't own
/// the parcel and isn't set to the same 'group' as the parcel.
/// </summary>
public int OtherCleanTime
{
get
{
return _otherCleanTime;
}
set
{
_otherCleanTime = value;
}
}
/// <summary>
/// parcel media description
/// </summary>
public string MediaDescription
{
get
{
return _mediaDescription;
}
set
{
_mediaDescription = value;
}
}
public LandData()
{
_globalID = UUID.Random();
}
/// <summary>
/// Make a new copy of the land data
/// </summary>
/// <returns></returns>
public LandData Copy()
{
LandData landData = new LandData();
landData._AABBMax = _AABBMax;
landData._AABBMin = _AABBMin;
landData._area = _area;
landData._auctionID = _auctionID;
landData._authBuyerID = _authBuyerID;
landData._category = _category;
landData._claimDate = _claimDate;
landData._claimPrice = _claimPrice;
landData._globalID = _globalID;
landData._groupID = _groupID;
landData._isGroupOwned = _isGroupOwned;
landData._localID = _localID;
landData._landingType = _landingType;
landData._mediaAutoScale = _mediaAutoScale;
landData._mediaID = _mediaID;
landData._mediaURL = _mediaURL;
landData._musicURL = _musicURL;
landData._ownerID = _ownerID;
landData._bitmap = (byte[])_bitmap.Clone();
landData._description = _description;
landData._flags = _flags;
landData._name = _name;
landData._status = _status;
landData._passHours = _passHours;
landData._passPrice = _passPrice;
landData._salePrice = _salePrice;
landData._snapshotID = _snapshotID;
landData._userLocation = _userLocation;
landData._userLookAt = _userLookAt;
landData._otherCleanTime = _otherCleanTime;
landData._mediaType = _mediaType;
landData._mediaDescription = _mediaDescription;
landData._mediaWidth = _mediaWidth;
landData._mediaHeight = _mediaHeight;
landData._mediaLoop = _mediaLoop;
landData._obscureMusic = _obscureMusic;
landData._obscureMedia = _obscureMedia;
landData._simwideArea = _simwideArea;
landData._simwidePrims = _simwidePrims;
landData._dwell = _dwell;
landData._parcelAccessList.Clear();
foreach (LandAccessEntry entry in _parcelAccessList)
{
LandAccessEntry newEntry = new LandAccessEntry();
newEntry.AgentID = entry.AgentID;
newEntry.Flags = entry.Flags;
newEntry.Expires = entry.Expires;
landData._parcelAccessList.Add(newEntry);
}
return landData;
}
public void ToXml(XmlWriter xmlWriter)
{
serializer.Serialize(xmlWriter, this);
}
/// <summary>
/// Restore a LandData object from the serialized xml representation.
/// </summary>
/// <param name="xmlReader"></param>
/// <returns></returns>
public static LandData FromXml(XmlReader xmlReader)
{
LandData land = (LandData)serializer.Deserialize(xmlReader);
return land;
}
}
}
| |
using System;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class FScreen
{
public float width; //in points, not pixels
public float height; //in points, not pixels
public float halfWidth; //for convenience, in points
public float halfHeight; //for convenience, in points
public float pixelWidth; //in pixels
public float pixelHeight; //in pixels
public delegate void ScreenOrientationChangeDelegate();
public event ScreenOrientationChangeDelegate SignalOrientationChange;
//the bool in SignalResize represents wasOrientationChange,
//which tells you whether the resize was due to an orientation change or not
public delegate void ScreenResizeDelegate(bool wasResizedDueToOrientationChange);
public event ScreenResizeDelegate SignalResize;
//this is populated by the FutileParams
private float _originX;
private float _originY;
private ScreenOrientation _currentOrientation;
private float _screenLongLength;
private float _screenShortLength;
private bool _didJustResize;
private float _oldWidth;
private float _oldHeight;
private FResolutionLevel _resLevel;
private FutileParams _futileParams;
public FScreen (FutileParams futileParams)
{
_futileParams = futileParams;
#if UNITY_IPHONE || UNITY_ANDROID
#if UNITY_3_5
TouchScreenKeyboard.autorotateToLandscapeLeft = false;
TouchScreenKeyboard.autorotateToLandscapeRight = false;
TouchScreenKeyboard.autorotateToPortrait = false;
TouchScreenKeyboard.autorotateToPortraitUpsideDown = false;
#else
Screen.autorotateToLandscapeLeft = false;
Screen.autorotateToLandscapeRight = false;
Screen.autorotateToPortrait = false;
Screen.autorotateToPortraitUpsideDown = false;
#endif
#endif
//Non-mobile unity always defaults to portrait for some reason, so fix this manually
if(Screen.height > Screen.width)
{
_currentOrientation = ScreenOrientation.Portrait;
}
else
{
_currentOrientation = ScreenOrientation.LandscapeLeft;
}
//get the correct orientation if we're on a mobile platform
#if !UNITY_EDITOR && (UNITY_IPHONE || UNITY_ANDROID)
_currentOrientation = Screen.orientation;
#endif
//special "single orientation" mode
if(_futileParams.singleOrientation != ScreenOrientation.Unknown)
{
_currentOrientation = _futileParams.singleOrientation;
}
else //if we're not in a supported orientation, put us in one!
{
if(_currentOrientation == ScreenOrientation.LandscapeLeft && !_futileParams.supportsLandscapeLeft)
{
if(_futileParams.supportsLandscapeRight) _currentOrientation = ScreenOrientation.LandscapeRight;
else if(_futileParams.supportsPortrait) _currentOrientation = ScreenOrientation.Portrait;
else if(_futileParams.supportsPortraitUpsideDown) _currentOrientation = ScreenOrientation.PortraitUpsideDown;
}
else if(_currentOrientation == ScreenOrientation.LandscapeRight && !_futileParams.supportsLandscapeRight)
{
if(_futileParams.supportsLandscapeLeft) _currentOrientation = ScreenOrientation.LandscapeLeft;
else if(_futileParams.supportsPortrait) _currentOrientation = ScreenOrientation.Portrait;
else if(_futileParams.supportsPortraitUpsideDown) _currentOrientation = ScreenOrientation.PortraitUpsideDown;
}
else if(_currentOrientation == ScreenOrientation.Portrait && !_futileParams.supportsPortrait)
{
if(_futileParams.supportsPortraitUpsideDown) _currentOrientation = ScreenOrientation.PortraitUpsideDown;
else if(_futileParams.supportsLandscapeLeft) _currentOrientation = ScreenOrientation.LandscapeLeft;
else if(_futileParams.supportsLandscapeRight) _currentOrientation = ScreenOrientation.LandscapeRight;
}
else if(_currentOrientation == ScreenOrientation.PortraitUpsideDown && !_futileParams.supportsPortraitUpsideDown)
{
if(_futileParams.supportsPortrait) _currentOrientation = ScreenOrientation.Portrait;
else if(_futileParams.supportsLandscapeLeft) _currentOrientation = ScreenOrientation.LandscapeLeft;
else if(_futileParams.supportsLandscapeRight) _currentOrientation = ScreenOrientation.LandscapeRight;
}
}
Screen.orientation = _currentOrientation;
_screenLongLength = Math.Max(Screen.height, Screen.width);
_screenShortLength = Math.Min(Screen.height, Screen.width);
if(_currentOrientation == ScreenOrientation.Portrait || _currentOrientation == ScreenOrientation.PortraitUpsideDown)
{
pixelWidth = _screenShortLength;
pixelHeight = _screenLongLength;
}
else //landscape
{
pixelWidth = _screenLongLength;
pixelHeight = _screenShortLength;
}
//get the resolution level - the one we're closest to WITHOUT going over, price is right rules :)
_resLevel = null;
foreach(FResolutionLevel resLevel in _futileParams.resLevels)
{
if(_screenLongLength <= resLevel.maxLength) //we've found our resLevel
{
_resLevel = resLevel;
break;
}
}
//if we couldn't find a res level, it means the screen is bigger than the biggest one, so just choose the biggest
if(_resLevel == null)
{
_resLevel = _futileParams.resLevels.GetLastObject();
if(_resLevel == null)
{
throw new FutileException("You must add at least one FResolutionLevel!");
}
}
Futile.resourceSuffix = _resLevel.resourceSuffix;
//this is what helps us figure out the display scale if we're not at a specific resolution level
//it's relative to the next highest resolution level
float displayScaleModifier = 1.0f;
if(_futileParams.shouldLerpToNearestResolutionLevel)
{
displayScaleModifier = _screenLongLength/_resLevel.maxLength;
}
Futile.displayScale = _resLevel.displayScale * displayScaleModifier;
Futile.displayScaleInverse = 1.0f/Futile.displayScale;
Futile.resourceScale = _resLevel.resourceScale;
Futile.resourceScaleInverse = 1.0f/Futile.resourceScale;
width = pixelWidth*Futile.displayScaleInverse;
height = pixelHeight*Futile.displayScaleInverse;
if(Futile.isOpenGL)
{
Futile.screenPixelOffset = 0;
}
else //directX needs to be offset by half a pixel
{
Futile.screenPixelOffset = 0.5f * Futile.displayScaleInverse;
}
halfWidth = width/2.0f;
halfHeight = height/2.0f;
_originX = _futileParams.origin.x;
_originY = _futileParams.origin.y;
Debug.Log ("Futile: Display scale is " + Futile.displayScale);
Debug.Log ("Futile: Resource scale is " + Futile.resourceScale);
Debug.Log ("Futile: Resource suffix is " + _resLevel.resourceSuffix);
Debug.Log ("FScreen: Screen size in pixels is (" + pixelWidth +"px," + pixelHeight+"px)");
Debug.Log ("FScreen: Screen size in points is (" + width + "," + height+")");
Debug.Log ("FScreen: Origin is at (" + _originX*width + "," + _originY*height+")");
Debug.Log ("FScreen: Initial orientation is " + _currentOrientation);
_didJustResize = true;
}
public void Update()
{
if(Input.deviceOrientation == DeviceOrientation.LandscapeLeft && _currentOrientation != ScreenOrientation.LandscapeLeft && _futileParams.supportsLandscapeLeft)
{
SwitchOrientation(ScreenOrientation.LandscapeLeft);
}
else if(Input.deviceOrientation == DeviceOrientation.LandscapeRight && _currentOrientation != ScreenOrientation.LandscapeRight && _futileParams.supportsLandscapeRight)
{
SwitchOrientation(ScreenOrientation.LandscapeRight);
}
else if(Input.deviceOrientation == DeviceOrientation.Portrait && _currentOrientation != ScreenOrientation.Portrait && _futileParams.supportsPortrait)
{
SwitchOrientation(ScreenOrientation.Portrait);
}
else if(Input.deviceOrientation == DeviceOrientation.PortraitUpsideDown && _currentOrientation != ScreenOrientation.PortraitUpsideDown && _futileParams.supportsPortraitUpsideDown)
{
SwitchOrientation(ScreenOrientation.PortraitUpsideDown);
}
if(_didJustResize)
{
_didJustResize = false;
_oldWidth = Screen.width;
_oldHeight = Screen.height;
}
else if(_oldWidth != Screen.width || _oldHeight != Screen.height)
{
_oldWidth = Screen.width;
_oldHeight = Screen.height;
UpdateScreenDimensions();
if(SignalResize != null) SignalResize(false);
}
}
public void SwitchOrientation (ScreenOrientation newOrientation)
{
Debug.Log("Futile: Orientation changed to " + newOrientation);
if(_futileParams.singleOrientation != ScreenOrientation.Unknown) //if we're in single orientation mode, just broadcast the change, don't actually change anything
{
_currentOrientation = newOrientation;
if(SignalOrientationChange != null) SignalOrientationChange();
}
else
{
Screen.orientation = newOrientation;
_currentOrientation = newOrientation;
UpdateScreenDimensions();
Debug.Log ("Orientation switched to " + _currentOrientation + " screen is now: " + pixelWidth+"x"+pixelHeight+"px");
if(SignalOrientationChange != null) SignalOrientationChange();
if(SignalResize != null) SignalResize(true);
_didJustResize = true;
}
}
private void UpdateScreenDimensions()
{
_screenLongLength = Math.Max (Screen.width, Screen.height);
_screenShortLength = Math.Min (Screen.width, Screen.height);
if(_currentOrientation == ScreenOrientation.Portrait || _currentOrientation == ScreenOrientation.PortraitUpsideDown)
{
pixelWidth = _screenShortLength;
pixelHeight = _screenLongLength;
}
else //landscape
{
pixelWidth = _screenLongLength;
pixelHeight = _screenShortLength;
}
width = pixelWidth*Futile.displayScaleInverse;
height = pixelHeight*Futile.displayScaleInverse;
halfWidth = width/2.0f;
halfHeight = height/2.0f;
Futile.instance.UpdateCameraPosition();
}
public float originX
{
get {return _originX;}
set
{
if(_originX != value)
{
_originX = value;
Futile.instance.UpdateCameraPosition();
}
}
}
public float originY
{
get {return _originY;}
set
{
if(_originY != value)
{
_originY = value;
Futile.instance.UpdateCameraPosition();
}
}
}
public ScreenOrientation currentOrientation
{
get {return _currentOrientation;}
set
{
if(_currentOrientation != value)
{
SwitchOrientation(value);
}
}
}
public bool IsLandscape()
{
return _currentOrientation == ScreenOrientation.LandscapeLeft || _currentOrientation == ScreenOrientation.LandscapeRight;
}
}
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Routing;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Diagnostics.Trace;
using Adxstudio.Xrm.Web.Mvc;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Configuration;
using Microsoft.Xrm.Portal.Configuration;
using Microsoft.Xrm.Portal.Web;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
namespace Adxstudio.Xrm.Web
{
/// <summary>
/// A <see cref="SiteMapProvider"/> for navigating portal <see cref="Entity"/> hierarchies.
/// </summary>
/// <remarks>
/// Configuration format.
/// <code>
/// <![CDATA[
/// <configuration>
///
/// <system.web>
/// <siteMap enabled="true" defaultProvider="Xrm">
/// <providers>
/// <add
/// name="Xrm"
/// type="Adxstudio.Xrm.Web.CrmSiteMapProvider"
/// securityTrimmingEnabled="true"
/// portalName="Xrm" [Microsoft.Xrm.Portal.Configuration.PortalContextElement]
/// />
/// </providers>
/// </siteMap>
/// </system.web>
///
/// </configuration>
/// ]]>
/// </code>
/// </remarks>
/// <seealso cref="PortalContextElement"/>
/// <seealso cref="PortalCrmConfigurationManager"/>
/// <seealso cref="CrmConfigurationManager"/>
public class CrmSiteMapProvider : Microsoft.Xrm.Portal.Web.CrmSiteMapProvider
{
public override SiteMapNode CurrentNode
{
get
{
if (IsPageless(HttpContext.Current))
{
// short circuit to the root node for flagged routes
return this.RootNode;
}
return base.CurrentNode;
}
}
public override SiteMapNode FindSiteMapNode(string rawUrl)
{
var clientUrl = ExtractClientUrlFromRawUrl(rawUrl);
TraceInfo("FindSiteMapNode({0})", clientUrl.PathWithQueryString);
var portal = PortalContext;
var context = portal.ServiceContext;
var website = portal.Website;
// Find any possible SiteMarkerRoutes (or other IPortalContextRoutes) that match this path.
var contextPath = RouteTable.Routes.GetPortalContextPath(portal, clientUrl.Path) ?? clientUrl.Path;
// If the URL matches a web page, try to look up that page and return a node.
var pageMappingResult = UrlMapping.LookupPageByUrlPath(context, website, contextPath);
if (pageMappingResult.Node != null && pageMappingResult.IsUnique)
{
return GetAccessibleNodeOrAccessDeniedNode(context, pageMappingResult.Node);
}
else if (!pageMappingResult.IsUnique)
{
return GetNotFoundNode();
}
// If the URL matches a web file, try to look up that file and return a node.
var file = UrlMapping.LookupFileByUrlPath(context, website, clientUrl.Path);
if (file != null)
{
return GetAccessibleNodeOrAccessDeniedNode(context, file);
}
// If there is a pageid Guid on the querystring, try to look up a web page by
// that ID and return a node.
Guid pageid;
if (TryParseGuid(clientUrl.QueryString["pageid"], out pageid))
{
var foundPage = context.CreateQuery("adx_webpage")
.FirstOrDefault(wp => wp.GetAttributeValue<Guid>("adx_webpageid") == pageid
&& wp.GetAttributeValue<EntityReference>("adx_websiteid") == website.ToEntityReference());
if (foundPage != null)
{
return GetAccessibleNodeOrAccessDeniedNode(context, foundPage);
}
}
// If the above lookups failed, try find a node in any other site map providers.
foreach (SiteMapProvider subProvider in SiteMap.Providers)
{
// Skip this provider if it is the same as this one.
if (subProvider.Name == Name) continue;
var node = subProvider.FindSiteMapNode(clientUrl.PathWithQueryString);
if (node != null)
{
return node;
}
}
return GetNotFoundNode();
}
public override SiteMapNode GetParentNode(SiteMapNode node)
{
TraceInfo("GetParentNode({0})", node.Key);
var portal = PortalContext;
var context = portal.ServiceContext;
var website = portal.Website;
var pageMappingResult = UrlMapping.LookupPageByUrlPath(context, website, node.Url);
if (pageMappingResult.Node == null)
{
return null;
}
var parentPage = pageMappingResult.Node.GetRelatedEntity(context, "adx_webpage_webpage", EntityRole.Referencing);
if (parentPage == null)
{
return null;
}
return GetAccessibleNodeOrAccessDeniedNode(context, parentPage);
}
protected override void AddNode(SiteMapNode node)
{
AddNode(node, base.AddNode);
}
protected override void AddNode(SiteMapNode node, SiteMapNode parentNode)
{
AddNode(node, n => base.AddNode(n, parentNode));
}
protected void AddNode(SiteMapNode node, Action<SiteMapNode> add)
{
if (!(node is CrmSiteMapNode))
{
add(node);
return;
}
Uri absoluteUri;
var encoded = false;
if (Uri.TryCreate(node.Url, UriKind.Absolute, out absoluteUri))
{
node.Url = HttpContext.Current.Server.UrlEncode(node.Url);
encoded = true;
}
add(node);
if (encoded)
{
node.Url = HttpContext.Current.Server.UrlDecode(node.Url);
}
}
public override SiteMapNodeCollection GetChildNodes(SiteMapNode node)
{
TraceInfo("GetChildNodes({0})", node.Key);
var children = new List<SiteMapNode>();
var portal = PortalContext;
var context = portal.ServiceContext;
var website = portal.Website;
// Shorcuts do not have children, may have the same Url as a web page.
if (IsShortcutNode(node))
{
return new SiteMapNodeCollection();
}
var pageMappingResult = UrlMapping.LookupPageByUrlPath(context, website, node.Url);
// If the node URL is that of a web page...
if (pageMappingResult.Node != null && pageMappingResult.IsUnique)
{
var childEntities = context.GetChildPages(pageMappingResult.Node).Union(context.GetChildFiles(pageMappingResult.Node)).Union(context.GetChildShortcuts(pageMappingResult.Node));
foreach (var entity in childEntities)
{
try
{
if (entity.LogicalName == "adx_shortcut")
{
var targetNode = GetShortcutTargetNode(context, entity);
var shortcutChildNode = GetShortcutCrmNode(context, entity, targetNode);
if (shortcutChildNode != null && ChildNodeValidator.Validate(context, shortcutChildNode))
{
children.Add(shortcutChildNode);
}
}
else
{
var childNode = GetNode(context, entity);
if (childNode != null && ChildNodeValidator.Validate(context, childNode))
{
children.Add(childNode);
}
}
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format(@"Exception creating child node for node child entity [{0}:{1}]: {2}", EntityNamePrivacy.GetEntityName(entity.LogicalName), entity.Id, e.ToString()));
continue;
}
}
}
// Append values from other site map providers.
foreach (SiteMapProvider subProvider in SiteMap.Providers)
{
// Skip this provider if it is the same as this one.
if (subProvider.Name == Name) continue;
var subProviderChildNodes = subProvider.GetChildNodes(node);
if (subProviderChildNodes == null) continue;
foreach (SiteMapNode childNode in subProviderChildNodes)
{
children.Add(childNode);
}
}
children.Sort(new SiteMapNodeDisplayOrderComparer());
return new SiteMapNodeCollection(children.ToArray());
}
protected CrmSiteMapNode GetShortcutCrmNode(OrganizationServiceContext serviceContext, Entity shortcut, CrmSiteMapNode targetNode)
{
if (shortcut == null)
{
throw new ArgumentNullException("shortcut");
}
if (shortcut.LogicalName != "adx_shortcut")
{
throw new ArgumentException("Entity {0} ({1}) is not of a type supported by this provider.".FormatWith(shortcut.Id, shortcut.GetType().FullName), "shortcut");
}
var url = !string.IsNullOrEmpty(shortcut.GetAttributeValue<string>("adx_externalurl"))
? shortcut.GetAttributeValue<string>("adx_externalurl")
: serviceContext.GetUrl(shortcut);
// Node does not have a valid URL, and should be filtered out of the sitemap.
if (string.IsNullOrEmpty(url))
{
return null;
}
var shortcutDescription = shortcut.GetAttributeValue<string>("adx_description");
var description = !string.IsNullOrEmpty(shortcutDescription)
? shortcutDescription
: targetNode != null
? targetNode.Description
: string.Empty;
return new CrmSiteMapNode(
this,
url,
url,
shortcut.GetAttributeValue<string>("adx_title") ?? shortcut.GetAttributeValue<string>("adx_name"),
description,
targetNode != null ? targetNode.RewriteUrl : url,
shortcut.GetAttributeValue<DateTime?>("modifiedon").GetValueOrDefault(DateTime.UtcNow),
shortcut);
}
private CrmSiteMapNode GetShortcutTargetNode(OrganizationServiceContext context, Entity entity)
{
if (!string.IsNullOrEmpty(entity.GetAttributeValue<string>("adx_externalurl")))
{
return null;
}
var targetWebPage = entity.GetRelatedEntity(context, "adx_webpage_shortcut");
if (targetWebPage != null)
{
return GetNode(context, targetWebPage);
}
var targetSurvey = entity.GetRelatedEntity(context, "adx_survey_shortcut");
if (targetSurvey != null)
{
return GetNode(context, targetSurvey);
}
var targetWebFile = entity.GetRelatedEntity(context, "adx_webfile_shortcut");
if (targetWebFile != null)
{
return GetNode(context, targetWebFile);
}
var targetEvent = entity.GetRelatedEntity(context, "adx_event_shortcut");
if (targetEvent != null)
{
return GetNode(context, targetEvent);
}
var targetForum = entity.GetRelatedEntity(context, "adx_communityforum_shortcut");
if (targetForum != null)
{
return GetNode(context, targetForum);
}
return null;
}
private static readonly Regex _notFoundServerRedirectPattern = new Regex(@"404;(?<ClientUrl>.*)$", RegexOptions.Compiled | RegexOptions.ExplicitCapture);
protected static UrlBuilder ExtractClientUrlFromRawUrl(string rawUrl)
{
var rawUrlBuilder = new UrlBuilder(rawUrl);
var notFoundServerRedirectMatch = _notFoundServerRedirectPattern.Match(rawUrl);
if (!notFoundServerRedirectMatch.Success)
{
return rawUrlBuilder;
}
var clientUrl = new UrlBuilder(notFoundServerRedirectMatch.Groups["ClientUrl"].Value);
if (!string.Equals(rawUrlBuilder.Host, clientUrl.Host, StringComparison.OrdinalIgnoreCase))
{
throw new SecurityException("rawUrl host {0} and server internal redirect URL host {1} do not match.".FormatWith(rawUrlBuilder.Host, clientUrl.Host));
}
return clientUrl;
}
protected static bool IsShortcutNode(SiteMapNode node)
{
var crmNode = node as CrmSiteMapNode;
return crmNode != null && crmNode.Entity != null && crmNode.Entity.LogicalName == "adx_shortcut";
}
/// <summary>
/// Gets whether the HttpContext page is "pageless", i.e. it's a route that doesn't exist in the sitemap.
/// ex: SignIn, Register pages. They are defined by MVC routes with property "pageless" = true.
/// </summary>
/// <param name="context">The HttpContext.</param>
/// <returns>Whether the context page is "pageless".</returns>
public static bool IsPageless(HttpContext context)
{
var wrappedContext = new HttpContextWrapper(context);
var routeData = RouteTable.Routes.GetRouteData(wrappedContext);
var pageless = routeData != null ? routeData.Values["pageless"] as bool? : null;
return pageless.GetValueOrDefault(false);
}
/// <summary>
/// Get the value of nonMVC flag from HttpContext/Route Data, if set
/// </summary>
/// <param name="context">Http Context</param>
/// <returns>Return nonMVC</returns>
public static bool IsNonMVC(HttpContext context)
{
var wrappedContext = new HttpContextWrapper(context);
var routeData = RouteTable.Routes.GetRouteData(wrappedContext);
var nonMVC = routeData != null ? routeData.Values["nonMVC"] as bool? : null;
return nonMVC.GetValueOrDefault(false);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.