context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal sealed partial class SolutionCrawlerRegistrationService
{
private sealed partial class WorkCoordinator
{
private sealed class SemanticChangeProcessor : IdleProcessor
{
private static readonly Func<int, DocumentId, bool, string> s_enqueueLogger = (t, i, b) => string.Format("[{0}] {1} - hint: {2}", t, i.ToString(), b);
private readonly SemaphoreSlim _gate;
private readonly Registration _registration;
private readonly ProjectProcessor _processor;
private readonly NonReentrantLock _workGate;
private readonly Dictionary<DocumentId, Data> _pendingWork;
public SemanticChangeProcessor(
IAsynchronousOperationListener listener,
Registration registration,
IncrementalAnalyzerProcessor documentWorkerProcessor,
int backOffTimeSpanInMS,
int projectBackOffTimeSpanInMS,
CancellationToken cancellationToken) :
base(listener, backOffTimeSpanInMS, cancellationToken)
{
_gate = new SemaphoreSlim(initialCount: 0);
_registration = registration;
_processor = new ProjectProcessor(listener, registration, documentWorkerProcessor, projectBackOffTimeSpanInMS, cancellationToken);
_workGate = new NonReentrantLock();
_pendingWork = new Dictionary<DocumentId, Data>();
Start();
}
public override Task AsyncProcessorTask
{
get
{
return Task.WhenAll(base.AsyncProcessorTask, _processor.AsyncProcessorTask);
}
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _gate.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
var data = Dequeue();
// we have a hint. check whether we can take advantage of it
if (await TryEnqueueFromHint(data.Document, data.ChangedMember).ConfigureAwait(continueOnCapturedContext: false))
{
data.AsyncToken.Dispose();
return;
}
EnqueueFullProjectDependency(data.Document);
data.AsyncToken.Dispose();
}
private Data Dequeue()
{
return DequeueWorker(_workGate, _pendingWork, this.CancellationToken);
}
private async Task<bool> TryEnqueueFromHint(Document document, SyntaxPath changedMember)
{
if (changedMember == null)
{
return false;
}
// see whether we already have semantic model. otherwise, use the expansive full project dependency one
// TODO: if there is a reliable way to track changed member, we could use GetSemanticModel here which could
// rebuild compilation from scratch
SemanticModel model;
SyntaxNode declarationNode;
if (!document.TryGetSemanticModel(out model) ||
!changedMember.TryResolve(await document.GetSyntaxRootAsync(this.CancellationToken).ConfigureAwait(false), out declarationNode))
{
return false;
}
var symbol = model.GetDeclaredSymbol(declarationNode, this.CancellationToken);
if (symbol == null)
{
return false;
}
return await TryEnqueueFromMemberAsync(document, symbol).ConfigureAwait(false) ||
await TryEnqueueFromTypeAsync(document, symbol).ConfigureAwait(false);
}
private async Task<bool> TryEnqueueFromTypeAsync(Document document, ISymbol symbol)
{
if (!IsType(symbol))
{
return false;
}
if (symbol.DeclaredAccessibility == Accessibility.Private)
{
await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false);
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromType, symbol.Name);
return true;
}
if (IsInternal(symbol))
{
var assembly = symbol.ContainingAssembly;
EnqueueFullProjectDependency(document, assembly);
return true;
}
return false;
}
private async Task<bool> TryEnqueueFromMemberAsync(Document document, ISymbol symbol)
{
if (!IsMember(symbol))
{
return false;
}
var typeSymbol = symbol.ContainingType;
if (symbol.DeclaredAccessibility == Accessibility.Private)
{
await EnqueueWorkItemAsync(document, symbol).ConfigureAwait(false);
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_EnqueueFromMember, symbol.Name);
return true;
}
if (typeSymbol == null)
{
return false;
}
return await TryEnqueueFromTypeAsync(document, typeSymbol).ConfigureAwait(false);
}
private Task EnqueueWorkItemAsync(Document document, ISymbol symbol)
{
return EnqueueWorkItemAsync(document, symbol.ContainingType != null ? symbol.ContainingType.Locations : symbol.Locations);
}
private async Task EnqueueWorkItemAsync(Document thisDocument, ImmutableArray<Location> locations)
{
var solution = thisDocument.Project.Solution;
var projectId = thisDocument.Id.ProjectId;
foreach (var location in locations)
{
Contract.Requires(location.IsInSource);
var document = solution.GetDocument(location.SourceTree, projectId);
Contract.Requires(document != null);
if (thisDocument == document)
{
continue;
}
await _processor.EnqueueWorkItemAsync(document).ConfigureAwait(false);
}
}
private bool IsInternal(ISymbol symbol)
{
return symbol.DeclaredAccessibility == Accessibility.Internal ||
symbol.DeclaredAccessibility == Accessibility.ProtectedAndInternal ||
symbol.DeclaredAccessibility == Accessibility.ProtectedOrInternal;
}
private bool IsType(ISymbol symbol)
{
return symbol.Kind == SymbolKind.NamedType;
}
private bool IsMember(ISymbol symbol)
{
return symbol.Kind == SymbolKind.Event ||
symbol.Kind == SymbolKind.Field ||
symbol.Kind == SymbolKind.Method ||
symbol.Kind == SymbolKind.Property;
}
private void EnqueueFullProjectDependency(Document document, IAssemblySymbol internalVisibleToAssembly = null)
{
var self = document.Project.Id;
// if there is no hint (this can happen for cases such as solution/project load and etc),
// we can postpone it even further
if (internalVisibleToAssembly == null)
{
_processor.Enqueue(self, needDependencyTracking: true);
return;
}
// most likely we got here since we are called due to typing.
// calculate dependency here and register each affected project to the next pipe line
var solution = document.Project.Solution;
var graph = solution.GetProjectDependencyGraph();
foreach (var projectId in graph.GetProjectsThatTransitivelyDependOnThisProject(self).Concat(self))
{
var project = solution.GetProject(projectId);
if (project == null)
{
continue;
}
Compilation compilation;
if (project.TryGetCompilation(out compilation))
{
var assembly = compilation.Assembly;
if (assembly != null && !assembly.IsSameAssemblyOrHasFriendAccessTo(internalVisibleToAssembly))
{
continue;
}
}
_processor.Enqueue(projectId);
}
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_FullProjects, internalVisibleToAssembly == null ? "full" : "internals");
}
public void Enqueue(Document document, SyntaxPath changedMember)
{
this.UpdateLastAccessTime();
using (_workGate.DisposableWait(this.CancellationToken))
{
Data data;
if (_pendingWork.TryGetValue(document.Id, out data))
{
// create new async token and dispose old one.
var newAsyncToken = this.Listener.BeginAsyncOperation("EnqueueSemanticChange");
data.AsyncToken.Dispose();
_pendingWork[document.Id] = new Data(document, data.ChangedMember == changedMember ? changedMember : null, newAsyncToken);
return;
}
_pendingWork.Add(document.Id, new Data(document, changedMember, this.Listener.BeginAsyncOperation("EnqueueSemanticChange")));
_gate.Release();
}
Logger.Log(FunctionId.WorkCoordinator_SemanticChange_Enqueue, s_enqueueLogger, Environment.TickCount, document.Id, changedMember != null);
}
private static TValue DequeueWorker<TKey, TValue>(NonReentrantLock gate, Dictionary<TKey, TValue> map, CancellationToken cancellationToken)
{
using (gate.DisposableWait(cancellationToken))
{
var first = default(KeyValuePair<TKey, TValue>);
foreach (var kv in map)
{
first = kv;
break;
}
// this is only one that removes data from the queue. so, it should always succeed
var result = map.Remove(first.Key);
Contract.Requires(result);
return first.Value;
}
}
private struct Data
{
public readonly Document Document;
public readonly SyntaxPath ChangedMember;
public readonly IAsyncToken AsyncToken;
public Data(Document document, SyntaxPath changedMember, IAsyncToken asyncToken)
{
this.AsyncToken = asyncToken;
this.Document = document;
this.ChangedMember = changedMember;
}
}
private class ProjectProcessor : IdleProcessor
{
private static readonly Func<int, ProjectId, string> s_enqueueLogger = (t, i) => string.Format("[{0}] {1}", t, i.ToString());
private readonly SemaphoreSlim _gate;
private readonly Registration _registration;
private readonly IncrementalAnalyzerProcessor _processor;
private readonly NonReentrantLock _workGate;
private readonly Dictionary<ProjectId, Data> _pendingWork;
public ProjectProcessor(
IAsynchronousOperationListener listener,
Registration registration,
IncrementalAnalyzerProcessor processor,
int backOffTimeSpanInMS,
CancellationToken cancellationToken) :
base(listener, backOffTimeSpanInMS, cancellationToken)
{
_registration = registration;
_processor = processor;
_gate = new SemaphoreSlim(initialCount: 0);
_workGate = new NonReentrantLock();
_pendingWork = new Dictionary<ProjectId, Data>();
Start();
}
public void Enqueue(ProjectId projectId, bool needDependencyTracking = false)
{
this.UpdateLastAccessTime();
using (_workGate.DisposableWait(this.CancellationToken))
{
// the project is already in the queue. nothing needs to be done
if (_pendingWork.ContainsKey(projectId))
{
return;
}
var data = new Data(projectId, needDependencyTracking, this.Listener.BeginAsyncOperation("EnqueueWorkItemForSemanticChangeAsync"));
_pendingWork.Add(projectId, data);
_gate.Release();
}
Logger.Log(FunctionId.WorkCoordinator_Project_Enqueue, s_enqueueLogger, Environment.TickCount, projectId);
}
public async Task EnqueueWorkItemAsync(Document document)
{
// we are shutting down
this.CancellationToken.ThrowIfCancellationRequested();
// call to this method is serialized. and only this method does the writing.
var priorityService = document.GetLanguageService<IWorkCoordinatorPriorityService>();
var isLowPriority = priorityService != null && await priorityService.IsLowPriorityAsync(document, this.CancellationToken).ConfigureAwait(false);
_processor.Enqueue(
new WorkItem(document.Id, document.Project.Language, InvocationReasons.SemanticChanged,
isLowPriority, this.Listener.BeginAsyncOperation("Semantic WorkItem")));
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _gate.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
var data = Dequeue();
using (data.AsyncToken)
{
var project = _registration.CurrentSolution.GetProject(data.ProjectId);
if (project == null)
{
return;
}
if (!data.NeedDependencyTracking)
{
await EnqueueWorkItemAsync(project).ConfigureAwait(false);
return;
}
// do dependency tracking here with current solution
var solution = _registration.CurrentSolution;
var graph = solution.GetProjectDependencyGraph();
foreach (var projectId in graph.GetProjectsThatTransitivelyDependOnThisProject(data.ProjectId).Concat(data.ProjectId))
{
project = solution.GetProject(projectId);
await EnqueueWorkItemAsync(project).ConfigureAwait(false);
}
}
}
private Data Dequeue()
{
return DequeueWorker(_workGate, _pendingWork, this.CancellationToken);
}
private async Task EnqueueWorkItemAsync(Project project)
{
if (project == null)
{
return;
}
foreach (var documentId in project.DocumentIds)
{
await EnqueueWorkItemAsync(project.GetDocument(documentId)).ConfigureAwait(false);
}
}
private struct Data
{
public readonly IAsyncToken AsyncToken;
public readonly ProjectId ProjectId;
public readonly bool NeedDependencyTracking;
public Data(ProjectId projectId, bool needDependencyTracking, IAsyncToken asyncToken)
{
this.AsyncToken = asyncToken;
this.ProjectId = projectId;
this.NeedDependencyTracking = needDependencyTracking;
}
}
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using Interop.VixCOM;
namespace Vestris.VMWareLib
{
/// <summary>
/// A collection of shared folders.
/// Shared folders will only be accessible inside the guest operating system if shared folders are
/// enabled for the virtual machine.
/// </summary>
public class VMWareSharedFolderCollection :
ICollection<VMWareSharedFolder>, IEnumerable<VMWareSharedFolder>, IDisposable
{
private IVM _vm = null;
private List<VMWareSharedFolder> _sharedFolders = null;
/// <summary>
/// A collection of shared folders that belong to a virtual machine.
/// </summary>
/// <param name="vm">Virtual machine.</param>
public VMWareSharedFolderCollection(IVM vm)
{
_vm = vm;
}
/// <summary>
/// Add (create) a shared folder.
/// </summary>
/// <param name="sharedFolder">The shared folder to add.</param>
public void Add(VMWareSharedFolder sharedFolder)
{
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_vm.AddSharedFolder(
sharedFolder.ShareName, sharedFolder.HostPath, sharedFolder.Flags, callback),
callback))
{
job.Wait(VMWareInterop.Timeouts.AddRemoveSharedFolderTimeout);
}
_sharedFolders = null;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to add shared folder: shareName=\"{0}\" hostPath=\"{1}\" flags={2}",
sharedFolder.ShareName, sharedFolder.HostPath, sharedFolder.Flags), ex);
}
}
/// <summary>
/// Get shared folders.
/// </summary>
/// <returns>A list of shared folders.</returns>
private List<VMWareSharedFolder> SharedFolders
{
get
{
if (_sharedFolders == null)
{
try
{
List<VMWareSharedFolder> sharedFolders = new List<VMWareSharedFolder>();
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_vm.GetNumSharedFolders(callback), callback))
{
int nSharedFolders = job.Wait<int>(
Constants.VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_COUNT,
VMWareInterop.Timeouts.GetSharedFoldersTimeout);
for (int i = 0; i < nSharedFolders; i++)
{
VMWareJobCallback getSharedfolderCallback = new VMWareJobCallback();
using (VMWareJob sharedFolderJob = new VMWareJob(
_vm.GetSharedFolderState(i, getSharedfolderCallback),
getSharedfolderCallback))
{
object[] sharedFolderProperties = {
Constants.VIX_PROPERTY_JOB_RESULT_ITEM_NAME,
Constants.VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_HOST,
Constants.VIX_PROPERTY_JOB_RESULT_SHARED_FOLDER_FLAGS
};
object[] sharedFolderPropertyValues = sharedFolderJob.Wait<object[]>(
sharedFolderProperties, VMWareInterop.Timeouts.GetSharedFoldersTimeout);
VMWareSharedFolder sharedFolder = new VMWareSharedFolder(
(string)sharedFolderPropertyValues[0],
(string)sharedFolderPropertyValues[1],
(int)sharedFolderPropertyValues[2]);
sharedFolders.Add(sharedFolder);
}
}
}
_sharedFolders = sharedFolders;
}
catch (Exception ex)
{
throw new Exception("Failed to get shared folders", ex);
}
}
return _sharedFolders;
}
}
/// <summary>
/// Delete all shared folders.
/// </summary>
public void Clear()
{
while (SharedFolders.Count > 0)
{
Remove(SharedFolders[0]);
}
}
/// <summary>
/// A function to copy shared folder objects between arrays.
/// Don't use externally.
/// </summary>
/// <param name="array">Target array.</param>
/// <param name="arrayIndex">Array index.</param>
public void CopyTo(VMWareSharedFolder[] array, int arrayIndex)
{
SharedFolders.CopyTo(array, arrayIndex);
}
/// <summary>
/// Returns true if this virtual machine has the folder specified.
/// </summary>
/// <param name="item">Shared folder.</param>
/// <returns>True if the virtual machine contains the specified shared folder.</returns>
public bool Contains(VMWareSharedFolder item)
{
return SharedFolders.Contains(item);
}
/// <summary>
/// Delete a shared folder.
/// </summary>
/// <param name="item">Shared folder to delete.</param>
/// <returns>True if the folder was deleted.</returns>
public bool Remove(VMWareSharedFolder item)
{
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_vm.RemoveSharedFolder(
item.ShareName, 0, callback),
callback))
{
job.Wait(VMWareInterop.Timeouts.AddRemoveSharedFolderTimeout);
}
return SharedFolders.Remove(item);
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to remove shared folder: shareName=\"{0}\"",
item.ShareName), ex);
}
}
/// <summary>
/// Number of shared folders.
/// </summary>
public int Count
{
get
{
return SharedFolders.Count;
}
}
/// <summary>
/// Returns true if the collection is read-only.
/// Shared folder collections are never read-only.
/// </summary>
public bool IsReadOnly
{
get
{
return false;
}
}
/// <summary>
/// A shared folder enumerator.
/// </summary>
/// <returns>Shared folders enumerator.</returns>
IEnumerator<VMWareSharedFolder> IEnumerable<VMWareSharedFolder>.GetEnumerator()
{
return SharedFolders.GetEnumerator();
}
/// <summary>
/// A shared folder enumerator.
/// </summary>
/// <returns>Shared folders enumerator.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return SharedFolders.GetEnumerator();
}
/// <summary>
/// Enable/disable all shared folders as a feature on a virtual machine.
/// </summary>
public bool Enabled
{
set
{
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_vm.EnableSharedFolders(value, 0, callback), callback))
{
job.Wait(VMWareInterop.Timeouts.EnableSharedFoldersTimeout);
}
_sharedFolders = null;
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to {0} shared folders",
(value == true) ? "enable" : "disable"), ex);
}
}
}
/// <summary>
/// Returns a shared folder at a given index.
/// </summary>
/// <param name="index">Shared folder index.</param>
/// <returns>A shared folder.</returns>
public VMWareSharedFolder this[int index]
{
get
{
return SharedFolders[index];
}
}
/// <summary>
/// Changes state of shared folder.
/// </summary>
/// <param name="sharedFolder">The shared folder to change state.</param>
/// <param name="flags">New state.</param>
public void SetState(VMWareSharedFolder sharedFolder, int flags)
{
try
{
VMWareJobCallback callback = new VMWareJobCallback();
using (VMWareJob job = new VMWareJob(_vm.SetSharedFolderState(
sharedFolder.ShareName, sharedFolder.HostPath, flags, callback),
callback))
{
job.Wait(VMWareInterop.Timeouts.GetSharedFoldersTimeout);
}
}
catch (Exception ex)
{
throw new Exception(
string.Format("Failed to set shared folder state: shareName=\"{0}\" hostPath=\"{1}\" flags={2}",
sharedFolder.ShareName, sharedFolder.HostPath, flags), ex);
}
}
/// <summary>
/// Dispose the object.
/// </summary>
public void Dispose()
{
_sharedFolders = null;
_vm = null;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using NodaTime;
using QuantConnect.Data;
using QuantConnect.Data.Market;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Securities;
using QuantConnect.Securities.Option;
namespace QuantConnect.Lean.Engine.DataFeeds
{
/// <summary>
/// Represents a grouping of data emitted at a certain time.
/// </summary>
public class TimeSlice
{
/// <summary>
/// Gets the count of data points in this <see cref="TimeSlice"/>
/// </summary>
public int DataPointCount { get; private set; }
/// <summary>
/// Gets the time this data was emitted
/// </summary>
public DateTime Time { get; private set; }
/// <summary>
/// Gets the data in the time slice
/// </summary>
public List<DataFeedPacket> Data { get; private set; }
/// <summary>
/// Gets the <see cref="Slice"/> that will be used as input for the algorithm
/// </summary>
public Slice Slice { get; private set; }
/// <summary>
/// Gets the data used to update the cash book
/// </summary>
public List<UpdateData<Cash>> CashBookUpdateData { get; private set; }
/// <summary>
/// Gets the data used to update securities
/// </summary>
public List<UpdateData<Security>> SecuritiesUpdateData { get; private set; }
/// <summary>
/// Gets the data used to update the consolidators
/// </summary>
public List<UpdateData<SubscriptionDataConfig>> ConsolidatorUpdateData { get; private set; }
/// <summary>
/// Gets all the custom data in this <see cref="TimeSlice"/>
/// </summary>
public List<UpdateData<Security>> CustomData { get; private set; }
/// <summary>
/// Gets the changes to the data subscriptions as a result of universe selection
/// </summary>
public SecurityChanges SecurityChanges { get; set; }
/// <summary>
/// Initializes a new <see cref="TimeSlice"/> containing the specified data
/// </summary>
public TimeSlice(DateTime time,
int dataPointCount,
Slice slice,
List<DataFeedPacket> data,
List<UpdateData<Cash>> cashBookUpdateData,
List<UpdateData<Security>> securitiesUpdateData,
List<UpdateData<SubscriptionDataConfig>> consolidatorUpdateData,
List<UpdateData<Security>> customData,
SecurityChanges securityChanges)
{
Time = time;
Data = data;
Slice = slice;
CustomData = customData;
DataPointCount = dataPointCount;
CashBookUpdateData = cashBookUpdateData;
SecuritiesUpdateData = securitiesUpdateData;
ConsolidatorUpdateData = consolidatorUpdateData;
SecurityChanges = securityChanges;
}
/// <summary>
/// Creates a new <see cref="TimeSlice"/> for the specified time using the specified data
/// </summary>
/// <param name="utcDateTime">The UTC frontier date time</param>
/// <param name="algorithmTimeZone">The algorithm's time zone, required for computing algorithm and slice time</param>
/// <param name="cashBook">The algorithm's cash book, required for generating cash update pairs</param>
/// <param name="data">The data in this <see cref="TimeSlice"/></param>
/// <param name="changes">The new changes that are seen in this time slice as a result of universe selection</param>
/// <returns>A new <see cref="TimeSlice"/> containing the specified data</returns>
public static TimeSlice Create(DateTime utcDateTime, DateTimeZone algorithmTimeZone, CashBook cashBook, List<DataFeedPacket> data, SecurityChanges changes)
{
int count = 0;
var security = new List<UpdateData<Security>>();
var custom = new List<UpdateData<Security>>();
var consolidator = new List<UpdateData<SubscriptionDataConfig>>();
var allDataForAlgorithm = new List<BaseData>(data.Count);
var cash = new List<UpdateData<Cash>>(cashBook.Count);
var cashSecurities = new HashSet<Symbol>();
foreach (var cashItem in cashBook.Values)
{
cashSecurities.Add(cashItem.SecuritySymbol);
}
Split split;
Dividend dividend;
Delisting delisting;
SymbolChangedEvent symbolChange;
// we need to be able to reference the slice being created in order to define the
// evaluation of option price models, so we define a 'future' that can be referenced
// in the option price model evaluation delegates for each contract
Slice slice = null;
var sliceFuture = new Lazy<Slice>(() => slice);
var algorithmTime = utcDateTime.ConvertFromUtc(algorithmTimeZone);
var tradeBars = new TradeBars(algorithmTime);
var quoteBars = new QuoteBars(algorithmTime);
var ticks = new Ticks(algorithmTime);
var splits = new Splits(algorithmTime);
var dividends = new Dividends(algorithmTime);
var delistings = new Delistings(algorithmTime);
var optionChains = new OptionChains(algorithmTime);
var symbolChanges = new SymbolChangedEvents(algorithmTime);
foreach (var packet in data)
{
var list = packet.Data;
var symbol = packet.Security.Symbol;
if (list.Count == 0) continue;
// keep count of all data points
if (list.Count == 1 && list[0] is BaseDataCollection)
{
var baseDataCollectionCount = ((BaseDataCollection)list[0]).Data.Count;
if (baseDataCollectionCount == 0)
{
continue;
}
count += baseDataCollectionCount;
}
else
{
count += list.Count;
}
if (!packet.Configuration.IsInternalFeed && packet.Configuration.IsCustomData)
{
// This is all the custom data
custom.Add(new UpdateData<Security>(packet.Security, packet.Configuration.Type, list));
}
var securityUpdate = new List<BaseData>(list.Count);
var consolidatorUpdate = new List<BaseData>(list.Count);
for (int i = 0; i < list.Count; i++)
{
var baseData = list[i];
if (!packet.Configuration.IsInternalFeed)
{
// this is all the data that goes into the algorithm
allDataForAlgorithm.Add(baseData);
}
// don't add internal feed data to ticks/bars objects
if (baseData.DataType != MarketDataType.Auxiliary)
{
if (!packet.Configuration.IsInternalFeed)
{
PopulateDataDictionaries(baseData, ticks, tradeBars, quoteBars, optionChains);
// special handling of options data to build the option chain
if (packet.Security.Type == SecurityType.Option)
{
if (baseData.DataType == MarketDataType.OptionChain)
{
optionChains[baseData.Symbol] = (OptionChain) baseData;
}
else if (!HandleOptionData(algorithmTime, baseData, optionChains, packet.Security, sliceFuture))
{
continue;
}
}
// this is data used to update consolidators
consolidatorUpdate.Add(baseData);
}
// this is the data used set market prices
securityUpdate.Add(baseData);
}
// include checks for various aux types so we don't have to construct the dictionaries in Slice
else if ((delisting = baseData as Delisting) != null)
{
delistings[symbol] = delisting;
}
else if ((dividend = baseData as Dividend) != null)
{
dividends[symbol] = dividend;
}
else if ((split = baseData as Split) != null)
{
splits[symbol] = split;
}
else if ((symbolChange = baseData as SymbolChangedEvent) != null)
{
// symbol changes is keyed by the requested symbol
symbolChanges[packet.Configuration.Symbol] = symbolChange;
}
}
if (securityUpdate.Count > 0)
{
// check for 'cash securities' if we found valid update data for this symbol
// and we need this data to update cash conversion rates, long term we should
// have Cash hold onto it's security, then he can update himself, or rather, just
// patch through calls to conversion rate to compue it on the fly using Security.Price
if (cashSecurities.Contains(packet.Security.Symbol))
{
foreach (var cashKvp in cashBook)
{
if (cashKvp.Value.SecuritySymbol == packet.Security.Symbol)
{
var cashUpdates = new List<BaseData> {securityUpdate[securityUpdate.Count - 1]};
cash.Add(new UpdateData<Cash>(cashKvp.Value, packet.Configuration.Type, cashUpdates));
}
}
}
security.Add(new UpdateData<Security>(packet.Security, packet.Configuration.Type, securityUpdate));
}
if (consolidatorUpdate.Count > 0)
{
consolidator.Add(new UpdateData<SubscriptionDataConfig>(packet.Configuration, packet.Configuration.Type, consolidatorUpdate));
}
}
slice = new Slice(algorithmTime, allDataForAlgorithm, tradeBars, quoteBars, ticks, optionChains, splits, dividends, delistings, symbolChanges, allDataForAlgorithm.Count > 0);
return new TimeSlice(utcDateTime, count, slice, data, cash, security, consolidator, custom, changes);
}
/// <summary>
/// Adds the specified <see cref="BaseData"/> instance to the appropriate <see cref="DataDictionary{T}"/>
/// </summary>
private static void PopulateDataDictionaries(BaseData baseData, Ticks ticks, TradeBars tradeBars, QuoteBars quoteBars, OptionChains optionChains)
{
var symbol = baseData.Symbol;
// populate data dictionaries
switch (baseData.DataType)
{
case MarketDataType.Tick:
ticks.Add(symbol, (Tick)baseData);
break;
case MarketDataType.TradeBar:
tradeBars[symbol] = (TradeBar) baseData;
break;
case MarketDataType.QuoteBar:
quoteBars[symbol] = (QuoteBar) baseData;
break;
case MarketDataType.OptionChain:
optionChains[symbol] = (OptionChain) baseData;
break;
}
}
private static bool HandleOptionData(DateTime algorithmTime, BaseData baseData, OptionChains optionChains, Security security, Lazy<Slice> sliceFuture)
{
var symbol = baseData.Symbol;
OptionChain chain;
var canonical = Symbol.Create(symbol.ID.Symbol, SecurityType.Option, symbol.ID.Market);
if (!optionChains.TryGetValue(canonical, out chain))
{
chain = new OptionChain(canonical, algorithmTime);
optionChains[canonical] = chain;
}
var universeData = baseData as OptionChainUniverseDataCollection;
if (universeData != null)
{
if (universeData.Underlying != null)
{
chain.Underlying = universeData.Underlying;
}
foreach (var contractSymbol in universeData.FilteredContracts)
{
chain.FilteredContracts.Add(contractSymbol);
}
return false;
}
OptionContract contract;
if (!chain.Contracts.TryGetValue(baseData.Symbol, out contract))
{
var underlyingSymbol = Symbol.Create(baseData.Symbol.ID.Symbol, SecurityType.Equity, baseData.Symbol.ID.Market);
contract = new OptionContract(baseData.Symbol, underlyingSymbol)
{
Time = baseData.EndTime,
LastPrice = security.Close,
BidPrice = security.BidPrice,
BidSize = security.BidSize,
AskPrice = security.AskPrice,
AskSize = security.AskSize,
UnderlyingLastPrice = chain.Underlying != null ? chain.Underlying.Price : 0m
};
chain.Contracts[baseData.Symbol] = contract;
var option = security as Option;
if (option != null)
{
contract.SetOptionPriceModel(() => option.PriceModel.Evaluate(option, sliceFuture.Value, contract));
}
}
// populate ticks and tradebars dictionaries with no aux data
switch (baseData.DataType)
{
case MarketDataType.Tick:
var tick = (Tick)baseData;
chain.Ticks.Add(tick.Symbol, tick);
UpdateContract(contract, tick);
break;
case MarketDataType.TradeBar:
var tradeBar = (TradeBar)baseData;
chain.TradeBars[symbol] = tradeBar;
contract.LastPrice = tradeBar.Close;
break;
case MarketDataType.QuoteBar:
var quote = (QuoteBar)baseData;
chain.QuoteBars[symbol] = quote;
UpdateContract(contract, quote);
break;
case MarketDataType.Base:
chain.AddAuxData(baseData);
break;
}
return true;
}
private static void UpdateContract(OptionContract contract, QuoteBar quote)
{
if (quote.Ask != null && quote.Ask.Close != 0m)
{
contract.AskPrice = quote.Ask.Close;
contract.AskSize = quote.LastAskSize;
}
if (quote.Bid != null && quote.Bid.Close != 0m)
{
contract.BidPrice = quote.Bid.Close;
contract.BidSize = quote.LastBidSize;
}
}
private static void UpdateContract(OptionContract contract, Tick tick)
{
if (tick.TickType == TickType.Trade)
{
contract.LastPrice = tick.Price;
}
else if (tick.TickType == TickType.Quote)
{
if (tick.AskPrice != 0m)
{
contract.AskPrice = tick.AskPrice;
contract.AskSize = tick.AskSize;
}
if (tick.BidPrice != 0m)
{
contract.BidPrice = tick.BidPrice;
contract.BidSize = tick.BidSize;
}
}
}
}
}
| |
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Logging.Logging
File: LogManager.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Logging
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Configuration;
using Ecng.Serialization;
using MoreLinq;
using StockSharp.Localization;
/// <summary>
/// Messages logging manager that monitors the <see cref="ILogSource.Log"/> event and forwards messages to the <see cref="LogManager.Listeners"/>.
/// </summary>
public class LogManager : Disposable, IPersistable
{
private static readonly MemoryStatisticsValue<LogMessage> _logMsgStat = new(LocalizedStrings.MessageLog);
static LogManager()
{
MemoryStatistics.Instance.Values.Add(_logMsgStat);
}
private sealed class ApplicationReceiver : BaseLogReceiver
{
public ApplicationReceiver()
{
Name = ConfigManager.TryGet("appName", TypeHelper.ApplicationName);
LogLevel = LogLevels.Info;
}
}
private sealed class LogSourceList : BaseList<ILogSource>
{
private readonly LogManager _parent;
public LogSourceList(LogManager parent)
{
_parent = parent ?? throw new ArgumentNullException(nameof(parent));
}
protected override bool OnAdding(ILogSource item)
{
item.Log += _parent.SourceLog;
return base.OnAdding(item);
}
protected override bool OnRemoving(ILogSource item)
{
item.Log -= _parent.SourceLog;
return base.OnRemoving(item);
}
protected override bool OnClearing()
{
foreach (var item in this)
OnRemoving(item);
return base.OnClearing();
}
}
private sealed class DisposeLogMessage : LogMessage
{
private readonly SyncObject _syncRoot = new();
public DisposeLogMessage()
: base(new ApplicationReceiver(), DateTimeOffset.MinValue, LogLevels.Off, string.Empty)
{
IsDispose = true;
}
public void Wait()
{
_syncRoot.WaitSignal();
}
public void Pulse()
{
_syncRoot.PulseSignal();
}
}
private static readonly DisposeLogMessage _disposeMessage = new();
private readonly object _syncRoot = new();
private readonly List<LogMessage> _pendingMessages = new();
private readonly Timer _flushTimer;
private bool _isFlusing;
private readonly bool _asyncMode;
/// <summary>
/// Instance.
/// </summary>
public static LogManager Instance => ConfigManager.TryGetService<LogManager>();
/// <summary>
/// Initializes a new instance of the <see cref="LogManager"/>.
/// </summary>
public LogManager()
: this(true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="LogManager"/>.
/// </summary>
/// <param name="asyncMode">Asynchronous mode.</param>
public LogManager(bool asyncMode)
{
ConfigManager.TryRegisterService(this);
Sources = new LogSourceList(this)
{
Application,
new UnhandledExceptionSource()
};
_asyncMode = asyncMode;
if (!_asyncMode)
return;
_flushTimer = ThreadingHelper.Timer(Flush);
FlushInterval = TimeSpan.FromMilliseconds(500);
}
/// <summary>
/// Local time zone to convert all incoming messages. Not use in case of <see langword="null"/>.
/// </summary>
public TimeZoneInfo LocalTimeZone { get; set; }
private void Flush()
{
LogMessage[] temp;
lock (_syncRoot)
{
if (_isFlusing)
return;
temp = _pendingMessages.CopyAndClear();
if (temp.Length == 0)
return;
_isFlusing = true;
}
_logMsgStat.Remove(temp);
try
{
var messages = new List<LogMessage>();
DisposeLogMessage disposeMessage = null;
ILogSource prevSource = null;
var level = default(LogLevels);
foreach (var message in temp)
{
if (prevSource == null || prevSource != message.Source)
{
prevSource = message.Source;
level = prevSource.GetLogLevel();
}
if (level == LogLevels.Inherit)
level = Application.LogLevel;
if (level <= message.Level)
messages.Add(message);
if (message.IsDispose)
disposeMessage = (DisposeLogMessage)message;
else if (LocalTimeZone != null)
message.Time = message.Time.Convert(LocalTimeZone);
}
if (messages.Count > 0)
_listeners.Cache.ForEach(l => l.WriteMessages(messages));
disposeMessage?.Pulse();
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
finally
{
lock (_syncRoot)
_isFlusing = false;
}
}
private ILogReceiver _application = new ApplicationReceiver();
/// <summary>
/// The all application level logs recipient.
/// </summary>
public ILogReceiver Application
{
get => _application;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (value == _application)
return;
Sources.Remove(_application);
_application = value;
Sources.Add(_application);
}
}
private readonly CachedSynchronizedSet<ILogListener> _listeners = new(true);
/// <summary>
/// Messages loggers arriving from <see cref="Sources"/>.
/// </summary>
public IList<ILogListener> Listeners => _listeners;
/// <summary>
/// Logs sources which are listened to the event <see cref="ILogSource.Log"/>.
/// </summary>
public IList<ILogSource> Sources { get; }
/// <summary>
/// Sending interval of messages collected from <see cref="Sources"/> to the <see cref="Listeners"/>. The default is 500 ms.
/// </summary>
public TimeSpan FlushInterval
{
get => _flushTimer?.Interval() ?? TimeSpan.MaxValue;
set
{
if (!_asyncMode)
return;
if (value < TimeSpan.FromMilliseconds(1))
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.IntervalMustBePositive);
_flushTimer.Interval(value);
}
}
private void SourceLog(LogMessage message)
{
if (message == null)
throw new ArgumentNullException(nameof(message));
_logMsgStat.Add(message);
lock (_syncRoot)
{
_pendingMessages.Add(message);
if (!_asyncMode)
Flush();
else
{
// mika: force flush in case too many messages
if (_pendingMessages.Count > 1000000)
ImmediateFlush();
}
}
}
private void ImmediateFlush()
{
_flushTimer.Change(TimeSpan.Zero, FlushInterval);
}
/// <summary>
/// Clear pending messages on dispose.
/// </summary>
public bool ClearPendingOnDispose { get; set; } = true;
/// <summary>
/// Release resources.
/// </summary>
protected override void DisposeManaged()
{
Sources.Clear();
if (_asyncMode)
{
lock (_syncRoot)
{
if (ClearPendingOnDispose)
_pendingMessages.Clear();
_pendingMessages.Add(_disposeMessage);
}
// flushing accumulated messages and closing the timer
ImmediateFlush();
_disposeMessage.Wait();
_flushTimer.Dispose();
}
base.DisposeManaged();
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public virtual void Load(SettingsStorage storage)
{
FlushInterval = storage.GetValue<TimeSpan>(nameof(FlushInterval));
//MaxMessageCount = storage.GetValue<int>(nameof(MaxMessageCount));
Listeners.AddRange(storage.GetValue<IEnumerable<SettingsStorage>>(nameof(Listeners)).Select(s => s.LoadEntire<ILogListener>()));
if (storage.Contains(nameof(LocalTimeZone)))
LocalTimeZone = storage.GetValue<TimeZoneInfo>(nameof(LocalTimeZone));
if (storage.Contains(nameof(Application)) && Application is IPersistable appPers)
appPers.Load(storage.GetValue<SettingsStorage>(nameof(Application)));
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public virtual void Save(SettingsStorage storage)
{
storage.SetValue(nameof(FlushInterval), FlushInterval);
//storage.SetValue(nameof(MaxMessageCount), MaxMessageCount);
storage.SetValue(nameof(Listeners), Listeners.Select(l => l.SaveEntire(false)).ToArray());
if (LocalTimeZone != null)
storage.SetValue(nameof(LocalTimeZone), LocalTimeZone);
if (Application is IPersistable appPers)
storage.SetValue(nameof(Application), appPers.Save());
}
}
}
| |
//
// $Id: ChromatogramListForm.cs 2322 2010-10-21 22:15:34Z chambm $
//
//
// Original author: Matt Chambers <matt.chambers .@. vanderbilt.edu>
//
// Copyright 2009 Vanderbilt University - Nashville, TN 37232
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DigitalRune.Windows.Docking;
using pwiz.CLI.cv;
using pwiz.CLI.data;
using pwiz.CLI.msdata;
using pwiz.CLI.analysis;
using seems.Misc;
namespace seems
{
public delegate void ChromatogramListCellClickHandler( object sender, ChromatogramListCellClickEventArgs e );
public delegate void ChromatogramListCellDoubleClickHandler( object sender, ChromatogramListCellDoubleClickEventArgs e );
public delegate void ChromatogramListFilterChangedHandler( object sender, ChromatogramListFilterChangedEventArgs e );
public partial class ChromatogramListForm : DockableForm
{
Dictionary<int, Chromatogram> chromatogramList; // indexable by Chromatogram.Index
public DataGridView GridView { get { return gridView; } }
public event ChromatogramListCellClickHandler CellClick;
public event ChromatogramListCellDoubleClickHandler CellDoubleClick;
public event ChromatogramListFilterChangedHandler FilterChanged;
protected void OnCellClick( DataGridViewCellMouseEventArgs e )
{
if( CellClick != null )
CellClick( this, new ChromatogramListCellClickEventArgs( this, e ) );
}
protected void OnCellDoubleClick( DataGridViewCellMouseEventArgs e )
{
if( CellDoubleClick != null )
CellDoubleClick( this, new ChromatogramListCellDoubleClickEventArgs( this, e ) );
}
protected void OnFilterChanged()
{
if( FilterChanged != null )
FilterChanged( this, new ChromatogramListFilterChangedEventArgs( this, chromatogramDataSet ) );
}
public ChromatogramListForm()
{
InitializeComponent();
initializeGridView();
}
private void initializeGridView()
{
// force handle creation
IntPtr dummy = gridView.Handle;
chromatogramList = new Dictionary<int, Chromatogram>();
typeDataGridViewTextBoxColumn.ToolTipText = new CVTermInfo( CVID.MS_chromatogram_type ).def;
}
private void gridView_DataBindingComplete( object sender, DataGridViewBindingCompleteEventArgs e )
{
if( e.ListChangedType == ListChangedType.Reset )
OnFilterChanged();
}
public void updateRow( ChromatogramDataSet.ChromatogramTableRow row, Chromatogram chromatogram )
{
chromatogramList[chromatogram.Index] = chromatogram;
pwiz.CLI.msdata.Chromatogram c = chromatogram.Element;
DataProcessing dp = chromatogram.DataProcessing;
if( dp == null )
dp = c.dataProcessing;
row.Type = c.cvParamChild( CVID.MS_chromatogram_type ).name;
row.DataPoints = c.defaultArrayLength;
row.DpId = ( dp == null || dp.id.Length == 0 ? "unknown" : dp.id );
}
public void Add( Chromatogram chromatogram )
{
ChromatogramDataSet.ChromatogramTableRow row = chromatogramDataSet.ChromatogramTable.NewChromatogramTableRow();
row.Id = chromatogram.Id;
/*if( nativeIdFormat != CVID.CVID_Unknown )
{
gridView.Columns["Id"].Visible = false;
string[] nameValuePairs = chromatogram.Id.Split( " ".ToCharArray() );
foreach( string nvp in nameValuePairs )
{
string[] nameValuePair = nvp.Split( "=".ToCharArray() );
row[nameValuePair[0]] = nameValuePair[1];
}
}*/
row.Index = chromatogram.Index;
updateRow( row, chromatogram );
chromatogramDataSet.ChromatogramTable.AddChromatogramTableRow( row );
//int rowIndex = gridView.Rows.Add();
//gridView.Rows[rowIndex].Tag = chromatogram;
chromatogram.Tag = this;
//UpdateRow( rowIndex );
}
public int IndexOf( Chromatogram chromatogram )
{
return chromatogramBindingSource.Find( "Index", chromatogram.Index );
}
public Chromatogram GetChromatogram( int index )
{
return chromatogramList[(int) ( chromatogramBindingSource[index] as DataRowView )[1]];
}
public void UpdateAllRows()
{
for( int i = 0; i < gridView.RowCount; ++i )
UpdateRow( i );
}
public void UpdateRow( int rowIndex )
{
UpdateRow( rowIndex, null );
}
public void UpdateRow( int rowIndex, ChromatogramList chromatogramList )
{
ChromatogramDataSet.ChromatogramTableRow row = ( chromatogramBindingSource[rowIndex] as DataRowView ).Row as ChromatogramDataSet.ChromatogramTableRow;
if( chromatogramList != null )
{
this.chromatogramList[row.Index].ChromatogramList = chromatogramList;
updateRow( row, this.chromatogramList[row.Index] );
//dp = rowChromatogram.DataProcessing;
//row.Tag = rowChromatogram = new Chromatogram( rowChromatogram, s );
//rowChromatogram.DataProcessing = dp;
} else
{
updateRow( row, this.chromatogramList[row.Index] );
//s = rowChromatogram.Element;
//dp = rowChromatogram.DataProcessing;
}
}
private void gridView_CellMouseClick( object sender, DataGridViewCellMouseEventArgs e )
{
//if( e.RowIndex > -1 && gridView.Columns[e.ColumnIndex] is DataGridViewLinkColumn )
// gridView_ShowCellToolTip( gridView[e.ColumnIndex, e.RowIndex] );
OnCellClick( e );
}
private void gridView_CellMouseDoubleClick( object sender, DataGridViewCellMouseEventArgs e )
{
OnCellDoubleClick( e );
}
private void selectColumnsToolStripMenuItem_Click( object sender, EventArgs e )
{
}
private void gridView_ColumnHeaderMouseClick( object sender, DataGridViewCellMouseEventArgs e )
{
if( e.Button == MouseButtons.Right )
{
Rectangle cellRectangle = gridView.GetCellDisplayRectangle( e.ColumnIndex, e.RowIndex, true );
Point cellLocation = new Point( cellRectangle.Left, cellRectangle.Top );
cellLocation.Offset( e.Location );
selectColumnsMenuStrip.Show( gridView, cellLocation );
}
}
}
public class ChromatogramListCellClickEventArgs : DataGridViewCellMouseEventArgs
{
private Chromatogram chromatogram;
public Chromatogram Chromatogram { get { return chromatogram; } }
internal ChromatogramListCellClickEventArgs( ChromatogramListForm sender, DataGridViewCellMouseEventArgs e )
: base( e.ColumnIndex, e.RowIndex, e.X, e.Y, e )
{
if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount )
chromatogram = sender.GetChromatogram( e.RowIndex );
}
}
public class ChromatogramListCellDoubleClickEventArgs : DataGridViewCellMouseEventArgs
{
private Chromatogram chromatogram;
public Chromatogram Chromatogram { get { return chromatogram; } }
internal ChromatogramListCellDoubleClickEventArgs( ChromatogramListForm sender, DataGridViewCellMouseEventArgs e )
: base( e.ColumnIndex, e.RowIndex, e.X, e.Y, e )
{
if( e.RowIndex > -1 && e.RowIndex < sender.GridView.RowCount )
chromatogram = sender.GetChromatogram( e.RowIndex );
}
}
public class ChromatogramListFilterChangedEventArgs : EventArgs
{
/// <summary>
/// The number of spectra that matched the new filter.
/// </summary>
public int Matches { get { return matches; } }
private int matches;
/// <summary>
/// The total number of spectra.
/// </summary>
public int Total { get { return total; } }
private int total;
internal ChromatogramListFilterChangedEventArgs( ChromatogramListForm sender, ChromatogramDataSet dataSet )
{
matches = sender.GridView.RowCount;
total = dataSet.ChromatogramTable.Count;
}
}
}
| |
using System;
using System.IO;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Reflection;
using System.Diagnostics;
using System.Configuration;
using System.Windows.Forms;
using System.Threading;
using MbUnit.Forms;
using MbUnit.Core;
using MbUnit.Core.Cons;
using MbUnit.Core.Cons.CommandLine;
namespace MbUnit.GUI
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public sealed class MbUnitForm : System.Windows.Forms.Form
{
private MbUnitFormArguments arguments;
private IContainer components = null;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItemFile;
private System.Windows.Forms.MenuItem menuItem10;
private System.Windows.Forms.MenuItem menuItem16;
private System.Windows.Forms.MenuItem menuItem18;
private System.Windows.Forms.MenuItem menuItem23;
private System.Windows.Forms.MenuItem menuItemFileNew;
private System.Windows.Forms.MenuItem menuItemFileOpen;
private System.Windows.Forms.MenuItem menuItemFileSaveAs;
private System.Windows.Forms.MenuItem menuItemFileExit;
private System.Windows.Forms.MenuItem menuItem29;
private System.Windows.Forms.MenuItem menuItemTests;
private System.Windows.Forms.MenuItem menuItemTestsRun;
private System.Windows.Forms.MenuItem menuItemTestsStop;
private System.Windows.Forms.MenuItem menuItemTree;
private System.Windows.Forms.MenuItem menuItemAssemblies;
private System.Windows.Forms.MenuItem menuItemAssembliesAddAssemblies;
private System.Windows.Forms.MenuItem menuItemAssembliesRemoveAssemblies;
private System.Windows.Forms.MenuItem menuItemAssembliesReload;
private System.Windows.Forms.MenuItem menuItemReports;
private System.Windows.Forms.MenuItem menuItemReportsHTML;
private System.Windows.Forms.MenuItem menuItemReportsXML;
private System.Windows.Forms.MenuItem menuItemTreeExpandAll;
private System.Windows.Forms.MenuItem menuItemTreeCollapseAll;
private System.Windows.Forms.MenuItem menuItemTreeExpandCurrent;
private System.Windows.Forms.MenuItem menuItemTreeCollapseCurrent;
private System.Windows.Forms.ImageList toolbarImageList;
private System.Windows.Forms.MenuItem menuItemTreeExpandCurrentFailures;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItemTreeExpandAllFailures;
private System.Windows.Forms.MenuItem menuItemTreeExpandAllIgnored;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem menuItemTreeExpandCurrentIgnored;
private System.Windows.Forms.MenuItem textMenuItem;
private System.Windows.Forms.MenuItem doxMenuItem;
private System.Windows.Forms.MenuItem menuItemTreeClearResults;
private ReflectorTreeView treeView = null;
private TestRunAndReportControl testResult;
private System.Windows.Forms.StatusBar statusBar1;
private System.Windows.Forms.StatusBarPanel timePanel;
private System.Windows.Forms.StatusBarPanel infoPanel;
private System.Windows.Forms.StatusBarPanel workerThreadPanel;
private Splitter splitter1;
private System.Timers.Timer statusBarTimer;
private string windowTitle = string.Empty;
private bool noArgs;
private string previousSettings = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
@"MbUnit\PreviousState.mbunit");
public MbUnitForm()
{
// set title.
this.SuspendLayout();
this.treeView=new ReflectorTreeView();
this.testResult=new TestRunAndReportControl();
this.splitter1=new Splitter();
this.treeView.Dock=DockStyle.Left;
this.splitter1.Dock=DockStyle.Left;
this.testResult.Dock=DockStyle.Fill;
this.Controls.AddRange(
new Control[]{ this.testResult, this.splitter1, this.treeView}
);
this.ResumeLayout(true);
InitializeComponent();
Assembly exeAssembly = Assembly.GetExecutingAssembly();
foreach (Attribute a in exeAssembly.GetCustomAttributes(true))
{
if (a is AssemblyTitleAttribute)
windowTitle = (a as AssemblyTitleAttribute).Title;
}
this.Text = String.Format("{0} (on .Net {1})",
windowTitle,
typeof(Object).GetType().Assembly.GetName().Version
);
this.testResult.TreeView = this.treeView;
this.statusBarTimer = new System.Timers.Timer(100);
this.statusBarTimer.AutoReset=true;
this.statusBarTimer.Enabled=true;
this.statusBarTimer.Elapsed+=new System.Timers.ElapsedEventHandler(statusBarTimer_Elapsed);
this.statusBarTimer.Start();
}
/// <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.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MbUnitForm));
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.menuItemFile = new System.Windows.Forms.MenuItem();
this.menuItemFileNew = new System.Windows.Forms.MenuItem();
this.menuItemFileOpen = new System.Windows.Forms.MenuItem();
this.menuItemFileSaveAs = new System.Windows.Forms.MenuItem();
this.menuItem29 = new System.Windows.Forms.MenuItem();
this.menuItemFileExit = new System.Windows.Forms.MenuItem();
this.menuItemAssemblies = new System.Windows.Forms.MenuItem();
this.menuItemAssembliesAddAssemblies = new System.Windows.Forms.MenuItem();
this.menuItemAssembliesRemoveAssemblies = new System.Windows.Forms.MenuItem();
this.menuItem23 = new System.Windows.Forms.MenuItem();
this.menuItemAssembliesReload = new System.Windows.Forms.MenuItem();
this.menuItemTests = new System.Windows.Forms.MenuItem();
this.menuItemTestsRun = new System.Windows.Forms.MenuItem();
this.menuItemTestsStop = new System.Windows.Forms.MenuItem();
this.menuItem10 = new System.Windows.Forms.MenuItem();
this.menuItemTree = new System.Windows.Forms.MenuItem();
this.menuItemTreeExpandAll = new System.Windows.Forms.MenuItem();
this.menuItemTreeCollapseAll = new System.Windows.Forms.MenuItem();
this.menuItem16 = new System.Windows.Forms.MenuItem();
this.menuItemTreeExpandCurrent = new System.Windows.Forms.MenuItem();
this.menuItemTreeCollapseCurrent = new System.Windows.Forms.MenuItem();
this.menuItem18 = new System.Windows.Forms.MenuItem();
this.menuItemTreeExpandAllFailures = new System.Windows.Forms.MenuItem();
this.menuItemTreeExpandCurrentFailures = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuItemTreeExpandAllIgnored = new System.Windows.Forms.MenuItem();
this.menuItemTreeExpandCurrentIgnored = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItemTreeClearResults = new System.Windows.Forms.MenuItem();
this.menuItemReports = new System.Windows.Forms.MenuItem();
this.menuItemReportsHTML = new System.Windows.Forms.MenuItem();
this.menuItemReportsXML = new System.Windows.Forms.MenuItem();
this.textMenuItem = new System.Windows.Forms.MenuItem();
this.doxMenuItem = new System.Windows.Forms.MenuItem();
this.toolbarImageList = new System.Windows.Forms.ImageList(this.components);
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.infoPanel = new System.Windows.Forms.StatusBarPanel();
this.timePanel = new System.Windows.Forms.StatusBarPanel();
this.workerThreadPanel = new System.Windows.Forms.StatusBarPanel();
((System.ComponentModel.ISupportInitialize)(this.infoPanel)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.timePanel)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.workerThreadPanel)).BeginInit();
this.SuspendLayout();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemFile,
this.menuItemAssemblies,
this.menuItemTests,
this.menuItemTree,
this.menuItemReports});
//
// menuItemFile
//
this.menuItemFile.Index = 0;
this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemFileNew,
this.menuItemFileOpen,
this.menuItemFileSaveAs,
this.menuItem29,
this.menuItemFileExit});
this.menuItemFile.Text = "&File";
//
// menuItemFileNew
//
this.menuItemFileNew.Index = 0;
this.menuItemFileNew.Text = "&New Project";
this.menuItemFileNew.Click += new System.EventHandler(this.menuItemFileNew_Click);
//
// menuItemFileOpen
//
this.menuItemFileOpen.Index = 1;
this.menuItemFileOpen.Text = "&Open Project...";
this.menuItemFileOpen.Click += new System.EventHandler(this.menuItemFileOpen_Click);
//
// menuItemFileSaveAs
//
this.menuItemFileSaveAs.Index = 2;
this.menuItemFileSaveAs.Text = "&Save Project As...";
this.menuItemFileSaveAs.Click += new System.EventHandler(this.menuItemFileSaveAs_Click);
//
// menuItem29
//
this.menuItem29.Index = 3;
this.menuItem29.Text = "-";
//
// menuItemFileExit
//
this.menuItemFileExit.Index = 4;
this.menuItemFileExit.Text = "&Exit";
this.menuItemFileExit.Click += new System.EventHandler(this.menuItemFileExit_Click);
//
// menuItemAssemblies
//
this.menuItemAssemblies.Index = 1;
this.menuItemAssemblies.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemAssembliesAddAssemblies,
this.menuItemAssembliesRemoveAssemblies,
this.menuItem23,
this.menuItemAssembliesReload});
this.menuItemAssemblies.Text = "&Assemblies";
//
// menuItemAssembliesAddAssemblies
//
this.menuItemAssembliesAddAssemblies.Index = 0;
this.menuItemAssembliesAddAssemblies.Text = "&Add Assemblies...";
this.menuItemAssembliesAddAssemblies.Click += new System.EventHandler(this.menuItemAssembliesAddAssemblies_Click);
//
// menuItemAssembliesRemoveAssemblies
//
this.menuItemAssembliesRemoveAssemblies.Index = 1;
this.menuItemAssembliesRemoveAssemblies.Text = "&Remove Assemblies";
this.menuItemAssembliesRemoveAssemblies.Click += new System.EventHandler(this.menuItemAssembliesRemoveAssemblies_Click);
//
// menuItem23
//
this.menuItem23.Index = 2;
this.menuItem23.Text = "-";
//
// menuItemAssembliesReload
//
this.menuItemAssembliesReload.Index = 3;
this.menuItemAssembliesReload.Text = "Re&load";
this.menuItemAssembliesReload.Click += new System.EventHandler(this.menuItemAssembliesReload_Click);
//
// menuItemTests
//
this.menuItemTests.Index = 2;
this.menuItemTests.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemTestsRun,
this.menuItemTestsStop,
this.menuItem10});
this.menuItemTests.Text = "&Tests";
//
// menuItemTestsRun
//
this.menuItemTestsRun.Index = 0;
this.menuItemTestsRun.Text = "&Run";
this.menuItemTestsRun.Click += new System.EventHandler(this.menuItemTestsRun_Click);
//
// menuItemTestsStop
//
this.menuItemTestsStop.Index = 1;
this.menuItemTestsStop.Text = "&Stop";
this.menuItemTestsStop.Click += new System.EventHandler(this.menuItemTestsStop_Click);
//
// menuItem10
//
this.menuItem10.Index = 2;
this.menuItem10.Text = "-";
//
// menuItemTree
//
this.menuItemTree.Index = 3;
this.menuItemTree.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemTreeExpandAll,
this.menuItemTreeCollapseAll,
this.menuItem16,
this.menuItemTreeExpandCurrent,
this.menuItemTreeCollapseCurrent,
this.menuItem18,
this.menuItemTreeExpandAllFailures,
this.menuItemTreeExpandCurrentFailures,
this.menuItem5,
this.menuItemTreeExpandAllIgnored,
this.menuItemTreeExpandCurrentIgnored,
this.menuItem2,
this.menuItemTreeClearResults});
this.menuItemTree.Text = "Tr&ee";
//
// menuItemTreeExpandAll
//
this.menuItemTreeExpandAll.Index = 0;
this.menuItemTreeExpandAll.Text = "&Expand All";
this.menuItemTreeExpandAll.Click += new System.EventHandler(this.menuItemTreeExpandAll_Click);
//
// menuItemTreeCollapseAll
//
this.menuItemTreeCollapseAll.Index = 1;
this.menuItemTreeCollapseAll.Text = "&Collapse All";
this.menuItemTreeCollapseAll.Click += new System.EventHandler(this.menuItemTreeCollapseAll_Click);
//
// menuItem16
//
this.menuItem16.Index = 2;
this.menuItem16.Text = "-";
//
// menuItemTreeExpandCurrent
//
this.menuItemTreeExpandCurrent.Index = 3;
this.menuItemTreeExpandCurrent.Text = "Expand C&urrent";
this.menuItemTreeExpandCurrent.Click += new System.EventHandler(this.menuItemTreeExpandCurrent_Click);
//
// menuItemTreeCollapseCurrent
//
this.menuItemTreeCollapseCurrent.Index = 4;
this.menuItemTreeCollapseCurrent.Text = "C&ollapse Current";
this.menuItemTreeCollapseCurrent.Click += new System.EventHandler(this.menuItemTreeCollapseCurrent_Click);
//
// menuItem18
//
this.menuItem18.Index = 5;
this.menuItem18.Text = "-";
//
// menuItemTreeExpandAllFailures
//
this.menuItemTreeExpandAllFailures.Index = 6;
this.menuItemTreeExpandAllFailures.Text = "Expand &All Failures";
this.menuItemTreeExpandAllFailures.Click += new System.EventHandler(this.menuItemTreeExpandAllFailures_Click);
//
// menuItemTreeExpandCurrentFailures
//
this.menuItemTreeExpandCurrentFailures.Index = 7;
this.menuItemTreeExpandCurrentFailures.Text = "Expand Current Fa&ilures";
this.menuItemTreeExpandCurrentFailures.Click += new System.EventHandler(this.menuItemTreeExpandCurrentFailures_Click);
//
// menuItem5
//
this.menuItem5.Index = 8;
this.menuItem5.Text = "-";
//
// menuItemTreeExpandAllIgnored
//
this.menuItemTreeExpandAllIgnored.Index = 9;
this.menuItemTreeExpandAllIgnored.Text = "Expand All Ignored";
this.menuItemTreeExpandAllIgnored.Click += new System.EventHandler(this.menuItemTreeExpandAllIgnored_Click);
//
// menuItemTreeExpandCurrentIgnored
//
this.menuItemTreeExpandCurrentIgnored.Index = 10;
this.menuItemTreeExpandCurrentIgnored.Text = "Expand Current Ignored";
this.menuItemTreeExpandCurrentIgnored.Click += new System.EventHandler(this.menuItemTreeExpandCurrentIgnored_Click);
//
// menuItem2
//
this.menuItem2.Index = 11;
this.menuItem2.Text = "-";
//
// menuItemTreeClearResults
//
this.menuItemTreeClearResults.Index = 12;
this.menuItemTreeClearResults.Text = "Clear Results";
this.menuItemTreeClearResults.Click += new System.EventHandler(this.menuItemTreeClearResults_Click);
//
// menuItemReports
//
this.menuItemReports.Index = 4;
this.menuItemReports.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItemReportsHTML,
this.menuItemReportsXML,
this.textMenuItem,
this.doxMenuItem});
this.menuItemReports.Text = "&Reports";
//
// menuItemReportsHTML
//
this.menuItemReportsHTML.Index = 0;
this.menuItemReportsHTML.Text = "&HTML";
this.menuItemReportsHTML.Click += new System.EventHandler(this.menuItemReportsHTML_Click);
//
// menuItemReportsXML
//
this.menuItemReportsXML.Index = 1;
this.menuItemReportsXML.Text = "&XML";
this.menuItemReportsXML.Click += new System.EventHandler(this.menuItemReportsXML_Click);
//
// textMenuItem
//
this.textMenuItem.Index = 2;
this.textMenuItem.Text = "&Text";
this.textMenuItem.Click += new System.EventHandler(this.textMenuItem_Click);
//
// doxMenuItem
//
this.doxMenuItem.Index = 3;
this.doxMenuItem.Text = "&Dox";
this.doxMenuItem.Click += new System.EventHandler(this.doxMenuItem_Click);
//
// toolbarImageList
//
this.toolbarImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
this.toolbarImageList.ImageSize = new System.Drawing.Size(16, 16);
this.toolbarImageList.TransparentColor = System.Drawing.Color.Transparent;
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 619);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
this.infoPanel,
this.timePanel,
this.workerThreadPanel});
this.statusBar1.ShowPanels = true;
this.statusBar1.Size = new System.Drawing.Size(992, 22);
this.statusBar1.TabIndex = 0;
//
// infoPanel
//
this.infoPanel.MinWidth = 400;
this.infoPanel.Text = "Info...";
this.infoPanel.ToolTipText = "Informations";
this.infoPanel.Width = 400;
//
// timePanel
//
this.timePanel.MinWidth = 150;
this.timePanel.Text = "Test Time:";
this.timePanel.ToolTipText = "Duration of the current test";
this.timePanel.Width = 150;
//
// workerThreadPanel
//
this.workerThreadPanel.MinWidth = 200;
this.workerThreadPanel.Text = "Worker Thread:";
this.workerThreadPanel.Width = 200;
//
// MbUnitForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(992, 641);
this.Controls.Add(this.statusBar1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Menu = this.mainMenu1;
this.Name = "MbUnitForm";
this.Text = "MbUnit GUI";
((System.ComponentModel.ISupportInitialize)(this.infoPanel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.timePanel)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.workerThreadPanel)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
TypeHelper.InvokeFutureStaticMethod(typeof(Application), "EnableVisualStyles");
Application.DoEvents();
using (MbUnitForm form = new MbUnitForm())
{
form.ParseArguments(args);
Thread thread = new Thread(new ThreadStart(form.ExecuteArguments));
thread.Start();
System.Windows.Forms.Application.Run(form);
}
return 100;
}
#region Menu Handlers
private void menuItemFileNew_Click(object sender, System.EventArgs e)
{
this.treeView.NewConfig();
}
private void menuItemFileOpen_Click(object sender, System.EventArgs e)
{
this.treeView.LoadProjectByDialog();
}
private void menuItemFileSaveAs_Click(object sender, System.EventArgs e)
{
this.treeView.SaveProjectByDialog();
}
private void menuItemFileExit_Click(object sender, System.EventArgs e)
{
this.Close();
}
private void menuItemAssembliesAddAssemblies_Click(object sender, System.EventArgs e)
{
this.treeView.AddAssembliesByDialog();
}
private void menuItemAssembliesRemoveAssemblies_Click(object sender, System.EventArgs e)
{
this.treeView.RemoveAssemblies();
}
private void menuItemAssembliesReload_Click(object sender, System.EventArgs e)
{
this.treeView.ReloadAssemblies();
}
private void menuItemTestsRun_Click(object sender, System.EventArgs e)
{
this.treeView.ThreadedRunTests();
}
private void menuItemTestsStop_Click(object sender, System.EventArgs e)
{
this.treeView.AbortWorkerThread();
}
private void menuItemTreeExpandAll_Click(object sender, System.EventArgs e)
{
this.treeView.TypeTree.ExpandAll();
}
private void menuItemTreeCollapseAll_Click(object sender, System.EventArgs e)
{
this.treeView.TypeTree.CollapseAll();
}
private void menuItemTreeExpandCurrent_Click(object sender, System.EventArgs e)
{
this.treeView.TypeTree.BeginUpdate();
this.expandChildNode(this.treeView.TypeTree.SelectedNode);
this.treeView.TypeTree.EndUpdate();
}
private void menuItemTreeCollapseCurrent_Click(object sender, System.EventArgs e)
{
this.treeView.TypeTree.BeginUpdate();
this.collapseChildNode(this.treeView.TypeTree.SelectedNode);
this.treeView.TypeTree.EndUpdate();
}
private void expandChildNode(TreeNode node)
{
if (node==null)
return;
node.Expand();
foreach(TreeNode child in node.Nodes)
expandChildNode(child);
}
private void collapseChildNode(TreeNode node)
{
if (node==null)
return;
node.Collapse();
foreach(TreeNode child in node.Nodes)
collapseChildNode(child);
}
private void menuItemTreeClearResults_Click(object sender, System.EventArgs e)
{
this.treeView.ClearAllResults();
}
private void menuItemReportsHTML_Click(object sender, System.EventArgs e)
{
this.treeView.GenerateHtmlReport();
}
private void menuItemReportsXML_Click(object sender, System.EventArgs e)
{
this.treeView.GenerateXmlReport();
}
private void doxMenuItem_Click(object sender, System.EventArgs e)
{
this.treeView.GenerateDoxReport();
}
private void textMenuItem_Click(object sender, System.EventArgs e)
{
this.treeView.GenerateTextReport();
}
private void menuItemTreeExpandAllFailures_Click(object sender, System.EventArgs e)
{
this.treeView.ExpandAllFailures();
}
private void menuItemTreeExpandCurrentFailures_Click(object sender, System.EventArgs e)
{
this.treeView.ExpandCurrentFailures();
}
private void menuItemTreeExpandAllIgnored_Click(object sender, System.EventArgs e)
{
this.treeView.ExpandAllIgnored();
}
private void menuItemTreeExpandCurrentIgnored_Click(object sender, System.EventArgs e)
{
this.treeView.ExpandCurrentIgnored();
}
#endregion
public delegate void LoadProjectDelegate(string fileName, bool silent);
private void LoadProjectInvoker(string fileName, bool silent)
{
this.treeView.LoadProject(fileName, silent);
}
public void ExecuteArguments()
{
if (this.arguments==null)
return;
System.Threading.Thread.Sleep(500);
try
{
if (this.arguments.Help)
{
MessageBox.Show(
CommandLineUtility.CommandLineArgumentsUsage(typeof(MbUnitFormArguments))
);
}
// load files or project if possible
if (this.arguments.Files != null)
{
foreach (string fileName in arguments.Files)
{
if (fileName.ToLower().EndsWith(".mbunit"))
{
this.Invoke(new LoadProjectDelegate(this.LoadProjectInvoker),
new object[] { fileName, false });
break;
}
this.treeView.AddAssembly(fileName);
}
}
// load last settings
if (ConfigurationSettings.AppSettings["restorePreviousState"] == "true" && this.noArgs)
{
this.Invoke(new LoadProjectDelegate(this.LoadProjectInvoker),
new object[] { previousSettings, true });
return;
}
// populate tree
this.treeView.ThreadedPopulateTree(false);
while (treeView.WorkerThreadAlive)
{
System.Threading.Thread.Sleep(100);
}
// run
if (this.arguments.Run)
{
this.treeView.ThreadedRunTests();
while (treeView.WorkerThreadAlive)
{
System.Threading.Thread.Sleep(100);
}
}
// generate report
foreach(ReportType reportType in this.arguments.ReportTypes)
{
switch(reportType)
{
case ReportType.Html:
this.treeView.GenerateHtmlReport(); break;
case ReportType.Text:
this.treeView.GenerateTextReport(); break;
case ReportType.Dox:
this.treeView.GenerateDoxReport(); break;
case ReportType.Xml:
this.treeView.GenerateXmlReport(); break;
}
}
// exit
if (this.arguments.Close)
{
System.Threading.Thread.Sleep(1000);
while (treeView.WorkerThreadAlive)
{
System.Threading.Thread.Sleep(100);
}
this.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Failure while executing arguments");
Console.WriteLine(ex.ToString());
throw new ApplicationException("Failure while executing arguments", ex);
}
}
public void ParseArguments(string[] args)
{
MbUnit.Core.Monitoring.ConsoleMonitor consoleMonitor = new MbUnit.Core.Monitoring.ConsoleMonitor();
consoleMonitor.Start();
try
{
this.arguments = new MbUnitFormArguments();
if (args.Length == 0)
{
this.noArgs = true;
}
CommandLineUtility.ParseCommandLineArguments(args, arguments);
}
catch (Exception)
{
consoleMonitor.Stop();
MessageBox.Show(consoleMonitor.Out + consoleMonitor.Error);
return;
}
finally
{
consoleMonitor.Stop();
}
}
private void UpdateStatusBar()
{
this.infoPanel.Text = this.treeView.InfoMessage;
this.timePanel.Text = String.Format("Test duration: {0:0.0}s",this.treeView.TestDuration);
this.workerThreadPanel.Text = String.Format("Worker thread: {0}",
(this.treeView.WorkerThreadAlive) ? "Working" : "Sleeping"
);
}
private void statusBarTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(this.UpdateStatusBar));
else
this.UpdateStatusBar();
}
catch { }
}
public void ClearReports()
{
this.testResult.ClearReports();
}
protected override void OnClosing(CancelEventArgs e)
{
if (ConfigurationSettings.AppSettings["restorePreviousState"] == "true")
{
try
{
// save current state
this.treeView.SaveProject(previousSettings);
}
catch (Exception)
{ }
}
// call base behaviour
base.OnClosing(e);
}
}
}
| |
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// All rights reserved.
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
// Neither the name of ComponentAce nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/*
Copyright (c) 2000,2001,2002,2003 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
using System;
namespace CocosSharp.Compression.Zlib
{
internal sealed class InfBlocks
{
private const int MANY = 1440;
// And'ing with mask[n] masks the lower n bits
private const int Z_OK = 0;
private const int Z_STREAM_END = 1;
private const int Z_NEED_DICT = 2;
private const int Z_ERRNO = - 1;
private const int Z_STREAM_ERROR = - 2;
private const int Z_DATA_ERROR = - 3;
private const int Z_MEM_ERROR = - 4;
private const int Z_BUF_ERROR = - 5;
private const int Z_VERSION_ERROR = - 6;
private const int TYPE = 0; // get type bits (3, including end bit)
private const int LENS = 1; // get lengths for stored
private const int STORED = 2; // processing stored block
private const int TABLE = 3; // get table lengths
private const int BTREE = 4; // get bit lengths tree for a dynamic block
private const int DTREE = 5; // get length, distance trees for a dynamic block
private const int CODES = 6; // processing fixed or dynamic block
private const int DRY = 7; // output remaining window bytes
private const int DONE = 8; // finished last block, done
private const int BAD = 9; // ot a data error--stuck here
private static readonly int[] inflate_mask = new[]
{
0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000f, 0x0000001f, 0x0000003f, 0x0000007f, 0x000000ff,
0x000001ff, 0x000003ff, 0x000007ff, 0x00000fff, 0x00001fff, 0x00003fff, 0x00007fff, 0x0000ffff
};
// Table for deflate from PKZIP's appnote.txt.
internal static readonly int[] border = new[] {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
internal int[] bb = new int[1]; // bit length tree depth
internal int bitb; // bit buffer
internal int bitk; // bits in bit buffer
internal int[] blens; // bit lengths of codes
internal long check; // check on output
internal Object checkfn; // check function
internal InfCodes codes; // if CODES, current state
internal int end; // one byte after sliding window
internal int[] hufts; // single malloc for tree space
internal int index; // index into blens (or border)
internal int last; // true if this block is the last block
internal int left; // if STORED, bytes left to copy
internal int mode; // current inflate_block mode
internal int read; // window read pointer
internal int table; // table lengths (14 bits)
internal int[] tb = new int[1]; // bit length decoding tree
internal byte[] window; // sliding window
internal int write; // window write pointer
internal InfBlocks(ZStream z, Object checkfn, int w)
{
hufts = new int[MANY * 3];
window = new byte[w];
end = w;
this.checkfn = checkfn;
mode = TYPE;
reset(z, null);
}
internal void reset(ZStream z, long[] c)
{
if (c != null)
c[0] = check;
if (mode == BTREE || mode == DTREE)
{
blens = null;
}
if (mode == CODES)
{
codes.free(z);
}
mode = TYPE;
bitk = 0;
bitb = 0;
read = write = 0;
if (checkfn != null)
z.adler = check = z._adler.adler32(0L, null, 0, 0);
}
internal int proc(ZStream z, int r)
{
int t; // temporary storage
int b; // bit buffer
int k; // bits in bit buffer
int p; // input data pointer
int n; // bytes available there
int q; // output window write pointer
int m; // bytes to end of window or read pointer
// copy input/output information to locals (UPDATE macro restores)
{
p = z.next_in_index;
n = z.avail_in;
b = bitb;
k = bitk;
}
{
q = write;
m = (q < read ? read - q - 1 : end - q);
}
// process input based on current state
while (true)
{
switch (mode)
{
case TYPE:
while (k < (3))
{
if (n != 0)
{
r = Z_OK;
}
else
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
t = (b & 7);
last = t & 1;
switch (SupportClass.URShift(t, 1))
{
case 0: // stored
{
b = SupportClass.URShift(b, (3));
k -= (3);
}
t = k & 7; // go to byte boundary
{
b = SupportClass.URShift(b, (t));
k -= (t);
}
mode = LENS; // get length of stored block
break;
case 1: // fixed
{
var bl = new int[1];
var bd = new int[1];
var tl = new int[1][];
var td = new int[1][];
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes = new InfCodes(bl[0], bd[0], tl[0], td[0], z);
}
{
b = SupportClass.URShift(b, (3));
k -= (3);
}
mode = CODES;
break;
case 2: // dynamic
{
b = SupportClass.URShift(b, (3));
k -= (3);
}
mode = TABLE;
break;
case 3: // illegal
{
b = SupportClass.URShift(b, (3));
k -= (3);
}
mode = BAD;
z.msg = "invalid block type";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
break;
case LENS:
while (k < (32))
{
if (n != 0)
{
r = Z_OK;
}
else
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
if (((SupportClass.URShift((~ b), 16)) & 0xffff) != (b & 0xffff))
{
mode = BAD;
z.msg = "invalid stored block lengths";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
left = (b & 0xffff);
b = k = 0; // dump bits
mode = left != 0 ? STORED : (last != 0 ? DRY : TYPE);
break;
case STORED:
if (n == 0)
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
if (m == 0)
{
if (q == end && read != 0)
{
q = 0;
m = (q < read ? read - q - 1 : end - q);
}
if (m == 0)
{
write = q;
r = inflate_flush(z, r);
q = write;
m = (q < read ? read - q - 1 : end - q);
if (q == end && read != 0)
{
q = 0;
m = (q < read ? read - q - 1 : end - q);
}
if (m == 0)
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
}
}
r = Z_OK;
t = left;
if (t > n)
t = n;
if (t > m)
t = m;
Array.Copy(z.next_in, p, window, q, t);
p += t;
n -= t;
q += t;
m -= t;
if ((left -= t) != 0)
break;
mode = last != 0 ? DRY : TYPE;
break;
case TABLE:
while (k < (14))
{
if (n != 0)
{
r = Z_OK;
}
else
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
table = t = (b & 0x3fff);
if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
{
mode = BAD;
z.msg = "too many length or distance symbols";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
blens = new int[t];
{
b = SupportClass.URShift(b, (14));
k -= (14);
}
index = 0;
mode = BTREE;
goto case BTREE;
case BTREE:
while (index < 4 + (SupportClass.URShift(table, 10)))
{
while (k < (3))
{
if (n != 0)
{
r = Z_OK;
}
else
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
blens[border[index++]] = b & 7;
{
b = SupportClass.URShift(b, (3));
k -= (3);
}
}
while (index < 19)
{
blens[border[index++]] = 0;
}
bb[0] = 7;
t = InfTree.inflate_trees_bits(blens, bb, tb, hufts, z);
if (t != Z_OK)
{
r = t;
if (r == Z_DATA_ERROR)
{
blens = null;
mode = BAD;
}
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
index = 0;
mode = DTREE;
goto case DTREE;
case DTREE:
while (true)
{
t = table;
if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)))
{
break;
}
int i, j, c;
t = bb[0];
while (k < (t))
{
if (n != 0)
{
r = Z_OK;
}
else
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
if (tb[0] == - 1)
{
//System.err.println("null...");
}
t = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 1];
c = hufts[(tb[0] + (b & inflate_mask[t])) * 3 + 2];
if (c < 16)
{
b = SupportClass.URShift(b, (t));
k -= (t);
blens[index++] = c;
}
else
{
// c == 16..18
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
while (k < (t + i))
{
if (n != 0)
{
r = Z_OK;
}
else
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
;
n--;
b |= (z.next_in[p++] & 0xff) << k;
k += 8;
}
b = SupportClass.URShift(b, (t));
k -= (t);
j += (b & inflate_mask[i]);
b = SupportClass.URShift(b, (i));
k -= (i);
i = index;
t = table;
if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1))
{
blens = null;
mode = BAD;
z.msg = "invalid bit length repeat";
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
c = c == 16 ? blens[i - 1] : 0;
do
{
blens[i++] = c;
} while (--j != 0);
index = i;
}
}
tb[0] = - 1;
{
var bl = new int[1];
var bd = new int[1];
var tl = new int[1];
var td = new int[1];
bl[0] = 9; // must be <= 9 for lookahead assumptions
bd[0] = 6; // must be <= 9 for lookahead assumptions
t = table;
t = InfTree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl,
td, hufts, z);
if (t != Z_OK)
{
if (t == Z_DATA_ERROR)
{
blens = null;
mode = BAD;
}
r = t;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
codes = new InfCodes(bl[0], bd[0], hufts, tl[0], hufts, td[0], z);
}
blens = null;
mode = CODES;
goto case CODES;
case CODES:
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
if ((r = codes.proc(this, z, r)) != Z_STREAM_END)
{
return inflate_flush(z, r);
}
r = Z_OK;
codes.free(z);
p = z.next_in_index;
n = z.avail_in;
b = bitb;
k = bitk;
q = write;
m = (q < read ? read - q - 1 : end - q);
if (last == 0)
{
mode = TYPE;
break;
}
mode = DRY;
goto case DRY;
case DRY:
write = q;
r = inflate_flush(z, r);
q = write;
m = (q < read ? read - q - 1 : end - q);
if (read != write)
{
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
mode = DONE;
goto case DONE;
case DONE:
r = Z_STREAM_END;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
case BAD:
r = Z_DATA_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
default:
r = Z_STREAM_ERROR;
bitb = b;
bitk = k;
z.avail_in = n;
z.total_in += p - z.next_in_index;
z.next_in_index = p;
write = q;
return inflate_flush(z, r);
}
}
}
internal void free(ZStream z)
{
reset(z, null);
window = null;
hufts = null;
//ZFREE(z, s);
}
internal void set_dictionary(byte[] d, int start, int n)
{
Array.Copy(d, start, window, 0, n);
read = write = n;
}
// Returns true if inflate is currently at the end of a block generated
// by Z_SYNC_FLUSH or Z_FULL_FLUSH.
internal int sync_point()
{
return mode == LENS ? 1 : 0;
}
// copy as much as possible from the sliding window to the output area
internal int inflate_flush(ZStream z, int r)
{
int n;
int p;
int q;
// local copies of source and destination pointers
p = z.next_out_index;
q = read;
// compute number of bytes to copy as far as end of window
n = ((q <= write ? write : end) - q);
if (n > z.avail_out)
n = z.avail_out;
if (n != 0 && r == Z_BUF_ERROR)
r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if (checkfn != null)
z.adler = check = z._adler.adler32(check, window, q, n);
// copy as far as end of window
Array.Copy(window, q, z.next_out, p, n);
p += n;
q += n;
// see if more to copy at beginning of window
if (q == end)
{
// wrap pointers
q = 0;
if (write == end)
write = 0;
// compute bytes to copy
n = write - q;
if (n > z.avail_out)
n = z.avail_out;
if (n != 0 && r == Z_BUF_ERROR)
r = Z_OK;
// update counters
z.avail_out -= n;
z.total_out += n;
// update check information
if (checkfn != null)
z.adler = check = z._adler.adler32(check, window, q, n);
// copy
Array.Copy(window, q, z.next_out, p, n);
p += n;
q += n;
}
// update pointers
z.next_out_index = p;
read = q;
// done
return r;
}
}
}
| |
// 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 System.Collections.Generic;
namespace Microsoft.Test.ModuleCore
{
////////////////////////////////////////////////////////////////
// KeywordParser
//
////////////////////////////////////////////////////////////////
public class KeywordParser
{
//Enum
protected enum PARSE
{
Initial,
Keyword,
Equal,
Value,
SingleBegin,
SingleEnd,
DoubleBegin,
DoubleEnd,
End
}
//Accessors
//Note: You can override these if you want to leverage our parser (inherit), and change
//some of the behavior (without reimplementing it).
private static Tokens s_DefaultTokens = new Tokens();
public class Tokens
{
public string Equal = "=";
public string Seperator = ";";
public string SingleQuote = "'";
public string DoubleQuote = "\"";
}
//Methods
public static Dictionary<string, string> ParseKeywords(string str)
{
return ParseKeywords(str, s_DefaultTokens);
}
public static Dictionary<string, string> ParseKeywords(string str, Tokens tokens)
{
PARSE state = PARSE.Initial;
int index = 0;
int keyStart = 0;
InsensitiveDictionary keywords = new InsensitiveDictionary(5);
string key = null;
if (str != null)
{
StringBuilder builder = new StringBuilder(str.Length);
for (; index < str.Length; index++)
{
char ch = str[index];
switch (state)
{
case PARSE.Initial:
if (char.IsLetterOrDigit(ch))
{
keyStart = index;
state = PARSE.Keyword;
}
break;
case PARSE.Keyword:
if (tokens.Seperator.IndexOf(ch) >= 0)
{
state = PARSE.Initial;
}
else if (tokens.Equal.IndexOf(ch) >= 0)
{
//Note: We have a case-insentive hashtable so we don't have to lowercase
key = str.Substring(keyStart, index - keyStart).Trim();
state = PARSE.Equal;
}
break;
case PARSE.Equal:
if (char.IsWhiteSpace(ch))
break;
builder.Length = 0;
//Note: Since we allow you to alter the tokens, these are not
//constant values, so we cannot use a switch statement...
if (tokens.SingleQuote.IndexOf(ch) >= 0)
{
state = PARSE.SingleBegin;
}
else if (tokens.DoubleQuote.IndexOf(ch) >= 0)
{
state = PARSE.DoubleBegin;
}
else if (tokens.Seperator.IndexOf(ch) >= 0)
{
keywords.Update(key, string.Empty);
state = PARSE.Initial;
}
else
{
state = PARSE.Value;
builder.Append(ch);
}
break;
case PARSE.Value:
if (tokens.Seperator.IndexOf(ch) >= 0)
{
keywords.Update(key, (builder.ToString()).Trim());
state = PARSE.Initial;
}
else
{
builder.Append(ch);
}
break;
case PARSE.SingleBegin:
if (tokens.SingleQuote.IndexOf(ch) >= 0)
state = PARSE.SingleEnd;
else
builder.Append(ch);
break;
case PARSE.DoubleBegin:
if (tokens.DoubleQuote.IndexOf(ch) >= 0)
state = PARSE.DoubleEnd;
else
builder.Append(ch);
break;
case PARSE.SingleEnd:
if (tokens.SingleQuote.IndexOf(ch) >= 0)
{
state = PARSE.SingleBegin;
builder.Append(ch);
}
else
{
keywords.Update(key, builder.ToString());
state = PARSE.End;
goto case PARSE.End;
}
break;
case PARSE.DoubleEnd:
if (tokens.DoubleQuote.IndexOf(ch) >= 0)
{
state = PARSE.DoubleBegin;
builder.Append(ch);
}
else
{
keywords.Update(key, builder.ToString());
state = PARSE.End;
goto case PARSE.End;
}
break;
case PARSE.End:
if (tokens.Seperator.IndexOf(ch) >= 0)
{
state = PARSE.Initial;
}
break;
default:
throw new TestFailedException("Unhandled State: " + StringEx.ToString(state));
}
}
switch (state)
{
case PARSE.Initial:
case PARSE.Keyword:
case PARSE.End:
break;
case PARSE.Equal:
keywords.Update(key, string.Empty);
break;
case PARSE.Value:
keywords.Update(key, (builder.ToString()).Trim());
break;
case PARSE.SingleBegin:
case PARSE.DoubleBegin:
case PARSE.SingleEnd:
case PARSE.DoubleEnd:
keywords.Update(key, builder.ToString());
break;
default:
throw new TestFailedException("Unhandled State: " + StringEx.ToString(state));
}
}
return keywords;
}
}
}
| |
namespace KabMan.Forms
{
partial class DCCList
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 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();
this.layoutControl1 = new DevExpress.XtraLayout.LayoutControl();
this.DCCGrid = new DevExpress.XtraGrid.GridControl();
this.CRackView = new DevExpress.XtraGrid.Views.Grid.GridView();
this.ID = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn1 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn5 = new DevExpress.XtraGrid.Columns.GridColumn();
this.gridColumn6 = new DevExpress.XtraGrid.Columns.GridColumn();
this.layoutControlGroup1 = new DevExpress.XtraLayout.LayoutControlGroup();
this.layoutControlItem1 = new DevExpress.XtraLayout.LayoutControlItem();
this.barManager1 = new DevExpress.XtraBars.BarManager(this.components);
this.bar1 = new DevExpress.XtraBars.Bar();
this.itemNew = new DevExpress.XtraBars.BarButtonItem();
this.itemDelete = new DevExpress.XtraBars.BarButtonItem();
this.itemExit = new DevExpress.XtraBars.BarButtonItem();
this.barDockControlTop = new DevExpress.XtraBars.BarDockControl();
this.barDockControlBottom = new DevExpress.XtraBars.BarDockControl();
this.barDockControlLeft = new DevExpress.XtraBars.BarDockControl();
this.barDockControlRight = new DevExpress.XtraBars.BarDockControl();
this.itemDetail = new DevExpress.XtraBars.BarButtonItem();
this.itemDetails = new DevExpress.XtraBars.BarButtonItem();
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).BeginInit();
this.layoutControl1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.DCCGrid)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.CRackView)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).BeginInit();
this.SuspendLayout();
//
// layoutControl1
//
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutGroupCaption.Options.UseForeColor = true;
this.layoutControl1.Appearance.DisabledLayoutItem.ForeColor = System.Drawing.SystemColors.GrayText;
this.layoutControl1.Appearance.DisabledLayoutItem.Options.UseForeColor = true;
this.layoutControl1.Controls.Add(this.DCCGrid);
this.layoutControl1.Dock = System.Windows.Forms.DockStyle.Fill;
this.layoutControl1.Location = new System.Drawing.Point(0, 24);
this.layoutControl1.Name = "layoutControl1";
this.layoutControl1.Root = this.layoutControlGroup1;
this.layoutControl1.Size = new System.Drawing.Size(646, 402);
this.layoutControl1.TabIndex = 0;
this.layoutControl1.Text = "layoutControl1";
//
// DCCGrid
//
this.DCCGrid.Location = new System.Drawing.Point(7, 7);
this.DCCGrid.MainView = this.CRackView;
this.DCCGrid.Name = "DCCGrid";
this.DCCGrid.Size = new System.Drawing.Size(633, 389);
this.DCCGrid.TabIndex = 5;
this.DCCGrid.ViewCollection.AddRange(new DevExpress.XtraGrid.Views.Base.BaseView[] {
this.CRackView});
this.DCCGrid.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.DCCGrid_MouseDoubleClick);
//
// CRackView
//
this.CRackView.Appearance.ColumnFilterButton.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.ColumnFilterButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CRackView.Appearance.ColumnFilterButton.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.ColumnFilterButton.ForeColor = System.Drawing.Color.Gray;
this.CRackView.Appearance.ColumnFilterButton.Options.UseBackColor = true;
this.CRackView.Appearance.ColumnFilterButton.Options.UseBorderColor = true;
this.CRackView.Appearance.ColumnFilterButton.Options.UseForeColor = true;
this.CRackView.Appearance.ColumnFilterButtonActive.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CRackView.Appearance.ColumnFilterButtonActive.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CRackView.Appearance.ColumnFilterButtonActive.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(212)))), ((int)(((byte)(212)))));
this.CRackView.Appearance.ColumnFilterButtonActive.ForeColor = System.Drawing.Color.Blue;
this.CRackView.Appearance.ColumnFilterButtonActive.Options.UseBackColor = true;
this.CRackView.Appearance.ColumnFilterButtonActive.Options.UseBorderColor = true;
this.CRackView.Appearance.ColumnFilterButtonActive.Options.UseForeColor = true;
this.CRackView.Appearance.Empty.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CRackView.Appearance.Empty.Options.UseBackColor = true;
this.CRackView.Appearance.EvenRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(223)))), ((int)(((byte)(223)))), ((int)(((byte)(223)))));
this.CRackView.Appearance.EvenRow.BackColor2 = System.Drawing.Color.GhostWhite;
this.CRackView.Appearance.EvenRow.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.EvenRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CRackView.Appearance.EvenRow.Options.UseBackColor = true;
this.CRackView.Appearance.EvenRow.Options.UseForeColor = true;
this.CRackView.Appearance.FilterCloseButton.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.FilterCloseButton.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(118)))), ((int)(((byte)(170)))), ((int)(((byte)(225)))));
this.CRackView.Appearance.FilterCloseButton.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.FilterCloseButton.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.FilterCloseButton.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CRackView.Appearance.FilterCloseButton.Options.UseBackColor = true;
this.CRackView.Appearance.FilterCloseButton.Options.UseBorderColor = true;
this.CRackView.Appearance.FilterCloseButton.Options.UseForeColor = true;
this.CRackView.Appearance.FilterPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(28)))), ((int)(((byte)(80)))), ((int)(((byte)(135)))));
this.CRackView.Appearance.FilterPanel.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.FilterPanel.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.FilterPanel.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.ForwardDiagonal;
this.CRackView.Appearance.FilterPanel.Options.UseBackColor = true;
this.CRackView.Appearance.FilterPanel.Options.UseForeColor = true;
this.CRackView.Appearance.FixedLine.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(58)))), ((int)(((byte)(58)))));
this.CRackView.Appearance.FixedLine.Options.UseBackColor = true;
this.CRackView.Appearance.FocusedCell.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(225)))));
this.CRackView.Appearance.FocusedCell.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.FocusedCell.Options.UseBackColor = true;
this.CRackView.Appearance.FocusedCell.Options.UseForeColor = true;
this.CRackView.Appearance.FocusedRow.BackColor = System.Drawing.Color.Navy;
this.CRackView.Appearance.FocusedRow.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(50)))), ((int)(((byte)(50)))), ((int)(((byte)(178)))));
this.CRackView.Appearance.FocusedRow.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.FocusedRow.Options.UseBackColor = true;
this.CRackView.Appearance.FocusedRow.Options.UseForeColor = true;
this.CRackView.Appearance.FooterPanel.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.FooterPanel.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.FooterPanel.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.FooterPanel.Options.UseBackColor = true;
this.CRackView.Appearance.FooterPanel.Options.UseBorderColor = true;
this.CRackView.Appearance.FooterPanel.Options.UseForeColor = true;
this.CRackView.Appearance.GroupButton.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.GroupButton.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.GroupButton.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.GroupButton.Options.UseBackColor = true;
this.CRackView.Appearance.GroupButton.Options.UseBorderColor = true;
this.CRackView.Appearance.GroupButton.Options.UseForeColor = true;
this.CRackView.Appearance.GroupFooter.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CRackView.Appearance.GroupFooter.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(202)))), ((int)(((byte)(202)))), ((int)(((byte)(202)))));
this.CRackView.Appearance.GroupFooter.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.GroupFooter.Options.UseBackColor = true;
this.CRackView.Appearance.GroupFooter.Options.UseBorderColor = true;
this.CRackView.Appearance.GroupFooter.Options.UseForeColor = true;
this.CRackView.Appearance.GroupPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(58)))), ((int)(((byte)(110)))), ((int)(((byte)(165)))));
this.CRackView.Appearance.GroupPanel.BackColor2 = System.Drawing.Color.White;
this.CRackView.Appearance.GroupPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CRackView.Appearance.GroupPanel.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.GroupPanel.Options.UseBackColor = true;
this.CRackView.Appearance.GroupPanel.Options.UseFont = true;
this.CRackView.Appearance.GroupPanel.Options.UseForeColor = true;
this.CRackView.Appearance.GroupRow.BackColor = System.Drawing.Color.Gray;
this.CRackView.Appearance.GroupRow.ForeColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.GroupRow.Options.UseBackColor = true;
this.CRackView.Appearance.GroupRow.Options.UseForeColor = true;
this.CRackView.Appearance.HeaderPanel.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.HeaderPanel.BorderColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.HeaderPanel.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Bold);
this.CRackView.Appearance.HeaderPanel.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.HeaderPanel.Options.UseBackColor = true;
this.CRackView.Appearance.HeaderPanel.Options.UseBorderColor = true;
this.CRackView.Appearance.HeaderPanel.Options.UseFont = true;
this.CRackView.Appearance.HeaderPanel.Options.UseForeColor = true;
this.CRackView.Appearance.HideSelectionRow.BackColor = System.Drawing.Color.Gray;
this.CRackView.Appearance.HideSelectionRow.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(212)))), ((int)(((byte)(208)))), ((int)(((byte)(200)))));
this.CRackView.Appearance.HideSelectionRow.Options.UseBackColor = true;
this.CRackView.Appearance.HideSelectionRow.Options.UseForeColor = true;
this.CRackView.Appearance.HorzLine.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.HorzLine.Options.UseBackColor = true;
this.CRackView.Appearance.OddRow.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.OddRow.BackColor2 = System.Drawing.Color.White;
this.CRackView.Appearance.OddRow.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.OddRow.GradientMode = System.Drawing.Drawing2D.LinearGradientMode.BackwardDiagonal;
this.CRackView.Appearance.OddRow.Options.UseBackColor = true;
this.CRackView.Appearance.OddRow.Options.UseForeColor = true;
this.CRackView.Appearance.Preview.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.Preview.ForeColor = System.Drawing.Color.Navy;
this.CRackView.Appearance.Preview.Options.UseBackColor = true;
this.CRackView.Appearance.Preview.Options.UseForeColor = true;
this.CRackView.Appearance.Row.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.Row.ForeColor = System.Drawing.Color.Black;
this.CRackView.Appearance.Row.Options.UseBackColor = true;
this.CRackView.Appearance.Row.Options.UseForeColor = true;
this.CRackView.Appearance.RowSeparator.BackColor = System.Drawing.Color.White;
this.CRackView.Appearance.RowSeparator.BackColor2 = System.Drawing.Color.FromArgb(((int)(((byte)(243)))), ((int)(((byte)(243)))), ((int)(((byte)(243)))));
this.CRackView.Appearance.RowSeparator.Options.UseBackColor = true;
this.CRackView.Appearance.SelectedRow.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(10)))), ((int)(((byte)(10)))), ((int)(((byte)(138)))));
this.CRackView.Appearance.SelectedRow.ForeColor = System.Drawing.Color.White;
this.CRackView.Appearance.SelectedRow.Options.UseBackColor = true;
this.CRackView.Appearance.SelectedRow.Options.UseForeColor = true;
this.CRackView.Appearance.VertLine.BackColor = System.Drawing.Color.Silver;
this.CRackView.Appearance.VertLine.Options.UseBackColor = true;
this.CRackView.Columns.AddRange(new DevExpress.XtraGrid.Columns.GridColumn[] {
this.ID,
this.gridColumn1,
this.gridColumn5,
this.gridColumn6});
this.CRackView.GridControl = this.DCCGrid;
this.CRackView.Name = "CRackView";
this.CRackView.OptionsBehavior.AllowIncrementalSearch = true;
this.CRackView.OptionsBehavior.Editable = false;
this.CRackView.OptionsCustomization.AllowFilter = false;
this.CRackView.OptionsView.EnableAppearanceEvenRow = true;
this.CRackView.OptionsView.EnableAppearanceOddRow = true;
this.CRackView.OptionsView.ShowGroupPanel = false;
this.CRackView.OptionsView.ShowIndicator = false;
//
// ID
//
this.ID.Caption = "ID";
this.ID.FieldName = "ID";
this.ID.Name = "ID";
//
// gridColumn1
//
this.gridColumn1.Caption = "Name";
this.gridColumn1.FieldName = "Name";
this.gridColumn1.Name = "gridColumn1";
this.gridColumn1.Visible = true;
this.gridColumn1.VisibleIndex = 0;
//
// gridColumn5
//
this.gridColumn5.Caption = "Trunk Model";
this.gridColumn5.FieldName = "Model";
this.gridColumn5.Name = "gridColumn5";
this.gridColumn5.Visible = true;
this.gridColumn5.VisibleIndex = 1;
//
// gridColumn6
//
this.gridColumn6.Caption = "Port Count";
this.gridColumn6.FieldName = "PortCount";
this.gridColumn6.Name = "gridColumn6";
this.gridColumn6.Visible = true;
this.gridColumn6.VisibleIndex = 2;
//
// layoutControlGroup1
//
this.layoutControlGroup1.CustomizationFormText = "layoutControlGroup1";
this.layoutControlGroup1.Items.AddRange(new DevExpress.XtraLayout.BaseLayoutItem[] {
this.layoutControlItem1});
this.layoutControlGroup1.Location = new System.Drawing.Point(0, 0);
this.layoutControlGroup1.Name = "layoutControlGroup1";
this.layoutControlGroup1.Size = new System.Drawing.Size(646, 402);
this.layoutControlGroup1.Spacing = new DevExpress.XtraLayout.Utils.Padding(0, 0, 0, 0);
this.layoutControlGroup1.Text = "layoutControlGroup1";
this.layoutControlGroup1.TextVisible = false;
//
// layoutControlItem1
//
this.layoutControlItem1.Control = this.DCCGrid;
this.layoutControlItem1.CustomizationFormText = "layoutControlItem1";
this.layoutControlItem1.Location = new System.Drawing.Point(0, 0);
this.layoutControlItem1.Name = "layoutControlItem1";
this.layoutControlItem1.Size = new System.Drawing.Size(644, 400);
this.layoutControlItem1.Text = "layoutControlItem1";
this.layoutControlItem1.TextLocation = DevExpress.Utils.Locations.Left;
this.layoutControlItem1.TextSize = new System.Drawing.Size(0, 0);
this.layoutControlItem1.TextToControlDistance = 0;
this.layoutControlItem1.TextVisible = false;
//
// barManager1
//
this.barManager1.AllowCustomization = false;
this.barManager1.AllowQuickCustomization = false;
this.barManager1.AllowShowToolbarsPopup = false;
this.barManager1.Bars.AddRange(new DevExpress.XtraBars.Bar[] {
this.bar1});
this.barManager1.DockControls.Add(this.barDockControlTop);
this.barManager1.DockControls.Add(this.barDockControlBottom);
this.barManager1.DockControls.Add(this.barDockControlLeft);
this.barManager1.DockControls.Add(this.barDockControlRight);
this.barManager1.Form = this;
this.barManager1.Items.AddRange(new DevExpress.XtraBars.BarItem[] {
this.itemNew,
this.itemDelete,
this.itemDetail,
this.itemExit,
this.itemDetails});
this.barManager1.MaxItemId = 9;
//
// bar1
//
this.bar1.BarName = "Custom 3";
this.bar1.DockCol = 0;
this.bar1.DockRow = 0;
this.bar1.DockStyle = DevExpress.XtraBars.BarDockStyle.Top;
this.bar1.LinksPersistInfo.AddRange(new DevExpress.XtraBars.LinkPersistInfo[] {
new DevExpress.XtraBars.LinkPersistInfo(this.itemNew),
new DevExpress.XtraBars.LinkPersistInfo(this.itemDelete, true),
new DevExpress.XtraBars.LinkPersistInfo(this.itemDetails, true),
new DevExpress.XtraBars.LinkPersistInfo(this.itemExit, true)});
this.bar1.OptionsBar.AllowQuickCustomization = false;
this.bar1.OptionsBar.DrawDragBorder = false;
this.bar1.OptionsBar.UseWholeRow = true;
this.bar1.Text = "Custom 3";
//
// itemNew
//
this.itemNew.Caption = "New";
this.itemNew.Id = 4;
this.itemNew.Name = "itemNew";
this.itemNew.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemNew.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemNew_ItemClick);
//
// itemDelete
//
this.itemDelete.Caption = "Delete";
this.itemDelete.Id = 5;
this.itemDelete.Name = "itemDelete";
this.itemDelete.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
//
// itemExit
//
this.itemExit.Caption = "Exit";
this.itemExit.Id = 7;
this.itemExit.Name = "itemExit";
this.itemExit.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemExit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemExit_ItemClick);
//
// itemDetail
//
this.itemDetail.Caption = "View Details";
this.itemDetail.Id = 6;
this.itemDetail.Name = "itemDetail";
this.itemDetail.PaintStyle = DevExpress.XtraBars.BarItemPaintStyle.CaptionGlyph;
this.itemDetail.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemDetail_ItemClick);
//
// itemDetails
//
this.itemDetails.Caption = "View Details";
this.itemDetails.Id = 8;
this.itemDetails.Name = "itemDetails";
this.itemDetails.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(this.itemDetails_ItemClick);
//
// DCCList
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(646, 426);
this.Controls.Add(this.layoutControl1);
this.Controls.Add(this.barDockControlLeft);
this.Controls.Add(this.barDockControlRight);
this.Controls.Add(this.barDockControlBottom);
this.Controls.Add(this.barDockControlTop);
this.Name = "DCCList";
this.Text = "DCCList";
this.Load += new System.EventHandler(this.DCCList_Load);
((System.ComponentModel.ISupportInitialize)(this.layoutControl1)).EndInit();
this.layoutControl1.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.DCCGrid)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.CRackView)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlGroup1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.layoutControlItem1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.barManager1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraLayout.LayoutControl layoutControl1;
private DevExpress.XtraLayout.LayoutControlGroup layoutControlGroup1;
private DevExpress.XtraBars.BarManager barManager1;
private DevExpress.XtraBars.BarDockControl barDockControlTop;
private DevExpress.XtraBars.BarDockControl barDockControlBottom;
private DevExpress.XtraBars.BarDockControl barDockControlLeft;
private DevExpress.XtraBars.BarDockControl barDockControlRight;
private DevExpress.XtraGrid.GridControl DCCGrid;
private DevExpress.XtraGrid.Views.Grid.GridView CRackView;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn1;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn5;
private DevExpress.XtraGrid.Columns.GridColumn gridColumn6;
private DevExpress.XtraLayout.LayoutControlItem layoutControlItem1;
private DevExpress.XtraGrid.Columns.GridColumn ID;
private DevExpress.XtraBars.Bar bar1;
private DevExpress.XtraBars.BarButtonItem itemNew;
private DevExpress.XtraBars.BarButtonItem itemDelete;
private DevExpress.XtraBars.BarButtonItem itemDetail;
private DevExpress.XtraBars.BarButtonItem itemExit;
private DevExpress.XtraBars.BarButtonItem itemDetails;
}
}
| |
// 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 System.Reflection.Tests
{
public class ConstructorInfoInvokeArrayTests
{
[Fact]
public void Invoke_SZArrayConstructor()
{
Type type = Type.GetType("System.Object[]");
ConstructorInfo[] constructors = type.GetConstructors();
Assert.Equal(1, constructors.Length);
ConstructorInfo constructor = constructors[0];
int[] blength = new int[] { -100, -9, -1 };
for (int j = 0; j < blength.Length; j++)
{
Assert.Throws<OverflowException>(() => constructor.Invoke(new object[] { blength[j] }));
}
int[] glength = new int[] { 0, 1, 2, 3, 5, 10, 99, 65535 };
for (int j = 0; j < glength.Length; j++)
{
object[] arr = (object[])constructor.Invoke(new object[] { glength[j] });
Assert.Equal(0, arr.GetLowerBound(0));
Assert.Equal(glength[j] - 1, arr.GetUpperBound(0));
Assert.Equal(glength[j], arr.Length);
}
}
[Fact]
public void Invoke_1DArrayConstructor()
{
Type type = Type.GetType("System.Char[*]");
MethodInfo getLowerBound = type.GetMethod("GetLowerBound");
MethodInfo getUpperBound = type.GetMethod("GetUpperBound");
PropertyInfo getLength = type.GetProperty("Length");
ConstructorInfo[] constructors = type.GetConstructors();
Assert.Equal(2, constructors.Length);
for (int i = 0; i < constructors.Length; i++)
{
switch (constructors[i].GetParameters().Length)
{
case 1:
{
int[] invalidLengths = new int[] { -100, -9, -1 };
for (int j = 0; j < invalidLengths.Length; j++)
{
Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths[j] }));
}
int[] validLengths = new int[] { 0, 1, 2, 3, 5, 10, 99 };
for (int j = 0; j < validLengths.Length; j++)
{
char[] arr = (char[])constructors[i].Invoke(new object[] { validLengths[j] });
Assert.Equal(0, arr.GetLowerBound(0));
Assert.Equal(validLengths[j] - 1, arr.GetUpperBound(0));
Assert.Equal(validLengths[j], arr.Length);
}
}
break;
case 2:
{
int[] invalidLowerBounds = new int[] { -20, 0, 20 };
int[] invalidLengths = new int[] { -100, -9, -1 };
for (int j = 0; j < invalidLengths.Length; j++)
{
Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLowerBounds[j], invalidLengths[j] }));
}
int[] validLowerBounds = new int[] { 0, 1, -1, 2, -3, 5, -10, 99, 100 };
int[] validLengths = new int[] { 0, 1, 3, 2, 3, 5, 10, 99, 0 };
for (int j = 0; j < validLengths.Length; j++)
{
object o = constructors[i].Invoke(new object[] { validLowerBounds[j], validLengths[j] });
Assert.Equal(validLowerBounds[j], (int)getLowerBound.Invoke(o, new object[] { 0 }));
Assert.Equal(validLowerBounds[j] + validLengths[j] - 1, (int)getUpperBound.Invoke(o, new object[] { 0 }));
Assert.Equal(validLengths[j], (int)getLength.GetValue(o, null));
}
}
break;
}
}
}
[Fact]
public void Invoke_2DArrayConstructor()
{
Type type = Type.GetType("System.Int32[,]", false);
ConstructorInfo[] constructors = type.GetConstructors();
Assert.Equal(2, constructors.Length);
for (int i = 0; i < constructors.Length; i++)
{
switch (constructors[i].GetParameters().Length)
{
case 2:
{
int[] invalidLengths1 = new int[] { -11, -10, 0, 10 };
int[] invalidLengths2 = new int[] { -33, 0, -20, -33 };
for (int j = 0; j < invalidLengths1.Length; j++)
{
Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths1[j], invalidLengths2[j] }));
}
int[] validLengths1 = new int[] { 0, 0, 1, 1, 2, 1, 2, 10, 17, 99 };
int[] validLengths2 = new int[] { 0, 1, 0, 1, 1, 2, 2, 110, 5, 900 };
for (int j = 0; j < validLengths1.Length; j++)
{
int[,] arr = (int[,])constructors[i].Invoke(new object[] { validLengths1[j], validLengths2[j] });
Assert.Equal(0, arr.GetLowerBound(0));
Assert.Equal(validLengths1[j] - 1, arr.GetUpperBound(0));
Assert.Equal(0, arr.GetLowerBound(1));
Assert.Equal(validLengths2[j] - 1, arr.GetUpperBound(1));
Assert.Equal(validLengths1[j] * validLengths2[j], arr.Length);
}
}
break;
case 4:
{
int[] invalidLowerBounds1 = new int[] { 10, -10, 20 };
int[] invalidLowerBounds2 = new int[] { -10, 10, 0 };
int[] invalidLengths3 = new int[] { -11, -10, 0 };
int[] invalidLengths4 = new int[] { -33, 0, -20 };
for (int j = 0; j < invalidLengths3.Length; j++)
{
Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLowerBounds1[j], invalidLengths3[j], invalidLowerBounds2[j], invalidLengths4[j] }));
}
int baseNum = 3;
int baseNum4 = baseNum * baseNum * baseNum * baseNum;
int[] validLengths1 = new int[baseNum4];
int[] validLowerBounds1 = new int[baseNum4];
int[] validLengths2 = new int[baseNum4];
int[] validLowerBounds2 = new int[baseNum4];
int cnt = 0;
for (int pos1 = 0; pos1 < baseNum; pos1++)
for (int pos2 = 0; pos2 < baseNum; pos2++)
for (int pos3 = 0; pos3 < baseNum; pos3++)
for (int pos4 = 0; pos4 < baseNum; pos4++)
{
int saved = cnt;
validLengths1[cnt] = saved % baseNum;
saved = saved / baseNum;
validLengths2[cnt] = saved % baseNum;
saved = saved / baseNum;
validLowerBounds1[cnt] = saved % baseNum;
saved = saved / baseNum;
validLowerBounds2[cnt] = saved % baseNum;
cnt++;
}
for (int j = 0; j < validLengths2.Length; j++)
{
int[,] arr = (int[,])constructors[i].Invoke(new object[] { validLengths1[j], validLengths2[j], validLowerBounds1[j], validLowerBounds2[j] });
Assert.Equal(validLengths1[j], arr.GetLowerBound(0));
Assert.Equal(validLengths1[j] + validLengths2[j] - 1, arr.GetUpperBound(0));
Assert.Equal(validLowerBounds1[j], arr.GetLowerBound(1));
Assert.Equal(validLowerBounds1[j] + validLowerBounds2[j] - 1, arr.GetUpperBound(1));
Assert.Equal(validLengths2[j] * validLowerBounds2[j], arr.Length);
}
// Lower can be < 0
validLengths1 = new int[] { 10, 10, 65535, 40, 0, -10, -10, -20, -40, 0 };
validLowerBounds1 = new int[] { 5, 99, -100, 30, 4, -5, 99, 100, -30, 0 };
validLengths2 = new int[] { 1, 200, 2, 40, 0, 1, 200, 2, 40, 65535 };
validLowerBounds2 = new int[] { 5, 10, 1, 0, 4, 5, 65535, 1, 0, 4 };
for (int j = 0; j < validLengths2.Length; j++)
{
int[,] arr = (int[,])constructors[i].Invoke(new object[] { validLengths1[j], validLengths2[j], validLowerBounds1[j], validLowerBounds2[j] });
Assert.Equal(validLengths1[j], arr.GetLowerBound(0));
Assert.Equal(validLengths1[j] + validLengths2[j] - 1, arr.GetUpperBound(0));
Assert.Equal(validLowerBounds1[j], arr.GetLowerBound(1));
Assert.Equal(validLowerBounds1[j] + validLowerBounds2[j] - 1, arr.GetUpperBound(1));
Assert.Equal(validLengths2[j] * validLowerBounds2[j], arr.Length);
}
}
break;
}
}
}
[Fact]
public void Invoke_LargeDimensionalArrayConstructor()
{
Type type = Type.GetType("System.Type[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]");
ConstructorInfo[] cia = type.GetConstructors();
Assert.Equal(2, cia.Length);
Assert.Throws<TypeLoadException>(() => Type.GetType("System.Type[,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,]"));
}
[Fact]
public void Invoke_JaggedArrayConstructor()
{
Type type = Type.GetType("System.String[][]");
ConstructorInfo[] constructors = type.GetConstructors();
Assert.Equal(2, constructors.Length);
for (int i = 0; i < constructors.Length; i++)
{
switch (constructors[i].GetParameters().Length)
{
case 1:
{
int[] invalidLengths = new int[] { -11, -10, -99 };
for (int j = 0; j < invalidLengths.Length; j++)
{
Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths[j] }));
}
int[] validLengths = new int[] { 0, 1, 2, 10, 17, 99 };
for (int j = 0; j < validLengths.Length; j++)
{
string[][] arr = (string[][])constructors[i].Invoke(new object[] { validLengths[j] });
Assert.Equal(0, arr.GetLowerBound(0));
Assert.Equal(validLengths[j] - 1, arr.GetUpperBound(0));
Assert.Equal(validLengths[j], arr.Length);
}
}
break;
case 2:
{
int[] invalidLengths1 = new int[] { -11, -10, 10, 1 };
int[] invalidLengths2 = new int[] { -33, 0, -33, -1 };
for (int j = 0; j < invalidLengths1.Length; j++)
{
Assert.Throws<OverflowException>(() => constructors[i].Invoke(new object[] { invalidLengths1[j], invalidLengths2[j] }));
}
int[] validLengths1 = new int[] { 0, 0, 0, 1, 1, 2, 1, 2, 10, 17, 500 };
int[] validLengths2 = new int[] { -33, 0, 1, 0, 1, 1, 2, 2, 110, 5, 100 };
for (int j = 0; j < validLengths1.Length; j++)
{
string[][] arr = (string[][])constructors[i].Invoke(new object[] { validLengths1[j], validLengths2[j] });
Assert.Equal(0, arr.GetLowerBound(0));
Assert.Equal(validLengths1[j] - 1, arr.GetUpperBound(0));
Assert.Equal(validLengths1[j], arr.Length);
if (validLengths1[j] == 0)
{
Assert.Equal(arr.Length, 0);
}
else
{
Assert.Equal(0, arr[0].GetLowerBound(0));
Assert.Equal(validLengths2[j] - 1, arr[0].GetUpperBound(0));
Assert.Equal(validLengths2[j], arr[0].Length);
}
}
}
break;
}
}
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
OR OTHER DEALINGS IN THE SOFTWARE.
*********************************************************************/
namespace TUVienna.CS_CUP
{
using System.Collections;
/** This class represents a Set of symbols and provides a series of
* Set operations to manipulate them.
*
* @see java_cup.symbol
* @version last updated: 11/25/95
* @author Scott Hudson
* translated to C# 08.09.2003 by Samuel Imriska
*/
public class symbol_set
{
/*-----------------------------------------------------------*/
/*--- Constructor(s) ----------------------------------------*/
/*-----------------------------------------------------------*/
/** Constructor for an empty Set. */
public symbol_set() { }
/** Constructor for cloning from another Set.
* @param other the Set we are cloning from.
*/
public symbol_set(symbol_set other)
{
not_null(other);
_all = (Hashtable)other._all.Clone();
}
/*-----------------------------------------------------------*/
/*--- (Access to) Instance Variables ------------------------*/
/*-----------------------------------------------------------*/
/** A hash table to hold the Set. Symbols are keyed using their name string.
*/
protected Hashtable _all = new Hashtable(11);
/** Access to all elements of the Set. */
public IEnumerator all() {return _all.Values.GetEnumerator();}
/** size of the Set */
public int size() {return _all.Count;}
/*-----------------------------------------------------------*/
/*--- (Access to) Instance Variables ------------------------*/
/*-----------------------------------------------------------*/
/** Helper function to test for a null object and throw an exception
* if one is found.
* @param obj the object we are testing.
*/
protected void not_null(object obj)
{
if (obj == null)
throw new internal_error("Null object used in Set operation");
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Determine if the Set contains a particular symbol.
* @param sym the symbol we are looking for.
*/
public bool contains(symbol sym) {return _all.ContainsKey(sym.name());}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Determine if this Set is an (improper) subset of another.
* @param other the Set we are testing against.
*/
public bool is_subset_of(symbol_set other)
{
not_null(other);
/* walk down our Set and make sure every element is in the other */
IEnumerator e = all();
while ( e.MoveNext() )
if (!other.contains((symbol)e.Current))
return false;
/* they were all there */
return true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Determine if this Set is an (improper) superset of another.
* @param other the Set we are are testing against.
*/
public bool is_superset_of(symbol_set other)
{
not_null(other);
return other.is_subset_of(this);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Add a single symbol to the Set.
* @param sym the symbol we are adding.
* @return true if this changes the Set.
*/
public bool add(symbol sym)
{
// object previous;
not_null(sym);
/* put the object in */
try
{
_all.Add(sym.name(),sym);
}
catch
{
return false;
}
/* if we had a previous, this is no change */
//return previous == null;
return true;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Remove a single symbol if it is in the Set.
* @param sym the symbol we are removing.
*/
public void remove(symbol sym)
{
not_null(sym);
_all.Remove(sym.name());
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Add (union) in a complete Set.
* @param other the Set we are adding in.
* @return true if this changes the Set.
*/
public bool add(symbol_set other)
{
bool result = false;
not_null(other);
/* walk down the other Set and do the adds individually */
IEnumerator e = other.all();
while ( e.MoveNext())
result = add((symbol)e.Current) || result;
return result;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Remove (Set subtract) a complete Set.
* @param other the Set we are removing.
*/
public void remove(symbol_set other)
{
not_null(other);
/* walk down the other Set and do the removes individually */
IEnumerator e = other.all();
while ( e.MoveNext() )
remove((symbol)e.Current);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Equality comparison. */
public bool Equals(symbol_set other)
{
if (other == null || other.size() != size()) return false;
/* once we know they are the same size, then improper subset does test */
try
{
return is_subset_of(other);
}
catch (internal_error e)
{
/* can't throw the error (because super class doesn't), so we crash */
e.crash();
return false;
}
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Generic equality comparison. */
public override bool Equals(object other)
{
if (other.GetType()!=typeof(symbol_set))
return false;
else
return Equals((symbol_set)other);
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Compute a hash code. */
public override int GetHashCode()
{
int result = 0;
int cnt;
IEnumerator e;
/* hash together codes from at most first 5 elements */
e = all();
cnt=0;
while (e.MoveNext() && cnt<5 )
{
cnt++;
result ^= ((symbol)e.Current).GetHashCode();
}
return result;
}
/*. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .*/
/** Convert to a string. */
public override string ToString()
{
string result;
bool comma_flag;
result = "{";
comma_flag = false;
IEnumerator e = all();
while ( e.MoveNext() )
{
if (comma_flag)
result += ", ";
else
comma_flag = true;
result += ((symbol)e.Current).name();
}
result += "}";
return result;
}
/*-----------------------------------------------------------*/
}
}
| |
// ------------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the ""License""); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR
// CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR
// NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Threading.Tasks;
using Amqp;
using Amqp.Framing;
using Amqp.Listener;
using Amqp.Sasl;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Trace = Amqp.Trace;
using TraceLevel = Amqp.TraceLevel;
namespace Test.Amqp
{
[TestClass]
public class WebSocketTests
{
const string address = "ws://guest:guest@localhost:18080/test";
#if NETFX
[TestMethod]
public void WebSocketContainerHostTests()
{
int total = 0;
int passed = 0;
string[] excluded = new string[]
{
"ContainerHostCustomTransportTest"
};
foreach (var mi in typeof(ContainerHostTests).GetMethods())
{
if (mi.GetCustomAttributes(typeof(TestMethodAttribute), false).Length > 0 &&
mi.GetCustomAttributes(typeof(IgnoreAttribute), false).Length == 0 &&
!excluded.Contains(mi.Name))
{
total++;
ContainerHostTests test = new ContainerHostTests();
test.Uri = new System.Uri(address);
test.ClassInitialize();
try
{
mi.Invoke(test, new object[0]);
System.Diagnostics.Trace.WriteLine(mi.Name + " passed");
passed++;
}
catch (Exception exception)
{
System.Diagnostics.Trace.WriteLine(mi.Name + " failed: " + exception.ToString());
}
test.ClassCleanup();
}
}
Assert.AreEqual(total, passed, string.Format("Not all tests passed {0}/{1}", passed, total));
}
[TestMethod]
public async Task WebSocketSslMutalAuthTest()
{
string testName = "WebSocketSslMutalAuthTest";
string listenAddress = "wss://localhost:18081/" + testName + "/";
Uri uri = new Uri(listenAddress);
X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost");
string output;
int code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", uri.Host, uri.Port), out output);
if (code != 0)
{
string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable",
uri.Host, uri.Port, cert.Thumbprint, Guid.NewGuid());
code = Exec("netsh.exe", args, out output);
Assert.AreEqual(0, code, "failed to add ssl cert: " + output);
}
X509Certificate serviceCert = null;
X509Certificate clientCert = null;
ListenerLink listenerLink = null;
var linkProcessor = new TestLinkProcessor();
linkProcessor.SetHandler(a => { listenerLink = a.Link; return false; });
var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
host.Listeners[0].SASL.EnableExternalMechanism = true;
host.Listeners[0].SSL.ClientCertificateRequired = true;
host.Listeners[0].SSL.CheckCertificateRevocation = true;
host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return true; };
host.RegisterLinkProcessor(linkProcessor);
host.Open();
try
{
ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return true; };
var wssFactory = new WebSocketTransportFactory();
wssFactory.Options = o =>
{
o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, uri.Host));
};
ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory });
connectionFactory.SASL.Profile = SaslProfile.External;
Connection connection = await connectionFactory.CreateAsync(new Address(listenAddress));
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");
await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } });
await connection.CloseAsync();
Assert.IsTrue(serviceCert != null, "service cert not received");
Assert.IsTrue(clientCert != null, "client cert not received");
Assert.IsTrue(listenerLink != null, "link not attached");
IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal;
Assert.IsTrue(principal != null, "connection pricipal is null");
Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert");
}
finally
{
host.Close();
}
}
static int Exec(string cmd, string args, out string output)
{
ProcessStartInfo psi = new ProcessStartInfo(cmd, args);
psi.RedirectStandardOutput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.WaitForExit();
output = process.StandardOutput.ReadToEnd();
return process.ExitCode;
}
#endif
[TestMethod]
public async Task WebSocketSendReceiveAsync()
{
if (Environment.GetEnvironmentVariable("CoreBroker") == "1")
{
// No Websocket listener on .Net Core
return;
}
string testName = "WebSocketSendReceiveAsync";
// assuming it matches the broker's setup and port is not taken
Address wsAddress = new Address(address);
int nMsgs = 50;
ConnectionFactory connectionFactory = new ConnectionFactory(
new TransportProvider[] { new WebSocketTransportFactory() });
Connection connection = await connectionFactory.CreateAsync(wsAddress);
Session session = new Session(connection);
SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");
for (int i = 0; i < nMsgs; ++i)
{
Message message = new Message();
message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName };
message.ApplicationProperties = new ApplicationProperties();
message.ApplicationProperties["sn"] = i;
await sender.SendAsync(message);
}
ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");
for (int i = 0; i < nMsgs; ++i)
{
Message message = await receiver.ReceiveAsync();
Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]);
receiver.Accept(message);
}
await sender.CloseAsync();
await receiver.CloseAsync();
await session.CloseAsync();
await connection.CloseAsync();
}
}
}
| |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type CalendarCalendarViewCollectionRequest.
/// </summary>
public partial class CalendarCalendarViewCollectionRequest : BaseRequest, ICalendarCalendarViewCollectionRequest
{
/// <summary>
/// Constructs a new CalendarCalendarViewCollectionRequest.
/// </summary>
/// <param name="requestUrl">The URL for the built request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="options">Query and header option name value pairs for the request.</param>
public CalendarCalendarViewCollectionRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="calendarViewEvent">The Event to add.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event calendarViewEvent)
{
return this.AddAsync(calendarViewEvent, CancellationToken.None);
}
/// <summary>
/// Adds the specified Event to the collection via POST.
/// </summary>
/// <param name="calendarViewEvent">The Event to add.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created Event.</returns>
public System.Threading.Tasks.Task<Event> AddAsync(Event calendarViewEvent, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
return this.SendAsync<Event>(calendarViewEvent, cancellationToken);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <returns>The collection page.</returns>
public System.Threading.Tasks.Task<ICalendarCalendarViewCollectionPage> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the collection page.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The collection page.</returns>
public async System.Threading.Tasks.Task<ICalendarCalendarViewCollectionPage> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var response = await this.SendAsync<CalendarCalendarViewCollectionResponse>(null, cancellationToken).ConfigureAwait(false);
if (response != null && response.Value != null && response.Value.CurrentPage != null)
{
if (response.AdditionalData != null)
{
object nextPageLink;
response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink);
var nextPageLinkString = nextPageLink as string;
if (!string.IsNullOrEmpty(nextPageLinkString))
{
response.Value.InitializeNextPageRequest(
this.Client,
nextPageLinkString);
}
// Copy the additional data collection to the page itself so that information is not lost
response.Value.AdditionalData = response.AdditionalData;
}
return response.Value;
}
return null;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="expandExpression">The expression from which to calculate the expand value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Expand(Expression<Func<Event, object>> expandExpression)
{
if (expandExpression == null)
{
throw new ArgumentNullException(nameof(expandExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(expandExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$expand", value));
}
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="selectExpression">The expression from which to calculate the select value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Select(Expression<Func<Event, object>> selectExpression)
{
if (selectExpression == null)
{
throw new ArgumentNullException(nameof(selectExpression));
}
string error;
string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error);
if (value == null)
{
throw new ArgumentException(error, nameof(selectExpression));
}
else
{
this.QueryOptions.Add(new QueryOption("$select", value));
}
return this;
}
/// <summary>
/// Adds the specified top value to the request.
/// </summary>
/// <param name="value">The top value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Top(int value)
{
this.QueryOptions.Add(new QueryOption("$top", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified filter value to the request.
/// </summary>
/// <param name="value">The filter value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Filter(string value)
{
this.QueryOptions.Add(new QueryOption("$filter", value));
return this;
}
/// <summary>
/// Adds the specified skip value to the request.
/// </summary>
/// <param name="value">The skip value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest Skip(int value)
{
this.QueryOptions.Add(new QueryOption("$skip", value.ToString()));
return this;
}
/// <summary>
/// Adds the specified orderby value to the request.
/// </summary>
/// <param name="value">The orderby value.</param>
/// <returns>The request object to send.</returns>
public ICalendarCalendarViewCollectionRequest OrderBy(string value)
{
this.QueryOptions.Add(new QueryOption("$orderby", value));
return this;
}
}
}
| |
#region Copyright
//
// Nini Configuration Project.
// Copyright (C) 2006 Brent R. Matzelle. All rights reserved.
//
// This software is published under the terms of the MIT X11 license, a copy of
// which has been included with this distribution in the LICENSE.txt file.
//
#endregion
using System;
using System.IO;
using System.Collections;
using Nini.Util;
namespace Nini.Ini
{
#region IniFileType enumeration
/// <include file='IniDocument.xml' path='//Enum[@name="IniFileType"]/docs/*' />
public enum IniFileType
{
/// <include file='IniDocument.xml' path='//Enum[@name="IniFileType"]/Value[@name="Standard"]/docs/*' />
Standard,
/// <include file='IniDocument.xml' path='//Enum[@name="IniFileType"]/Value[@name="PythonStyle"]/docs/*' />
PythonStyle,
/// <include file='IniDocument.xml' path='//Enum[@name="IniFileType"]/Value[@name="SambaStyle"]/docs/*' />
SambaStyle,
/// <include file='IniDocument.xml' path='//Enum[@name="IniFileType"]/Value[@name="MysqlStyle"]/docs/*' />
MysqlStyle,
/// <include file='IniDocument.xml' path='//Enum[@name="IniFileType"]/Value[@name="WindowsStyle"]/docs/*' />
WindowsStyle
}
#endregion
/// <include file='IniDocument.xml' path='//Class[@name="IniDocument"]/docs/*' />
public class IniDocument
{
#region Private variables
IniSectionCollection sections = new IniSectionCollection ();
ArrayList initialComment = new ArrayList ();
IniFileType fileType = IniFileType.Standard;
#endregion
#region Public properties
/// <include file='IniDocument.xml' path='//Property[@name="FileType"]/docs/*' />
public IniFileType FileType
{
get { return fileType; }
set { fileType = value; }
}
#endregion
#region Constructors
/// <include file='IniDocument.xml' path='//Constructor[@name="ConstructorPath"]/docs/*' />
public IniDocument (string filePath)
{
fileType = IniFileType.Standard;
Load (filePath);
}
/// <include file='IniDocument.xml' path='//Constructor[@name="ConstructorPathType"]/docs/*' />
public IniDocument (string filePath, IniFileType type)
{
fileType = type;
Load (filePath);
}
/// <include file='IniDocument.xml' path='//Constructor[@name="ConstructorTextReader"]/docs/*' />
public IniDocument (TextReader reader)
{
fileType = IniFileType.Standard;
Load (reader);
}
/// <include file='IniDocument.xml' path='//Constructor[@name="ConstructorTextReaderType"]/docs/*' />
public IniDocument (TextReader reader, IniFileType type)
{
fileType = type;
Load (reader);
}
/// <include file='IniDocument.xml' path='//Constructor[@name="ConstructorStream"]/docs/*' />
public IniDocument (Stream stream)
{
fileType = IniFileType.Standard;
Load (stream);
}
/// <include file='IniDocument.xml' path='//Constructor[@name="ConstructorStreamType"]/docs/*' />
public IniDocument (Stream stream, IniFileType type)
{
fileType = type;
Load (stream);
}
/// <include file='IniDocument.xml' path='//Constructor[@name="ConstructorIniReader"]/docs/*' />
public IniDocument (IniReader reader)
{
fileType = IniFileType.Standard;
Load (reader);
}
/// <include file='IniDocument.xml' path='//Constructor[@name="Constructor"]/docs/*' />
public IniDocument ()
{
}
#endregion
#region Public methods
/// <include file='IniDocument.xml' path='//Method[@name="LoadPath"]/docs/*' />
public void Load (string filePath)
{
Load (new StreamReader (filePath));
}
/// <include file='IniDocument.xml' path='//Method[@name="LoadTextReader"]/docs/*' />
public void Load (TextReader reader)
{
Load (GetIniReader (reader, fileType));
}
/// <include file='IniDocument.xml' path='//Method[@name="LoadStream"]/docs/*' />
public void Load (Stream stream)
{
Load (new StreamReader (stream));
}
/// <include file='IniDocument.xml' path='//Method[@name="LoadIniReader"]/docs/*' />
public void Load (IniReader reader)
{
LoadReader (reader);
}
/// <include file='IniSection.xml' path='//Property[@name="Comment"]/docs/*' />
public IniSectionCollection Sections
{
get { return sections; }
}
/// <include file='IniDocument.xml' path='//Method[@name="SaveTextWriter"]/docs/*' />
public void Save (TextWriter textWriter)
{
IniWriter writer = GetIniWriter (textWriter, fileType);
IniItem item = null;
IniSection section = null;
foreach (string comment in initialComment)
{
writer.WriteEmpty (comment);
}
for (int j = 0; j < sections.Count; j++)
{
section = sections[j];
writer.WriteSection (section.Name, section.Comment);
for (int i = 0; i < section.ItemCount; i++)
{
item = section.GetItem (i);
switch (item.Type)
{
case IniType.Key:
writer.WriteKey (item.Name, item.Value, item.Comment);
break;
case IniType.Empty:
writer.WriteEmpty (item.Comment);
break;
}
}
}
writer.Close ();
}
/// <include file='IniDocument.xml' path='//Method[@name="SavePath"]/docs/*' />
public void Save (string filePath)
{
StreamWriter writer = new StreamWriter (filePath);
Save (writer);
writer.Close ();
}
/// <include file='IniDocument.xml' path='//Method[@name="SaveStream"]/docs/*' />
public void Save (Stream stream)
{
Save (new StreamWriter (stream));
}
#endregion
#region Private methods
/// <summary>
/// Loads the file not saving comments.
/// </summary>
private void LoadReader (IniReader reader)
{
reader.IgnoreComments = false;
bool sectionFound = false;
IniSection section = null;
try {
while (reader.Read ())
{
switch (reader.Type)
{
case IniType.Empty:
if (!sectionFound) {
initialComment.Add (reader.Comment);
} else {
section.Set (reader.Comment);
}
break;
case IniType.Section:
sectionFound = true;
// If section already exists then overwrite it
if (sections[reader.Name] != null) {
sections.Remove (reader.Name);
}
section = new IniSection (reader.Name, reader.Comment);
sections.Add (section);
break;
case IniType.Key:
if (section.GetValue (reader.Name) == null) {
section.Set (reader.Name, reader.Value, reader.Comment);
}
break;
}
}
} catch (Exception ex) {
throw ex;
} finally {
// Always close the file
reader.Close ();
}
}
/// <summary>
/// Returns a proper INI reader depending upon the type parameter.
/// </summary>
private IniReader GetIniReader (TextReader reader, IniFileType type)
{
IniReader result = new IniReader (reader);
switch (type)
{
case IniFileType.Standard:
// do nothing
break;
case IniFileType.PythonStyle:
result.AcceptCommentAfterKey = false;
result.SetCommentDelimiters (new char[] { ';', '#' });
result.SetAssignDelimiters (new char[] { ':' });
break;
case IniFileType.SambaStyle:
result.AcceptCommentAfterKey = false;
result.SetCommentDelimiters (new char[] { ';', '#' });
result.LineContinuation = true;
break;
case IniFileType.MysqlStyle:
result.AcceptCommentAfterKey = false;
result.AcceptNoAssignmentOperator = true;
result.SetCommentDelimiters (new char[] { '#' });
result.SetAssignDelimiters (new char[] { ':', '=' });
break;
case IniFileType.WindowsStyle:
result.ConsumeAllKeyText = true;
break;
}
return result;
}
/// <summary>
/// Returns a proper IniWriter depending upon the type parameter.
/// </summary>
private IniWriter GetIniWriter (TextWriter reader, IniFileType type)
{
IniWriter result = new IniWriter (reader);
switch (type)
{
case IniFileType.Standard:
case IniFileType.WindowsStyle:
// do nothing
break;
case IniFileType.PythonStyle:
result.AssignDelimiter = ':';
result.CommentDelimiter = '#';
break;
case IniFileType.SambaStyle:
case IniFileType.MysqlStyle:
result.AssignDelimiter = '=';
result.CommentDelimiter = '#';
break;
}
return result;
}
#endregion
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// General Ledger Budgets Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class GLBUDGDataSet : EduHubDataSet<GLBUDG>
{
/// <inheritdoc />
public override string Name { get { return "GLBUDG"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal GLBUDGDataSet(EduHubContext Context)
: base(Context)
{
Index_BUDGETKEY = new Lazy<Dictionary<string, GLBUDG>>(() => this.ToDictionary(i => i.BUDGETKEY));
Index_CODE = new Lazy<NullDictionary<string, IReadOnlyList<GLBUDG>>>(() => this.ToGroupedNullDictionary(i => i.CODE));
Index_INITIATIVE = new Lazy<NullDictionary<string, IReadOnlyList<GLBUDG>>>(() => this.ToGroupedNullDictionary(i => i.INITIATIVE));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="GLBUDG" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="GLBUDG" /> fields for each CSV column header</returns>
internal override Action<GLBUDG, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<GLBUDG, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "BUDGETKEY":
mapper[i] = (e, v) => e.BUDGETKEY = v;
break;
case "SUBPROGRAM":
mapper[i] = (e, v) => e.SUBPROGRAM = v;
break;
case "TITLE":
mapper[i] = (e, v) => e.TITLE = v;
break;
case "CODE":
mapper[i] = (e, v) => e.CODE = v;
break;
case "GL_PROGRAM":
mapper[i] = (e, v) => e.GL_PROGRAM = v;
break;
case "INITIATIVE":
mapper[i] = (e, v) => e.INITIATIVE = v;
break;
case "CURR01":
mapper[i] = (e, v) => e.CURR01 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR02":
mapper[i] = (e, v) => e.CURR02 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR03":
mapper[i] = (e, v) => e.CURR03 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR04":
mapper[i] = (e, v) => e.CURR04 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR05":
mapper[i] = (e, v) => e.CURR05 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR06":
mapper[i] = (e, v) => e.CURR06 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR07":
mapper[i] = (e, v) => e.CURR07 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR08":
mapper[i] = (e, v) => e.CURR08 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR09":
mapper[i] = (e, v) => e.CURR09 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR10":
mapper[i] = (e, v) => e.CURR10 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR11":
mapper[i] = (e, v) => e.CURR11 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "CURR12":
mapper[i] = (e, v) => e.CURR12 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "OPBAL":
mapper[i] = (e, v) => e.OPBAL = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR01":
mapper[i] = (e, v) => e.LASTYR01 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR02":
mapper[i] = (e, v) => e.LASTYR02 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR03":
mapper[i] = (e, v) => e.LASTYR03 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR04":
mapper[i] = (e, v) => e.LASTYR04 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR05":
mapper[i] = (e, v) => e.LASTYR05 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR06":
mapper[i] = (e, v) => e.LASTYR06 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR07":
mapper[i] = (e, v) => e.LASTYR07 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR08":
mapper[i] = (e, v) => e.LASTYR08 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR09":
mapper[i] = (e, v) => e.LASTYR09 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR10":
mapper[i] = (e, v) => e.LASTYR10 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR11":
mapper[i] = (e, v) => e.LASTYR11 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTYR12":
mapper[i] = (e, v) => e.LASTYR12 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG01":
mapper[i] = (e, v) => e.BUDG01 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG02":
mapper[i] = (e, v) => e.BUDG02 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG03":
mapper[i] = (e, v) => e.BUDG03 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG04":
mapper[i] = (e, v) => e.BUDG04 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG05":
mapper[i] = (e, v) => e.BUDG05 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG06":
mapper[i] = (e, v) => e.BUDG06 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG07":
mapper[i] = (e, v) => e.BUDG07 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG08":
mapper[i] = (e, v) => e.BUDG08 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG09":
mapper[i] = (e, v) => e.BUDG09 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG10":
mapper[i] = (e, v) => e.BUDG10 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG11":
mapper[i] = (e, v) => e.BUDG11 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "BUDG12":
mapper[i] = (e, v) => e.BUDG12 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG01":
mapper[i] = (e, v) => e.NEXTBUDG01 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG02":
mapper[i] = (e, v) => e.NEXTBUDG02 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG03":
mapper[i] = (e, v) => e.NEXTBUDG03 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG04":
mapper[i] = (e, v) => e.NEXTBUDG04 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG05":
mapper[i] = (e, v) => e.NEXTBUDG05 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG06":
mapper[i] = (e, v) => e.NEXTBUDG06 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG07":
mapper[i] = (e, v) => e.NEXTBUDG07 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG08":
mapper[i] = (e, v) => e.NEXTBUDG08 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG09":
mapper[i] = (e, v) => e.NEXTBUDG09 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG10":
mapper[i] = (e, v) => e.NEXTBUDG10 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG11":
mapper[i] = (e, v) => e.NEXTBUDG11 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXTBUDG12":
mapper[i] = (e, v) => e.NEXTBUDG12 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "ANNUALBUDG":
mapper[i] = (e, v) => e.ANNUALBUDG = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "NEXT_ANN_BUDG":
mapper[i] = (e, v) => e.NEXT_ANN_BUDG = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG01":
mapper[i] = (e, v) => e.LASTBUDG01 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG02":
mapper[i] = (e, v) => e.LASTBUDG02 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG03":
mapper[i] = (e, v) => e.LASTBUDG03 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG04":
mapper[i] = (e, v) => e.LASTBUDG04 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG05":
mapper[i] = (e, v) => e.LASTBUDG05 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG06":
mapper[i] = (e, v) => e.LASTBUDG06 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG07":
mapper[i] = (e, v) => e.LASTBUDG07 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG08":
mapper[i] = (e, v) => e.LASTBUDG08 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG09":
mapper[i] = (e, v) => e.LASTBUDG09 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG10":
mapper[i] = (e, v) => e.LASTBUDG10 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG11":
mapper[i] = (e, v) => e.LASTBUDG11 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LASTBUDG12":
mapper[i] = (e, v) => e.LASTBUDG12 = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "LAST_ANN_BUDG":
mapper[i] = (e, v) => e.LAST_ANN_BUDG = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "IMPORTED":
mapper[i] = (e, v) => e.IMPORTED = v;
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="GLBUDG" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="GLBUDG" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="GLBUDG" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{GLBUDG}"/> of entities</returns>
internal override IEnumerable<GLBUDG> ApplyDeltaEntities(IEnumerable<GLBUDG> Entities, List<GLBUDG> DeltaEntities)
{
HashSet<string> Index_BUDGETKEY = new HashSet<string>(DeltaEntities.Select(i => i.BUDGETKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.BUDGETKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_BUDGETKEY.Remove(entity.BUDGETKEY);
if (entity.BUDGETKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<string, GLBUDG>> Index_BUDGETKEY;
private Lazy<NullDictionary<string, IReadOnlyList<GLBUDG>>> Index_CODE;
private Lazy<NullDictionary<string, IReadOnlyList<GLBUDG>>> Index_INITIATIVE;
#endregion
#region Index Methods
/// <summary>
/// Find GLBUDG by BUDGETKEY field
/// </summary>
/// <param name="BUDGETKEY">BUDGETKEY value used to find GLBUDG</param>
/// <returns>Related GLBUDG entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public GLBUDG FindByBUDGETKEY(string BUDGETKEY)
{
return Index_BUDGETKEY.Value[BUDGETKEY];
}
/// <summary>
/// Attempt to find GLBUDG by BUDGETKEY field
/// </summary>
/// <param name="BUDGETKEY">BUDGETKEY value used to find GLBUDG</param>
/// <param name="Value">Related GLBUDG entity</param>
/// <returns>True if the related GLBUDG entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByBUDGETKEY(string BUDGETKEY, out GLBUDG Value)
{
return Index_BUDGETKEY.Value.TryGetValue(BUDGETKEY, out Value);
}
/// <summary>
/// Attempt to find GLBUDG by BUDGETKEY field
/// </summary>
/// <param name="BUDGETKEY">BUDGETKEY value used to find GLBUDG</param>
/// <returns>Related GLBUDG entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public GLBUDG TryFindByBUDGETKEY(string BUDGETKEY)
{
GLBUDG value;
if (Index_BUDGETKEY.Value.TryGetValue(BUDGETKEY, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find GLBUDG by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find GLBUDG</param>
/// <returns>List of related GLBUDG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<GLBUDG> FindByCODE(string CODE)
{
return Index_CODE.Value[CODE];
}
/// <summary>
/// Attempt to find GLBUDG by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find GLBUDG</param>
/// <param name="Value">List of related GLBUDG entities</param>
/// <returns>True if the list of related GLBUDG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByCODE(string CODE, out IReadOnlyList<GLBUDG> Value)
{
return Index_CODE.Value.TryGetValue(CODE, out Value);
}
/// <summary>
/// Attempt to find GLBUDG by CODE field
/// </summary>
/// <param name="CODE">CODE value used to find GLBUDG</param>
/// <returns>List of related GLBUDG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<GLBUDG> TryFindByCODE(string CODE)
{
IReadOnlyList<GLBUDG> value;
if (Index_CODE.Value.TryGetValue(CODE, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find GLBUDG by INITIATIVE field
/// </summary>
/// <param name="INITIATIVE">INITIATIVE value used to find GLBUDG</param>
/// <returns>List of related GLBUDG entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<GLBUDG> FindByINITIATIVE(string INITIATIVE)
{
return Index_INITIATIVE.Value[INITIATIVE];
}
/// <summary>
/// Attempt to find GLBUDG by INITIATIVE field
/// </summary>
/// <param name="INITIATIVE">INITIATIVE value used to find GLBUDG</param>
/// <param name="Value">List of related GLBUDG entities</param>
/// <returns>True if the list of related GLBUDG entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByINITIATIVE(string INITIATIVE, out IReadOnlyList<GLBUDG> Value)
{
return Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out Value);
}
/// <summary>
/// Attempt to find GLBUDG by INITIATIVE field
/// </summary>
/// <param name="INITIATIVE">INITIATIVE value used to find GLBUDG</param>
/// <returns>List of related GLBUDG entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<GLBUDG> TryFindByINITIATIVE(string INITIATIVE)
{
IReadOnlyList<GLBUDG> value;
if (Index_INITIATIVE.Value.TryGetValue(INITIATIVE, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a GLBUDG table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[GLBUDG]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[GLBUDG](
[BUDGETKEY] varchar(15) NOT NULL,
[SUBPROGRAM] varchar(4) NULL,
[TITLE] varchar(30) NULL,
[CODE] varchar(10) NULL,
[GL_PROGRAM] varchar(3) NULL,
[INITIATIVE] varchar(3) NULL,
[CURR01] money NULL,
[CURR02] money NULL,
[CURR03] money NULL,
[CURR04] money NULL,
[CURR05] money NULL,
[CURR06] money NULL,
[CURR07] money NULL,
[CURR08] money NULL,
[CURR09] money NULL,
[CURR10] money NULL,
[CURR11] money NULL,
[CURR12] money NULL,
[OPBAL] money NULL,
[LASTYR01] money NULL,
[LASTYR02] money NULL,
[LASTYR03] money NULL,
[LASTYR04] money NULL,
[LASTYR05] money NULL,
[LASTYR06] money NULL,
[LASTYR07] money NULL,
[LASTYR08] money NULL,
[LASTYR09] money NULL,
[LASTYR10] money NULL,
[LASTYR11] money NULL,
[LASTYR12] money NULL,
[BUDG01] money NULL,
[BUDG02] money NULL,
[BUDG03] money NULL,
[BUDG04] money NULL,
[BUDG05] money NULL,
[BUDG06] money NULL,
[BUDG07] money NULL,
[BUDG08] money NULL,
[BUDG09] money NULL,
[BUDG10] money NULL,
[BUDG11] money NULL,
[BUDG12] money NULL,
[NEXTBUDG01] money NULL,
[NEXTBUDG02] money NULL,
[NEXTBUDG03] money NULL,
[NEXTBUDG04] money NULL,
[NEXTBUDG05] money NULL,
[NEXTBUDG06] money NULL,
[NEXTBUDG07] money NULL,
[NEXTBUDG08] money NULL,
[NEXTBUDG09] money NULL,
[NEXTBUDG10] money NULL,
[NEXTBUDG11] money NULL,
[NEXTBUDG12] money NULL,
[ANNUALBUDG] money NULL,
[NEXT_ANN_BUDG] money NULL,
[LASTBUDG01] money NULL,
[LASTBUDG02] money NULL,
[LASTBUDG03] money NULL,
[LASTBUDG04] money NULL,
[LASTBUDG05] money NULL,
[LASTBUDG06] money NULL,
[LASTBUDG07] money NULL,
[LASTBUDG08] money NULL,
[LASTBUDG09] money NULL,
[LASTBUDG10] money NULL,
[LASTBUDG11] money NULL,
[LASTBUDG12] money NULL,
[LAST_ANN_BUDG] money NULL,
[IMPORTED] varchar(1) NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [GLBUDG_Index_BUDGETKEY] PRIMARY KEY CLUSTERED (
[BUDGETKEY] ASC
)
);
CREATE NONCLUSTERED INDEX [GLBUDG_Index_CODE] ON [dbo].[GLBUDG]
(
[CODE] ASC
);
CREATE NONCLUSTERED INDEX [GLBUDG_Index_INITIATIVE] ON [dbo].[GLBUDG]
(
[INITIATIVE] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLBUDG]') AND name = N'GLBUDG_Index_CODE')
ALTER INDEX [GLBUDG_Index_CODE] ON [dbo].[GLBUDG] DISABLE;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLBUDG]') AND name = N'GLBUDG_Index_INITIATIVE')
ALTER INDEX [GLBUDG_Index_INITIATIVE] ON [dbo].[GLBUDG] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLBUDG]') AND name = N'GLBUDG_Index_CODE')
ALTER INDEX [GLBUDG_Index_CODE] ON [dbo].[GLBUDG] REBUILD PARTITION = ALL;
IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[GLBUDG]') AND name = N'GLBUDG_Index_INITIATIVE')
ALTER INDEX [GLBUDG_Index_INITIATIVE] ON [dbo].[GLBUDG] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="GLBUDG"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="GLBUDG"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<GLBUDG> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<string> Index_BUDGETKEY = new List<string>();
foreach (var entity in Entities)
{
Index_BUDGETKEY.Add(entity.BUDGETKEY);
}
builder.AppendLine("DELETE [dbo].[GLBUDG] WHERE");
// Index_BUDGETKEY
builder.Append("[BUDGETKEY] IN (");
for (int index = 0; index < Index_BUDGETKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// BUDGETKEY
var parameterBUDGETKEY = $"@p{parameterIndex++}";
builder.Append(parameterBUDGETKEY);
command.Parameters.Add(parameterBUDGETKEY, SqlDbType.VarChar, 15).Value = Index_BUDGETKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the GLBUDG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the GLBUDG data set</returns>
public override EduHubDataSetDataReader<GLBUDG> GetDataSetDataReader()
{
return new GLBUDGDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the GLBUDG data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the GLBUDG data set</returns>
public override EduHubDataSetDataReader<GLBUDG> GetDataSetDataReader(List<GLBUDG> Entities)
{
return new GLBUDGDataReader(new EduHubDataSetLoadedReader<GLBUDG>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class GLBUDGDataReader : EduHubDataSetDataReader<GLBUDG>
{
public GLBUDGDataReader(IEduHubDataSetReader<GLBUDG> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 74; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // BUDGETKEY
return Current.BUDGETKEY;
case 1: // SUBPROGRAM
return Current.SUBPROGRAM;
case 2: // TITLE
return Current.TITLE;
case 3: // CODE
return Current.CODE;
case 4: // GL_PROGRAM
return Current.GL_PROGRAM;
case 5: // INITIATIVE
return Current.INITIATIVE;
case 6: // CURR01
return Current.CURR01;
case 7: // CURR02
return Current.CURR02;
case 8: // CURR03
return Current.CURR03;
case 9: // CURR04
return Current.CURR04;
case 10: // CURR05
return Current.CURR05;
case 11: // CURR06
return Current.CURR06;
case 12: // CURR07
return Current.CURR07;
case 13: // CURR08
return Current.CURR08;
case 14: // CURR09
return Current.CURR09;
case 15: // CURR10
return Current.CURR10;
case 16: // CURR11
return Current.CURR11;
case 17: // CURR12
return Current.CURR12;
case 18: // OPBAL
return Current.OPBAL;
case 19: // LASTYR01
return Current.LASTYR01;
case 20: // LASTYR02
return Current.LASTYR02;
case 21: // LASTYR03
return Current.LASTYR03;
case 22: // LASTYR04
return Current.LASTYR04;
case 23: // LASTYR05
return Current.LASTYR05;
case 24: // LASTYR06
return Current.LASTYR06;
case 25: // LASTYR07
return Current.LASTYR07;
case 26: // LASTYR08
return Current.LASTYR08;
case 27: // LASTYR09
return Current.LASTYR09;
case 28: // LASTYR10
return Current.LASTYR10;
case 29: // LASTYR11
return Current.LASTYR11;
case 30: // LASTYR12
return Current.LASTYR12;
case 31: // BUDG01
return Current.BUDG01;
case 32: // BUDG02
return Current.BUDG02;
case 33: // BUDG03
return Current.BUDG03;
case 34: // BUDG04
return Current.BUDG04;
case 35: // BUDG05
return Current.BUDG05;
case 36: // BUDG06
return Current.BUDG06;
case 37: // BUDG07
return Current.BUDG07;
case 38: // BUDG08
return Current.BUDG08;
case 39: // BUDG09
return Current.BUDG09;
case 40: // BUDG10
return Current.BUDG10;
case 41: // BUDG11
return Current.BUDG11;
case 42: // BUDG12
return Current.BUDG12;
case 43: // NEXTBUDG01
return Current.NEXTBUDG01;
case 44: // NEXTBUDG02
return Current.NEXTBUDG02;
case 45: // NEXTBUDG03
return Current.NEXTBUDG03;
case 46: // NEXTBUDG04
return Current.NEXTBUDG04;
case 47: // NEXTBUDG05
return Current.NEXTBUDG05;
case 48: // NEXTBUDG06
return Current.NEXTBUDG06;
case 49: // NEXTBUDG07
return Current.NEXTBUDG07;
case 50: // NEXTBUDG08
return Current.NEXTBUDG08;
case 51: // NEXTBUDG09
return Current.NEXTBUDG09;
case 52: // NEXTBUDG10
return Current.NEXTBUDG10;
case 53: // NEXTBUDG11
return Current.NEXTBUDG11;
case 54: // NEXTBUDG12
return Current.NEXTBUDG12;
case 55: // ANNUALBUDG
return Current.ANNUALBUDG;
case 56: // NEXT_ANN_BUDG
return Current.NEXT_ANN_BUDG;
case 57: // LASTBUDG01
return Current.LASTBUDG01;
case 58: // LASTBUDG02
return Current.LASTBUDG02;
case 59: // LASTBUDG03
return Current.LASTBUDG03;
case 60: // LASTBUDG04
return Current.LASTBUDG04;
case 61: // LASTBUDG05
return Current.LASTBUDG05;
case 62: // LASTBUDG06
return Current.LASTBUDG06;
case 63: // LASTBUDG07
return Current.LASTBUDG07;
case 64: // LASTBUDG08
return Current.LASTBUDG08;
case 65: // LASTBUDG09
return Current.LASTBUDG09;
case 66: // LASTBUDG10
return Current.LASTBUDG10;
case 67: // LASTBUDG11
return Current.LASTBUDG11;
case 68: // LASTBUDG12
return Current.LASTBUDG12;
case 69: // LAST_ANN_BUDG
return Current.LAST_ANN_BUDG;
case 70: // IMPORTED
return Current.IMPORTED;
case 71: // LW_DATE
return Current.LW_DATE;
case 72: // LW_TIME
return Current.LW_TIME;
case 73: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // SUBPROGRAM
return Current.SUBPROGRAM == null;
case 2: // TITLE
return Current.TITLE == null;
case 3: // CODE
return Current.CODE == null;
case 4: // GL_PROGRAM
return Current.GL_PROGRAM == null;
case 5: // INITIATIVE
return Current.INITIATIVE == null;
case 6: // CURR01
return Current.CURR01 == null;
case 7: // CURR02
return Current.CURR02 == null;
case 8: // CURR03
return Current.CURR03 == null;
case 9: // CURR04
return Current.CURR04 == null;
case 10: // CURR05
return Current.CURR05 == null;
case 11: // CURR06
return Current.CURR06 == null;
case 12: // CURR07
return Current.CURR07 == null;
case 13: // CURR08
return Current.CURR08 == null;
case 14: // CURR09
return Current.CURR09 == null;
case 15: // CURR10
return Current.CURR10 == null;
case 16: // CURR11
return Current.CURR11 == null;
case 17: // CURR12
return Current.CURR12 == null;
case 18: // OPBAL
return Current.OPBAL == null;
case 19: // LASTYR01
return Current.LASTYR01 == null;
case 20: // LASTYR02
return Current.LASTYR02 == null;
case 21: // LASTYR03
return Current.LASTYR03 == null;
case 22: // LASTYR04
return Current.LASTYR04 == null;
case 23: // LASTYR05
return Current.LASTYR05 == null;
case 24: // LASTYR06
return Current.LASTYR06 == null;
case 25: // LASTYR07
return Current.LASTYR07 == null;
case 26: // LASTYR08
return Current.LASTYR08 == null;
case 27: // LASTYR09
return Current.LASTYR09 == null;
case 28: // LASTYR10
return Current.LASTYR10 == null;
case 29: // LASTYR11
return Current.LASTYR11 == null;
case 30: // LASTYR12
return Current.LASTYR12 == null;
case 31: // BUDG01
return Current.BUDG01 == null;
case 32: // BUDG02
return Current.BUDG02 == null;
case 33: // BUDG03
return Current.BUDG03 == null;
case 34: // BUDG04
return Current.BUDG04 == null;
case 35: // BUDG05
return Current.BUDG05 == null;
case 36: // BUDG06
return Current.BUDG06 == null;
case 37: // BUDG07
return Current.BUDG07 == null;
case 38: // BUDG08
return Current.BUDG08 == null;
case 39: // BUDG09
return Current.BUDG09 == null;
case 40: // BUDG10
return Current.BUDG10 == null;
case 41: // BUDG11
return Current.BUDG11 == null;
case 42: // BUDG12
return Current.BUDG12 == null;
case 43: // NEXTBUDG01
return Current.NEXTBUDG01 == null;
case 44: // NEXTBUDG02
return Current.NEXTBUDG02 == null;
case 45: // NEXTBUDG03
return Current.NEXTBUDG03 == null;
case 46: // NEXTBUDG04
return Current.NEXTBUDG04 == null;
case 47: // NEXTBUDG05
return Current.NEXTBUDG05 == null;
case 48: // NEXTBUDG06
return Current.NEXTBUDG06 == null;
case 49: // NEXTBUDG07
return Current.NEXTBUDG07 == null;
case 50: // NEXTBUDG08
return Current.NEXTBUDG08 == null;
case 51: // NEXTBUDG09
return Current.NEXTBUDG09 == null;
case 52: // NEXTBUDG10
return Current.NEXTBUDG10 == null;
case 53: // NEXTBUDG11
return Current.NEXTBUDG11 == null;
case 54: // NEXTBUDG12
return Current.NEXTBUDG12 == null;
case 55: // ANNUALBUDG
return Current.ANNUALBUDG == null;
case 56: // NEXT_ANN_BUDG
return Current.NEXT_ANN_BUDG == null;
case 57: // LASTBUDG01
return Current.LASTBUDG01 == null;
case 58: // LASTBUDG02
return Current.LASTBUDG02 == null;
case 59: // LASTBUDG03
return Current.LASTBUDG03 == null;
case 60: // LASTBUDG04
return Current.LASTBUDG04 == null;
case 61: // LASTBUDG05
return Current.LASTBUDG05 == null;
case 62: // LASTBUDG06
return Current.LASTBUDG06 == null;
case 63: // LASTBUDG07
return Current.LASTBUDG07 == null;
case 64: // LASTBUDG08
return Current.LASTBUDG08 == null;
case 65: // LASTBUDG09
return Current.LASTBUDG09 == null;
case 66: // LASTBUDG10
return Current.LASTBUDG10 == null;
case 67: // LASTBUDG11
return Current.LASTBUDG11 == null;
case 68: // LASTBUDG12
return Current.LASTBUDG12 == null;
case 69: // LAST_ANN_BUDG
return Current.LAST_ANN_BUDG == null;
case 70: // IMPORTED
return Current.IMPORTED == null;
case 71: // LW_DATE
return Current.LW_DATE == null;
case 72: // LW_TIME
return Current.LW_TIME == null;
case 73: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // BUDGETKEY
return "BUDGETKEY";
case 1: // SUBPROGRAM
return "SUBPROGRAM";
case 2: // TITLE
return "TITLE";
case 3: // CODE
return "CODE";
case 4: // GL_PROGRAM
return "GL_PROGRAM";
case 5: // INITIATIVE
return "INITIATIVE";
case 6: // CURR01
return "CURR01";
case 7: // CURR02
return "CURR02";
case 8: // CURR03
return "CURR03";
case 9: // CURR04
return "CURR04";
case 10: // CURR05
return "CURR05";
case 11: // CURR06
return "CURR06";
case 12: // CURR07
return "CURR07";
case 13: // CURR08
return "CURR08";
case 14: // CURR09
return "CURR09";
case 15: // CURR10
return "CURR10";
case 16: // CURR11
return "CURR11";
case 17: // CURR12
return "CURR12";
case 18: // OPBAL
return "OPBAL";
case 19: // LASTYR01
return "LASTYR01";
case 20: // LASTYR02
return "LASTYR02";
case 21: // LASTYR03
return "LASTYR03";
case 22: // LASTYR04
return "LASTYR04";
case 23: // LASTYR05
return "LASTYR05";
case 24: // LASTYR06
return "LASTYR06";
case 25: // LASTYR07
return "LASTYR07";
case 26: // LASTYR08
return "LASTYR08";
case 27: // LASTYR09
return "LASTYR09";
case 28: // LASTYR10
return "LASTYR10";
case 29: // LASTYR11
return "LASTYR11";
case 30: // LASTYR12
return "LASTYR12";
case 31: // BUDG01
return "BUDG01";
case 32: // BUDG02
return "BUDG02";
case 33: // BUDG03
return "BUDG03";
case 34: // BUDG04
return "BUDG04";
case 35: // BUDG05
return "BUDG05";
case 36: // BUDG06
return "BUDG06";
case 37: // BUDG07
return "BUDG07";
case 38: // BUDG08
return "BUDG08";
case 39: // BUDG09
return "BUDG09";
case 40: // BUDG10
return "BUDG10";
case 41: // BUDG11
return "BUDG11";
case 42: // BUDG12
return "BUDG12";
case 43: // NEXTBUDG01
return "NEXTBUDG01";
case 44: // NEXTBUDG02
return "NEXTBUDG02";
case 45: // NEXTBUDG03
return "NEXTBUDG03";
case 46: // NEXTBUDG04
return "NEXTBUDG04";
case 47: // NEXTBUDG05
return "NEXTBUDG05";
case 48: // NEXTBUDG06
return "NEXTBUDG06";
case 49: // NEXTBUDG07
return "NEXTBUDG07";
case 50: // NEXTBUDG08
return "NEXTBUDG08";
case 51: // NEXTBUDG09
return "NEXTBUDG09";
case 52: // NEXTBUDG10
return "NEXTBUDG10";
case 53: // NEXTBUDG11
return "NEXTBUDG11";
case 54: // NEXTBUDG12
return "NEXTBUDG12";
case 55: // ANNUALBUDG
return "ANNUALBUDG";
case 56: // NEXT_ANN_BUDG
return "NEXT_ANN_BUDG";
case 57: // LASTBUDG01
return "LASTBUDG01";
case 58: // LASTBUDG02
return "LASTBUDG02";
case 59: // LASTBUDG03
return "LASTBUDG03";
case 60: // LASTBUDG04
return "LASTBUDG04";
case 61: // LASTBUDG05
return "LASTBUDG05";
case 62: // LASTBUDG06
return "LASTBUDG06";
case 63: // LASTBUDG07
return "LASTBUDG07";
case 64: // LASTBUDG08
return "LASTBUDG08";
case 65: // LASTBUDG09
return "LASTBUDG09";
case 66: // LASTBUDG10
return "LASTBUDG10";
case 67: // LASTBUDG11
return "LASTBUDG11";
case 68: // LASTBUDG12
return "LASTBUDG12";
case 69: // LAST_ANN_BUDG
return "LAST_ANN_BUDG";
case 70: // IMPORTED
return "IMPORTED";
case 71: // LW_DATE
return "LW_DATE";
case 72: // LW_TIME
return "LW_TIME";
case 73: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "BUDGETKEY":
return 0;
case "SUBPROGRAM":
return 1;
case "TITLE":
return 2;
case "CODE":
return 3;
case "GL_PROGRAM":
return 4;
case "INITIATIVE":
return 5;
case "CURR01":
return 6;
case "CURR02":
return 7;
case "CURR03":
return 8;
case "CURR04":
return 9;
case "CURR05":
return 10;
case "CURR06":
return 11;
case "CURR07":
return 12;
case "CURR08":
return 13;
case "CURR09":
return 14;
case "CURR10":
return 15;
case "CURR11":
return 16;
case "CURR12":
return 17;
case "OPBAL":
return 18;
case "LASTYR01":
return 19;
case "LASTYR02":
return 20;
case "LASTYR03":
return 21;
case "LASTYR04":
return 22;
case "LASTYR05":
return 23;
case "LASTYR06":
return 24;
case "LASTYR07":
return 25;
case "LASTYR08":
return 26;
case "LASTYR09":
return 27;
case "LASTYR10":
return 28;
case "LASTYR11":
return 29;
case "LASTYR12":
return 30;
case "BUDG01":
return 31;
case "BUDG02":
return 32;
case "BUDG03":
return 33;
case "BUDG04":
return 34;
case "BUDG05":
return 35;
case "BUDG06":
return 36;
case "BUDG07":
return 37;
case "BUDG08":
return 38;
case "BUDG09":
return 39;
case "BUDG10":
return 40;
case "BUDG11":
return 41;
case "BUDG12":
return 42;
case "NEXTBUDG01":
return 43;
case "NEXTBUDG02":
return 44;
case "NEXTBUDG03":
return 45;
case "NEXTBUDG04":
return 46;
case "NEXTBUDG05":
return 47;
case "NEXTBUDG06":
return 48;
case "NEXTBUDG07":
return 49;
case "NEXTBUDG08":
return 50;
case "NEXTBUDG09":
return 51;
case "NEXTBUDG10":
return 52;
case "NEXTBUDG11":
return 53;
case "NEXTBUDG12":
return 54;
case "ANNUALBUDG":
return 55;
case "NEXT_ANN_BUDG":
return 56;
case "LASTBUDG01":
return 57;
case "LASTBUDG02":
return 58;
case "LASTBUDG03":
return 59;
case "LASTBUDG04":
return 60;
case "LASTBUDG05":
return 61;
case "LASTBUDG06":
return 62;
case "LASTBUDG07":
return 63;
case "LASTBUDG08":
return 64;
case "LASTBUDG09":
return 65;
case "LASTBUDG10":
return 66;
case "LASTBUDG11":
return 67;
case "LASTBUDG12":
return 68;
case "LAST_ANN_BUDG":
return 69;
case "IMPORTED":
return 70;
case "LW_DATE":
return 71;
case "LW_TIME":
return 72;
case "LW_USER":
return 73;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Formula.PTG
{
using System;
using System.Text;
using NPOI.Util;
using NPOI.SS.Util;
using NPOI.SS.Formula.Constant;
/**
* ArrayPtg - handles arrays
*
* The ArrayPtg is a little weird, the size of the Ptg when parsing initially only
* includes the Ptg sid and the reserved bytes. The next Ptg in the expression then follows.
* It is only after the "size" of all the Ptgs is met, that the ArrayPtg data is actually
* held after this. So Ptg.CreateParsedExpression keeps track of the number of
* ArrayPtg elements and need to Parse the data upto the FORMULA record size.
*
* @author Jason Height (jheight at chariot dot net dot au)
*/
public class ArrayPtg : Ptg
{
public const byte sid = 0x20;
private const int RESERVED_FIELD_LEN = 7;
/**
* The size of the plain tArray token written within the standard formula tokens
* (not including the data which comes after all formula tokens)
*/
public const int PLAIN_TOKEN_SIZE = 1 + RESERVED_FIELD_LEN;
//private static byte[] DEFAULT_RESERVED_DATA = new byte[RESERVED_FIELD_LEN];
// 7 bytes of data (stored as an int, short and byte here)
private int _reserved0Int;
private int _reserved1Short;
private int _reserved2Byte;
// data from these fields comes after the Ptg data of all tokens in current formula
private int _nColumns;
private int _nRows;
private Object[] _arrayValues;
ArrayPtg(int reserved0, int reserved1, int reserved2, int nColumns, int nRows, Object[] arrayValues)
{
_reserved0Int = reserved0;
_reserved1Short = reserved1;
_reserved2Byte = reserved2;
_nColumns = nColumns;
_nRows = nRows;
_arrayValues = arrayValues;
}
/**
* @param values2d array values arranged in rows
*/
public ArrayPtg(Object[][] values2d)
{
int nColumns = values2d[0].Length;
int nRows = values2d.Length;
// convert 2-d to 1-d array (row by row according to getValueIndex())
_nColumns = (short)nColumns;
_nRows = (short)nRows;
Object[] vv = new Object[_nColumns * _nRows];
for (int r = 0; r < nRows; r++)
{
Object[] rowData = values2d[r];
for (int c = 0; c < nColumns; c++)
{
vv[GetValueIndex(c, r)] = rowData[c];
}
}
_arrayValues = vv;
_reserved0Int = 0;
_reserved1Short = 0;
_reserved2Byte = 0;
}
public Object[][] GetTokenArrayValues()
{
if (_arrayValues == null)
{
throw new InvalidOperationException("array values not read yet");
}
Object[][] result = new Object[_nRows][];
for (int r = 0; r < _nRows; r++)
{
result[r] = new object[_nColumns];
for (int c = 0; c < _nColumns; c++)
{
result[r][c] = _arrayValues[GetValueIndex(c, r)];
}
}
return result;
}
public override bool IsBaseToken
{
get { return false; }
}
public override String ToString()
{
StringBuilder buffer = new StringBuilder("[ArrayPtg]\n");
buffer.Append("columns = ").Append(ColumnCount).Append("\n");
buffer.Append("rows = ").Append(RowCount).Append("\n");
for (int x = 0; x < ColumnCount; x++)
{
for (int y = 0; y < RowCount; y++)
{
Object o = _arrayValues.GetValue(GetValueIndex(x, y));
buffer.Append("[").Append(x).Append("][").Append(y).Append("] = ").Append(o).Append("\n");
}
}
return buffer.ToString();
}
/**
* Note - (2D) array elements are stored column by column
* @return the index into the internal 1D array for the specified column and row
*/
/* package */
public int GetValueIndex(int colIx, int rowIx)
{
if (colIx < 0 || colIx >= _nColumns)
{
throw new ArgumentException("Specified colIx (" + colIx
+ ") is outside the allowed range (0.." + (_nColumns - 1) + ")");
}
if (rowIx < 0 || rowIx >= _nRows)
{
throw new ArgumentException("Specified rowIx (" + rowIx
+ ") is outside the allowed range (0.." + (_nRows - 1) + ")");
}
return rowIx * _nColumns + colIx;
}
public override void Write(ILittleEndianOutput out1)
{
out1.WriteByte(sid + PtgClass);
out1.WriteInt(_reserved0Int);
out1.WriteShort(_reserved1Short);
out1.WriteByte(_reserved2Byte);
}
public int WriteTokenValueBytes(ILittleEndianOutput out1)
{
out1.WriteByte(_nColumns - 1);
out1.WriteShort(_nRows - 1);
ConstantValueParser.Encode(out1, _arrayValues);
return 3 + ConstantValueParser.GetEncodedSize(_arrayValues);
}
public int RowCount
{
get
{
return _nRows;
}
}
public int ColumnCount
{
get
{
return _nColumns;
}
}
/** This size includes the size of the array Ptg plus the Array Ptg Token value size*/
public override int Size
{
get
{
int size = 1 + 7 + 1 + 2;
size += ConstantValueParser.GetEncodedSize(_arrayValues);
return size;
}
}
public override String ToFormulaString()
{
StringBuilder b = new StringBuilder();
b.Append("{");
for (int y = 0; y < RowCount; y++)
{
if (y > 0)
{
b.Append(";");
}
for (int x = 0; x < ColumnCount; x++)
{
if (x > 0)
{
b.Append(",");
}
Object o = _arrayValues.GetValue(GetValueIndex(x, y));
b.Append(GetConstantText(o));
}
}
b.Append("}");
return b.ToString();
}
private static String GetConstantText(Object o)
{
if (o == null)
{
return ""; // TODO - how is 'empty value' represented in formulas?
}
if (o is String)
{
return "\"" + (String)o + "\"";
}
if (o is Double || o is double)
{
return NumberToTextConverter.ToText((Double)o);
}
if (o is bool || o is Boolean)
{
return ((bool)o).ToString().ToUpper();
}
if (o is ErrorConstant)
{
return ((ErrorConstant)o).Text;
}
throw new ArgumentException("Unexpected constant class (" + o.GetType().Name + ")");
}
public override byte DefaultOperandClass
{
get { return Ptg.CLASS_ARRAY; }
}
/**
* Represents the initial plain tArray token (without the constant data that trails the whole
* formula). Objects of this class are only temporary and cannot be used as {@link Ptg}s.
* These temporary objects get converted to {@link ArrayPtg} by the
* {@link #finishReading(LittleEndianInput)} method.
*/
public class Initial : Ptg
{
private int _reserved0;
private int _reserved1;
private int _reserved2;
public Initial(ILittleEndianInput in1)
{
_reserved0 = in1.ReadInt();
_reserved1 = in1.ReadUShort();
_reserved2 = in1.ReadUByte();
}
private static Exception Invalid()
{
throw new InvalidOperationException("This object is a partially initialised tArray, and cannot be used as a Ptg");
}
public override byte DefaultOperandClass
{
get
{
throw Invalid();
}
}
public override int Size
{
get
{
return PLAIN_TOKEN_SIZE;
}
}
public override bool IsBaseToken
{
get
{
return false;
}
}
public override String ToFormulaString()
{
throw Invalid();
}
public override void Write(ILittleEndianOutput out1)
{
throw Invalid();
}
/**
* Read in the actual token (array) values. This occurs
* AFTER the last Ptg in the expression.
* See page 304-305 of Excel97-2007BinaryFileFormat(xls)Specification.pdf
*/
public ArrayPtg FinishReading(ILittleEndianInput in1)
{
int nColumns = in1.ReadUByte();
short nRows = in1.ReadShort();
//The token_1_columns and token_2_rows do not follow the documentation.
//The number of physical rows and columns is actually +1 of these values.
//Which is not explicitly documented.
nColumns++;
nRows++;
int totalCount = nRows * nColumns;
Object[] arrayValues = ConstantValueParser.Parse(in1, totalCount);
ArrayPtg result = new ArrayPtg(_reserved0, _reserved1, _reserved2, nColumns, nRows, arrayValues);
result.PtgClass = this.PtgClass;
return result;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.IO;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Html;
using Microsoft.Extensions.Internal;
namespace Microsoft.AspNetCore.Razor.TagHelpers
{
/// <summary>
/// An HTML tag helper attribute.
/// </summary>
public class TagHelperAttribute : IHtmlContentContainer
{
/// <summary>
/// Instantiates a new instance of <see cref="TagHelperAttribute"/> with the specified <paramref name="name"/>.
/// <see cref="ValueStyle"/> is set to <see cref="HtmlAttributeValueStyle.Minimized"/> and <see cref="Value"/> to
/// <c>null</c>.
/// </summary>
/// <param name="name">The <see cref="Name"/> of the attribute.</param>
public TagHelperAttribute(string name)
: this(name, value: null, valueStyle: HtmlAttributeValueStyle.Minimized)
{
}
/// <summary>
/// Instantiates a new instance of <see cref="TagHelperAttribute"/> with the specified <paramref name="name"/>
/// and <paramref name="value"/>. <see cref="ValueStyle"/> is set to <see cref="HtmlAttributeValueStyle.DoubleQuotes"/>.
/// </summary>
/// <param name="name">The <see cref="Name"/> of the attribute.</param>
/// <param name="value">The <see cref="Value"/> of the attribute.</param>
public TagHelperAttribute(string name, object value)
: this(name, value, valueStyle: HtmlAttributeValueStyle.DoubleQuotes)
{
}
/// <summary>
/// Instantiates a new instance of <see cref="TagHelperAttribute"/> with the specified <paramref name="name"/>,
/// <paramref name="value"/> and <paramref name="valueStyle"/>.
/// </summary>
/// <param name="name">The <see cref="Name"/> of the new instance.</param>
/// <param name="value">The <see cref="Value"/> of the new instance.</param>
/// <param name="valueStyle">The <see cref="ValueStyle"/> of the new instance.</param>
/// <remarks>If <paramref name="valueStyle"/> is <see cref="HtmlAttributeValueStyle.Minimized"/>,
/// <paramref name="value"/> is ignored when this instance is rendered.</remarks>
public TagHelperAttribute(string name, object value, HtmlAttributeValueStyle valueStyle)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
Name = name;
Value = value;
ValueStyle = valueStyle;
}
/// <summary>
/// Gets the name of the attribute.
/// </summary>
public string Name { get; }
/// <summary>
/// Gets the value of the attribute.
/// </summary>
public object Value { get; }
/// <summary>
/// Gets the value style of the attribute.
/// </summary>
public HtmlAttributeValueStyle ValueStyle { get; }
/// <inheritdoc />
/// <remarks><see cref="Name"/> is compared case-insensitively.</remarks>
public bool Equals(TagHelperAttribute other)
{
return
other != null &&
string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase) &&
ValueStyle == other.ValueStyle &&
(ValueStyle == HtmlAttributeValueStyle.Minimized || Equals(Value, other.Value));
}
/// <inheritdoc />
public void WriteTo(TextWriter writer, HtmlEncoder encoder)
{
if (writer == null)
{
throw new ArgumentNullException(nameof(writer));
}
if (encoder == null)
{
throw new ArgumentNullException(nameof(encoder));
}
writer.Write(Name);
if (ValueStyle == HtmlAttributeValueStyle.Minimized)
{
return;
}
var valuePrefix = GetAttributeValuePrefix(ValueStyle);
if (valuePrefix != null)
{
writer.Write(valuePrefix);
}
var htmlContent = Value as IHtmlContent;
if (htmlContent != null)
{
htmlContent.WriteTo(writer, encoder);
}
else if (Value != null)
{
encoder.Encode(writer, Value.ToString());
}
var valueSuffix = GetAttributeValueSuffix(ValueStyle);
if (valueSuffix != null)
{
writer.Write(valueSuffix);
}
}
/// <inheritdoc />
public void CopyTo(IHtmlContentBuilder destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
destination.AppendHtml(Name);
if (ValueStyle == HtmlAttributeValueStyle.Minimized)
{
return;
}
var valuePrefix = GetAttributeValuePrefix(ValueStyle);
if (valuePrefix != null)
{
destination.AppendHtml(valuePrefix);
}
string valueAsString;
IHtmlContentContainer valueAsHtmlContainer;
IHtmlContent valueAsHtmlContent;
if ((valueAsString = Value as string) != null)
{
destination.Append(valueAsString);
}
else if ((valueAsHtmlContainer = Value as IHtmlContentContainer) != null)
{
valueAsHtmlContainer.CopyTo(destination);
}
else if ((valueAsHtmlContent = Value as IHtmlContent) != null)
{
destination.AppendHtml(valueAsHtmlContent);
}
else if (Value != null)
{
destination.Append(Value.ToString());
}
var valueSuffix = GetAttributeValueSuffix(ValueStyle);
if (valueSuffix != null)
{
destination.AppendHtml(valueSuffix);
}
}
/// <inheritdoc />
public void MoveTo(IHtmlContentBuilder destination)
{
if (destination == null)
{
throw new ArgumentNullException(nameof(destination));
}
destination.AppendHtml(Name);
if (ValueStyle == HtmlAttributeValueStyle.Minimized)
{
return;
}
var valuePrefix = GetAttributeValuePrefix(ValueStyle);
if (valuePrefix != null)
{
destination.AppendHtml(valuePrefix);
}
string valueAsString;
IHtmlContentContainer valueAsHtmlContainer;
IHtmlContent valueAsHtmlContent;
if ((valueAsString = Value as string) != null)
{
destination.Append(valueAsString);
}
else if ((valueAsHtmlContainer = Value as IHtmlContentContainer) != null)
{
valueAsHtmlContainer.MoveTo(destination);
}
else if ((valueAsHtmlContent = Value as IHtmlContent) != null)
{
destination.AppendHtml(valueAsHtmlContent);
}
else if (Value != null)
{
destination.Append(Value.ToString());
}
var valueSuffix = GetAttributeValueSuffix(ValueStyle);
if (valueSuffix != null)
{
destination.AppendHtml(valueSuffix);
}
}
/// <inheritdoc />
public override bool Equals(object obj)
{
var other = obj as TagHelperAttribute;
return Equals(other);
}
/// <inheritdoc />
public override int GetHashCode()
{
var hashCode = new HashCode();
hashCode.Add(Name, StringComparer.Ordinal);
if (ValueStyle != HtmlAttributeValueStyle.Minimized)
{
hashCode.Add(Value);
}
hashCode.Add(ValueStyle);
return hashCode.ToHashCode();
}
private static string GetAttributeValuePrefix(HtmlAttributeValueStyle valueStyle)
{
switch (valueStyle)
{
case HtmlAttributeValueStyle.DoubleQuotes:
return "=\"";
case HtmlAttributeValueStyle.SingleQuotes:
return "='";
case HtmlAttributeValueStyle.NoQuotes:
return "=";
}
return null;
}
private static string GetAttributeValueSuffix(HtmlAttributeValueStyle valueStyle)
{
switch (valueStyle)
{
case HtmlAttributeValueStyle.DoubleQuotes:
return "\"";
case HtmlAttributeValueStyle.SingleQuotes:
return "'";
}
return null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.ComponentModel;
using System.Diagnostics;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.Net.NetworkInformation
{
public partial class Ping
{
private static readonly object s_socketInitializationLock = new object();
private static bool s_socketInitialized;
private int _sendSize = 0; // Needed to determine what the reply size is for ipv6 in callback.
private bool _ipv6 = false;
private ManualResetEvent _pingEvent;
private RegisteredWaitHandle _registeredWait;
private SafeLocalAllocHandle _requestBuffer;
private SafeLocalAllocHandle _replyBuffer;
private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV4;
private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV6;
private TaskCompletionSource<PingReply> _taskCompletionSource;
// Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException.
// We do not need to or want to capture such exceptions into the returned task.
private Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options)
{
var tcs = new TaskCompletionSource<PingReply>();
_taskCompletionSource = tcs;
_ipv6 = (address.AddressFamily == AddressFamily.InterNetworkV6);
_sendSize = buffer.Length;
// Get and cache correct handle.
if (!_ipv6 && _handlePingV4 == null)
{
_handlePingV4 = Interop.IpHlpApi.IcmpCreateFile();
if (_handlePingV4.IsInvalid)
{
_handlePingV4 = null;
throw new Win32Exception(); // Gets last error.
}
}
else if (_ipv6 && _handlePingV6 == null)
{
_handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile();
if (_handlePingV6.IsInvalid)
{
_handlePingV6 = null;
throw new Win32Exception(); // Gets last error.
}
}
var ipOptions = new Interop.IpHlpApi.IPOptions(options);
if (_replyBuffer == null)
{
_replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket);
}
// Queue the event.
int error;
try
{
if (_pingEvent == null)
{
_pingEvent = new ManualResetEvent(false);
}
else
{
_pingEvent.Reset();
}
_registeredWait = ThreadPool.RegisterWaitForSingleObject(_pingEvent, (state, _) => ((Ping)state).PingCallback(), this, -1, true);
SetUnmanagedStructures(buffer);
if (!_ipv6)
{
SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
error = (int)Interop.IpHlpApi.IcmpSendEcho2(
_handlePingV4,
pingEventSafeWaitHandle,
IntPtr.Zero,
IntPtr.Zero,
(uint)address.GetAddress(),
_requestBuffer,
(ushort)buffer.Length,
ref ipOptions,
_replyBuffer,
MaxUdpPacket,
(uint)timeout);
}
else
{
IPEndPoint ep = new IPEndPoint(address, 0);
Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep);
byte[] sourceAddr = new byte[28];
SafeWaitHandle pingEventSafeWaitHandle = _pingEvent.GetSafeWaitHandle();
error = (int)Interop.IpHlpApi.Icmp6SendEcho2(
_handlePingV6,
pingEventSafeWaitHandle,
IntPtr.Zero,
IntPtr.Zero,
sourceAddr,
remoteAddr.Buffer,
_requestBuffer,
(ushort)buffer.Length,
ref ipOptions,
_replyBuffer,
MaxUdpPacket,
(uint)timeout);
}
}
catch
{
UnregisterWaitHandle();
throw;
}
if (error == 0)
{
error = Marshal.GetLastWin32Error();
// Only skip Async IO Pending error value.
if (error != Interop.IpHlpApi.ERROR_IO_PENDING)
{
// Cleanup.
FreeUnmanagedStructures();
UnregisterWaitHandle();
throw new Win32Exception(error);
}
}
return tcs.Task;
}
/*private*/ partial void InternalDisposeCore()
{
if (_handlePingV4 != null)
{
_handlePingV4.Dispose();
_handlePingV4 = null;
}
if (_handlePingV6 != null)
{
_handlePingV6.Dispose();
_handlePingV6 = null;
}
UnregisterWaitHandle();
if (_pingEvent != null)
{
_pingEvent.Dispose();
_pingEvent = null;
}
if (_replyBuffer != null)
{
_replyBuffer.Dispose();
_replyBuffer = null;
}
}
private void UnregisterWaitHandle()
{
lock (_lockObject)
{
if (_registeredWait != null)
{
// If Unregister returns false, it is sufficient to nullify registeredWait
// and let its own finalizer clean up later.
_registeredWait.Unregister(null);
_registeredWait = null;
}
}
}
// Private callback invoked when icmpsendecho APIs succeed.
private void PingCallback()
{
TaskCompletionSource<PingReply> tcs = _taskCompletionSource;
_taskCompletionSource = null;
PingReply reply = null;
Exception error = null;
bool canceled = false;
try
{
lock (_lockObject)
{
canceled = _canceled;
// Parse reply buffer.
SafeLocalAllocHandle buffer = _replyBuffer;
// Marshals and constructs new reply.
if (_ipv6)
{
Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure<Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle());
reply = CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize);
}
else
{
Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure<Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle());
reply = CreatePingReplyFromIcmpEchoReply(icmpReply);
}
}
}
catch (Exception e)
{
// In case of failure, create a failed event arg.
error = new PingException(SR.net_ping, e);
}
finally
{
FreeUnmanagedStructures();
UnregisterWaitHandle();
Finish();
}
// Once we've called Finish, complete the task
if (canceled)
{
tcs.SetCanceled();
}
else if (reply != null)
{
tcs.SetResult(reply);
}
else
{
Debug.Assert(error != null);
tcs.SetException(error);
}
}
// Copies _requestBuffer into unmanaged memory for async icmpsendecho APIs.
private unsafe void SetUnmanagedStructures(byte[] buffer)
{
_requestBuffer = SafeLocalAllocHandle.LocalAlloc(buffer.Length);
byte* dst = (byte*)_requestBuffer.DangerousGetHandle();
for (int i = 0; i < buffer.Length; ++i)
{
dst[i] = buffer[i];
}
}
// Releases the unmanaged memory after ping completion.
private void FreeUnmanagedStructures()
{
if (_requestBuffer != null)
{
_requestBuffer.Dispose();
_requestBuffer = null;
}
}
private static PingReply CreatePingReplyFromIcmpEchoReply(Interop.IpHlpApi.IcmpEchoReply reply)
{
const int DontFragmentFlag = 2;
IPAddress address = new IPAddress(reply.address);
IPStatus ipStatus = (IPStatus)reply.status; // The icmpsendecho IP status codes.
long rtt;
PingOptions options;
byte[] buffer;
if (ipStatus == IPStatus.Success)
{
// Only copy the data if we succeed w/ the ping operation.
rtt = reply.roundTripTime;
options = new PingOptions(reply.options.ttl, (reply.options.flags & DontFragmentFlag) > 0);
buffer = new byte[reply.dataSize];
Marshal.Copy(reply.data, buffer, 0, reply.dataSize);
}
else
{
rtt = default(long);
options = default(PingOptions);
buffer = Array.Empty<byte>();
}
return new PingReply(address, options, ipStatus, rtt, buffer);
}
private static PingReply CreatePingReplyFromIcmp6EchoReply(Interop.IpHlpApi.Icmp6EchoReply reply, IntPtr dataPtr, int sendSize)
{
IPAddress address = new IPAddress(reply.Address.Address, reply.Address.ScopeID);
IPStatus ipStatus = (IPStatus)reply.Status; // The icmpsendecho IP status codes.
long rtt;
byte[] buffer;
if (ipStatus == IPStatus.Success)
{
// Only copy the data if we succeed w/ the ping operation.
rtt = reply.RoundTripTime;
buffer = new byte[sendSize];
Marshal.Copy(IntPtrHelper.Add(dataPtr, 36), buffer, 0, sendSize);
}
else
{
rtt = default(long);
buffer = Array.Empty<byte>();
}
return new PingReply(address, default(PingOptions), ipStatus, rtt, buffer);
}
/*private*/ static partial void InitializeSockets()
{
if (!Volatile.Read(ref s_socketInitialized))
{
lock (s_socketInitializationLock)
{
if (!s_socketInitialized)
{
// Ensure that WSAStartup has been called once per process.
// The System.Net.NameResolution contract is responsible with the initialization.
Dns.GetHostName();
// Cache some settings locally.
s_socketInitialized = true;
}
}
}
}
}
}
| |
/*
* Author: Tristan Chambers
* Date: Thursday, November 7, 2013
* Email: Tristan.Chambershotmail.com
* Website: Tristan.PaperHatStudios.com
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
namespace SMPL.Props
{
/// <summary>
/// Property list.
/// </summary>
public class PropertyList : PropertyEntry
{
#region Properties
/// <summary>
/// Gets a read-only list of keys.
/// </summary>
public ReadOnlyCollection<string> Keys
{
get
{
return _keys.AsReadOnly();
}
}
/// <summary>
/// Gets the entries.
/// </summary>
/// <value>The entries.</value>
public ReadOnlyCollection<PropertyEntry> Entries
{
get
{
return _entries.AsReadOnly();
}
}
/// <summary>
/// The comment on the group close bracket.
/// </summary>
/// <value></value>
public string CloseComment { get; set; }
/// <summary>
/// Determines the amount of entries in the list.
/// </summary>
public int Count
{
get { return _entries.Count; }
}
#endregion // Properties
#region Private Variables
private List<string> _keys;
private List<PropertyEntry> _entries;
private int _lastLoadedIndex;
#endregion // Private Variables
/// <summary>
/// Initializes a new instance of the <see cref="SimplifiedProperties.PropertyList"/> class.
/// </summary>
/// <param name="file">File.</param>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
public PropertyList(string key)
: this(key, string.Empty)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="SimplifiedProperties.PropertyList"/> class.
/// </summary>
/// <param name="file">File.</param>
/// <param name="key">Key.</param>
/// <param name="value">Value.</param>
/// <param name="comment">Comment.</param>
public PropertyList(string key, string comment)
: base(key, string.Empty, comment)
{
_keys = new List<string>();
_entries = new List<PropertyEntry>();
}
/// <summary>
/// Adds a new property entry to the list.
/// Note that this does not mark the property to save.
/// </summary>
/// <param name="file">The property file that is the parent to the property.</param>
/// <param name="key">Key.</param>
/// <param name="defaultValue">Value.</param>
/// <param name="comment">Comment.</param>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public void NewEntry<T>(string key, T defaultValue, string comment)
{
AddEntry(new PropertyEntry(key,
defaultValue == null
? null
: defaultValue.ToString(), comment));
}
/// <summary>
/// Adds a new array entry to the list.
/// </summary>
/// <param name="value">The value.</param>
public void AddArrayEntry<T>(T value)
{
AddArrayEntry(value, null);
}
/// <summary>
/// Adds a new array entry to the list.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="comment">The comment.</param>
public void AddArrayEntry<T>(T value, string comment)
{
AddEntry(new ArrayEntry(value + "", comment));
}
/// <summary>
/// Adds a new line entry.
/// </summary>
public void NewLine()
{
AddEntry(new NewLineEntry(){ Loaded = true });
}
/// <summary>
/// Adds the entry.
/// </summary>
/// <returns>The entry.</returns>
/// <param name="entry">Entry.</param>
public PropertyEntry AddEntry(PropertyEntry entry)
{
if (entry == null)
throw new PropertyException("A null entry was added to a property list.", this);
var alias = entry is CommentEntry || entry is NewLineEntry || entry is BlockCommentEntry ?
entry.Key : Tools.GetAlias(entry.Key, Keys);
if (_lastLoadedIndex + 1 >= _keys.Count)
_keys.Add(alias);
else
_keys.Insert(_lastLoadedIndex + 1, alias);
entry.Key = alias;
if (_lastLoadedIndex + 1 >= _entries.Count)
_entries.Add(entry);
else
_entries.Insert(_lastLoadedIndex + 1, entry);
entry.Parent = this;
_lastLoadedIndex = _keys.Count - 1;
return entry;
}
/// <summary>
/// Contains the specified key.
/// </summary>
/// <param name="key">Key.</param>
public bool Contains(string key)
{
return _keys.Contains(key);
}
/// <summary>
/// Finds the index of an entry.
/// </summary>
/// <param name="entry">The entry.</param>
public int IndexOf(PropertyEntry entry)
{
return _entries.IndexOf(entry);
}
/// <summary>
/// Gets an entry using the key.
/// </summary>
/// <returns>Shit.</returns>
/// <param name="key">The key used to get the entry.</param>
public PropertyEntry GetEntry(string key)
{
PropertyEntry entry = null;
for (int i = 0; i < _keys.Count; i++)
{
var eachEntry = _entries[i];
if (_keys[i].Equals(key)
&& (eachEntry.GetType() == typeof(PropertyEntry)
|| eachEntry.GetType() == typeof(ConcatenatedEntry)))
{
entry = eachEntry;
break;
}
}
return entry;
}
/// <summary>
/// Sets the entry at an index.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="entry">Entry.</param>
public bool SetEntryAt(int index, PropertyEntry entry)
{
if (index < 0 || index > _entries.Count)
return false;
_keys[index] = entry.Key;
_entries[index] = entry;
Modified = true;
return true;
}
/// <summary>
/// Removes an entry from the list using it's key.
/// </summary>
/// <returns>The entry.</returns>
/// <param name="key">Key.</param>
public PropertyEntry RemoveEntry(string key)
{
return RemoveEntry(GetEntry(key));
}
/// <summary>
/// Removes an entry from the list.
/// </summary>
/// <returns>The entry.</returns>
/// <param name="entry">Entry.</param>
public PropertyEntry RemoveEntry(PropertyEntry entry)
{
if (entry == null)
return null;
int index = IndexOf(entry);
_keys.RemoveAt(index);
_entries.RemoveAt(index);
return entry;
}
/// <summary>
/// Gets the value of an entry or creates the entry if it does not exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
public PropertyEntry GetOrCreateEntry(string key, object defaultValue)
{
return GetOrCreateEntry(key, defaultValue, string.Empty);
}
/// <summary>
/// Gets the value of an entry or creates the entry if it does not exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="comment">The comment for the entry.</param>
public PropertyEntry GetOrCreateEntry(string key, object defaultValue, string comment)
{
PropertyEntry entry;
if (Contains(key))
{
entry = GetEntry(key);
}
else
{
entry = AddEntry(new PropertyEntry(key, defaultValue.ToString(), comment));
}
return entry;
}
/// <summary>
/// Sets the value of an entry or creates the entry if it does not exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="newValue">The new value.</param>
/// <param name="comment">The comment for the entry.</param>
public PropertyEntry SetOrCreateEntry(string key, object newValue)
{
return SetOrCreateEntry(key, newValue, string.Empty);
}
/// <summary>
/// Sets the value of an entry or creates the entry if it does not exist.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="newValue">The new value.</param>
/// <param name="comment">The comment for the entry.</param>
public PropertyEntry SetOrCreateEntry(string key, object newValue, string comment)
{
PropertyEntry entry;
if (Contains(key))
{
entry = GetEntry(key);
entry.StringValue = newValue + "";
}
else
{
entry = AddEntry(new PropertyEntry(key, newValue + "", comment));
}
return entry;
}
/// <summary>
/// Gets the value of an entry or creates the entry if it does not exist.
/// This will mark the entry as loaded. See PropertyFile.CommentUnloadedEntries.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
public T LoadEntry<T>(string key, T defaultValue)
{
return LoadEntry<T>(key, defaultValue, string.Empty);
}
/// <summary>
/// Gets the value of an entry or creates the entry if it does not exist.
/// This will mark the entry as loaded. See PropertyFile.CommentUnloadedEntries.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="defaultValue">The default value.</param>
/// <param name="comment">The comment for the entry.</param>
public T LoadEntry<T>(string key, T defaultValue, string comment)
{
var entry = GetOrCreateEntry(key, defaultValue, comment);
entry.Loaded = true;
return entry.GetValue<T>();
}
/// <summary>
/// Gets all array entries that can be parsed to the specified type.
/// </summary>
public List<ArrayEntry> GetArrayEntries<T>()
{
var arrayEntries = new List<ArrayEntry>();
for (int i = 0; i < _entries.Count; i++)
{
var entry = _entries[i] as ArrayEntry;
if (entry == null)
continue;
T val;
if (!TryGetValue<T>(out val))
continue;
arrayEntries.Add(entry);
}
return arrayEntries;
}
/// <summary>
/// Loads an array of values from the list. This will only load values
/// that can be parsed to the specified type.
/// </summary>
public T[] LoadArray<T>()
{
T[] values = new T[_entries.Count];
int addIndex = 0;
for (int i = 0; i < _entries.Count; i++)
{
var entry = _entries[i] as ArrayEntry;
if (entry == null)
continue;
T val;
if (!entry.TryGetValue(out val))
continue;
values[addIndex] = val;
entry.Loaded = true;
addIndex++;
}
if (addIndex < _entries.Count)
{
Array.Resize(ref values, addIndex);
}
return values;
}
/// <summary>
/// Gets an array entry by index and by type.
/// </summary>
/// <returns>The array entry.</returns>
/// <param name="index">Index.</param>
/// <typeparam name="T">The vaue type of the entry.</typeparam>
public ArrayEntry GetArrayEntry<T>(int index)
{
int currentIndex = 0;
for (int i = 0; i < _entries.Count; i++)
{
var entry = _entries[i];
if (entry is ArrayEntry)
{
try
{
if (currentIndex == index)
{
entry.GetValue<T>();
return entry as ArrayEntry;
}
currentIndex++;
}
catch
{
}
}
}
return null;
}
/// <summary>
/// Gets the list.
/// </summary>
/// <param name="key">Key.</param>
public PropertyList GetList(string key)
{
PropertyList list = null;
for (int i = 0; i < _keys.Count; i++)
{
var eachEntry = _entries[i];
if (_keys[i].Equals(key) && eachEntry.GetType() == typeof(PropertyList))
{
list = eachEntry as PropertyList;
}
}
return list;
}
/// <summary>
/// Gets/Creates a list.
/// </summary>
/// <param name="key">Key.</param>
public PropertyList GetOrCreateList(string key)
{
return GetOrCreateList(key, null);
}
/// <summary>
/// Gets/Creates a list.
/// </summary>
/// <param name="key">Key.</param>
/// <param name="comment">Comment.</param>
public PropertyList GetOrCreateList(string key, string comment)
{
PropertyList list = GetList(key);
if (list == null)
{
list = new PropertyList(key, comment);
AddEntry(list);
}
return list;
}
/// <summary>
/// Gets/Creates a list and marks it as loaded.
/// </summary>
/// <param name="key">Key.</param>
public PropertyList LoadList(string key)
{
return LoadList(key, null);
}
/// <summary>
/// Gets/Creates a list and marks it as loaded.
/// </summary>
/// <param name="key">Key.</param>
/// <param name="comment">Comment.</param>
public PropertyList LoadList(string key, string comment)
{
PropertyList list = GetOrCreateList(key, comment);
list.Loaded = true;
return list;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (Parent != null)
{
sb.AppendFormat("{0} {{", Key);
if (!Comment.IsNullEmptyOrWhite())
{
sb.AppendFormat(" # {0}", Comment);
}
sb.AppendLine();
}
for (int i = 0; i < _entries.Count; i++)
{
var entry = _entries[i];
sb.AppendLine(entry.ToString());
}
for (int i = 0; i < IndentLevel; i++)
{
sb.Append(" ");
}
if (Parent != null)
{
sb.Append("}");
if (!string.IsNullOrEmpty(CloseComment))
{
sb.AppendFormat(" # {0}", CloseComment);
}
}
string toString = sb.ToString();
for (int i = 0; i < IndentLevel; i++)
{
toString = " " + toString;
}
return toString;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.IO;
using System.Text;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Diagnostics;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Versioning;
using System.Threading.Tasks;
namespace System.Xml
{
internal partial class XsdValidatingReader : XmlReader, IXmlSchemaInfo, IXmlLineInfo, IXmlNamespaceResolver
{
// Gets the text value of the current node.
public override Task<string> GetValueAsync()
{
if ((int)_validationState < 0)
{
return Task.FromResult(_cachedNode.RawValue);
}
return _coreReader.GetValueAsync();
}
public override Task<object> ReadContentAsObjectAsync()
{
if (!CanReadContentAs(this.NodeType))
{
throw CreateReadContentAsException(nameof(ReadContentAsObject));
}
return InternalReadContentAsObjectAsync(true);
}
public override async Task<string> ReadContentAsStringAsync()
{
if (!CanReadContentAs(this.NodeType))
{
throw CreateReadContentAsException(nameof(ReadContentAsString));
}
object typedValue = await InternalReadContentAsObjectAsync().ConfigureAwait(false);
XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType;
try
{
if (xmlType != null)
{
return xmlType.ValueConverter.ToString(typedValue);
}
else
{
return typedValue as string;
}
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
}
public override async Task<object> ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
if (!CanReadContentAs(this.NodeType))
{
throw CreateReadContentAsException(nameof(ReadContentAs));
}
string originalStringValue;
var tuple_0 = await InternalReadContentAsObjectTupleAsync(false).ConfigureAwait(false);
originalStringValue = tuple_0.Item1;
object typedValue = tuple_0.Item2;
XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType;
try
{
if (xmlType != null)
{
// special-case convertions to DateTimeOffset; typedValue is by default a DateTime
// which cannot preserve time zone, so we need to convert from the original string
if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase)
{
typedValue = originalStringValue;
}
return xmlType.ValueConverter.ChangeType(typedValue, returnType);
}
else
{
return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver);
}
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
}
public override async Task<object> ReadElementContentAsObjectAsync()
{
if (this.NodeType != XmlNodeType.Element)
{
throw CreateReadElementContentAsException(nameof(ReadElementContentAsObject));
}
var tuple_1 = await InternalReadElementContentAsObjectAsync(true).ConfigureAwait(false);
return tuple_1.Item2;
}
public override async Task<string> ReadElementContentAsStringAsync()
{
if (this.NodeType != XmlNodeType.Element)
{
throw CreateReadElementContentAsException(nameof(ReadElementContentAsString));
}
XmlSchemaType xmlType;
var tuple_9 = await InternalReadElementContentAsObjectAsync().ConfigureAwait(false);
xmlType = tuple_9.Item1;
object typedValue = tuple_9.Item2;
try
{
if (xmlType != null)
{
return xmlType.ValueConverter.ToString(typedValue);
}
else
{
return typedValue as string;
}
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo);
}
}
public override async Task<object> ReadElementContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver)
{
if (this.NodeType != XmlNodeType.Element)
{
throw CreateReadElementContentAsException(nameof(ReadElementContentAs));
}
XmlSchemaType xmlType;
string originalStringValue;
var tuple_10 = await InternalReadElementContentAsObjectTupleAsync(false).ConfigureAwait(false);
xmlType = tuple_10.Item1;
originalStringValue = tuple_10.Item2;
object typedValue = tuple_10.Item3;
try
{
if (xmlType != null)
{
// special-case convertions to DateTimeOffset; typedValue is by default a DateTime
// which cannot preserve time zone, so we need to convert from the original string
if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase)
{
typedValue = originalStringValue;
}
return xmlType.ValueConverter.ChangeType(typedValue, returnType, namespaceResolver);
}
else
{
return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver);
}
}
catch (FormatException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (InvalidCastException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
catch (OverflowException e)
{
throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo);
}
}
private Task<bool> ReadAsync_Read(Task<bool> task)
{
if (task.IsSuccess())
{
if (task.Result)
{
return ProcessReaderEventAsync().ReturnTrueTaskWhenFinishAsync();
}
else
{
_validator.EndValidation();
if (_coreReader.EOF)
{
_validationState = ValidatingReaderState.EOF;
}
return AsyncHelper.DoneTaskFalse;
}
}
else
{
return _ReadAsync_Read(task);
}
}
private async Task<bool> _ReadAsync_Read(Task<bool> task)
{
if (await task.ConfigureAwait(false))
{
await ProcessReaderEventAsync().ConfigureAwait(false);
return true;
}
else
{
_validator.EndValidation();
if (_coreReader.EOF)
{
_validationState = ValidatingReaderState.EOF;
}
return false;
}
}
private Task<bool> ReadAsync_ReadAhead(Task task)
{
if (task.IsSuccess())
{
_validationState = ValidatingReaderState.Read;
return AsyncHelper.DoneTaskTrue; ;
}
else
{
return _ReadAsync_ReadAhead(task);
}
}
private async Task<bool> _ReadAsync_ReadAhead(Task task)
{
await task.ConfigureAwait(false);
_validationState = ValidatingReaderState.Read;
return true;
}
// Reads the next node from the stream/TextReader.
public override Task<bool> ReadAsync()
{
switch (_validationState)
{
case ValidatingReaderState.Read:
Task<bool> readTask = _coreReader.ReadAsync();
return ReadAsync_Read(readTask);
case ValidatingReaderState.ParseInlineSchema:
return ProcessInlineSchemaAsync().ReturnTrueTaskWhenFinishAsync();
case ValidatingReaderState.OnAttribute:
case ValidatingReaderState.OnDefaultAttribute:
case ValidatingReaderState.ClearAttributes:
case ValidatingReaderState.OnReadAttributeValue:
ClearAttributesInfo();
if (_inlineSchemaParser != null)
{
_validationState = ValidatingReaderState.ParseInlineSchema;
goto case ValidatingReaderState.ParseInlineSchema;
}
else
{
_validationState = ValidatingReaderState.Read;
goto case ValidatingReaderState.Read;
}
case ValidatingReaderState.ReadAhead: //Will enter here on calling Skip()
ClearAttributesInfo();
Task task = ProcessReaderEventAsync();
return ReadAsync_ReadAhead(task);
case ValidatingReaderState.OnReadBinaryContent:
_validationState = _savedState;
return _readBinaryHelper.FinishAsync().CallBoolTaskFuncWhenFinishAsync(thisRef => thisRef.ReadAsync(), this);
case ValidatingReaderState.Init:
_validationState = ValidatingReaderState.Read;
if (_coreReader.ReadState == ReadState.Interactive)
{ //If the underlying reader is already positioned on a ndoe, process it
return ProcessReaderEventAsync().ReturnTrueTaskWhenFinishAsync();
}
else
{
goto case ValidatingReaderState.Read;
}
case ValidatingReaderState.ReaderClosed:
case ValidatingReaderState.EOF:
return AsyncHelper.DoneTaskFalse;
default:
return AsyncHelper.DoneTaskFalse;
}
}
// Skips to the end tag of the current element.
public override async Task SkipAsync()
{
int startDepth = Depth;
switch (NodeType)
{
case XmlNodeType.Element:
if (_coreReader.IsEmptyElement)
{
break;
}
bool callSkipToEndElem = true;
//If union and unionValue has been parsed till EndElement, then validator.ValidateEndElement has been called
//Hence should not call SkipToEndElement as the current context has already been popped in the validator
if ((_xmlSchemaInfo.IsUnionType || _xmlSchemaInfo.IsDefault) && _coreReader is XsdCachingReader)
{
callSkipToEndElem = false;
}
await _coreReader.SkipAsync().ConfigureAwait(false);
_validationState = ValidatingReaderState.ReadAhead;
if (callSkipToEndElem)
{
_validator.SkipToEndElement(_xmlSchemaInfo);
}
break;
case XmlNodeType.Attribute:
MoveToElement();
goto case XmlNodeType.Element;
}
//For all other NodeTypes Skip() same as Read()
await ReadAsync().ConfigureAwait(false);
return;
}
public override async Task<int> ReadContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
public override async Task<int> ReadContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBase64Async(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBase64Async(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
public override async Task<int> ReadElementContentAsBinHexAsync(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadContentAsBinaryHelper when called first time
if (_validationState != ValidatingReaderState.OnReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this);
_savedState = _validationState;
}
// restore original state in order to have a normal Read() behavior when called from readBinaryHelper
_validationState = _savedState;
// call to the helper
int readCount = await _readBinaryHelper.ReadElementContentAsBinHexAsync(buffer, index, count).ConfigureAwait(false);
// set OnReadBinaryContent state again and return
_savedState = _validationState;
_validationState = ValidatingReaderState.OnReadBinaryContent;
return readCount;
}
private Task ProcessReaderEventAsync()
{
if (_replayCache)
{ //if in replay mode, do nothing since nodes have been validated already
//If NodeType == XmlNodeType.EndElement && if manageNamespaces, may need to pop namespace scope, since scope is not popped in ReadAheadForMemberType
return Task.CompletedTask;
}
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
return ProcessElementEventAsync();
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(GetStringValue);
break;
case XmlNodeType.Text: // text inside a node
case XmlNodeType.CDATA: // <![CDATA[...]]>
_validator.ValidateText(GetStringValue);
break;
case XmlNodeType.EndElement:
return ProcessEndElementEventAsync();
case XmlNodeType.EntityReference:
throw new InvalidOperationException();
case XmlNodeType.DocumentType:
#if TEMP_HACK_FOR_SCHEMA_INFO
validator.SetDtdSchemaInfo((SchemaInfo)coreReader.DtdInfo);
#else
_validator.SetDtdSchemaInfo(_coreReader.DtdInfo);
#endif
break;
default:
break;
}
return Task.CompletedTask;
}
private async Task ProcessElementEventAsync()
{
if (_processInlineSchema && IsXSDRoot(_coreReader.LocalName, _coreReader.NamespaceURI) && _coreReader.Depth > 0)
{
_xmlSchemaInfo.Clear();
_attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount;
if (!_coreReader.IsEmptyElement)
{ //If its not empty schema, then parse else ignore
_inlineSchemaParser = new Parser(SchemaType.XSD, _coreReaderNameTable, _validator.SchemaSet.GetSchemaNames(_coreReaderNameTable), _validationEvent);
await _inlineSchemaParser.StartParsingAsync(_coreReader, null).ConfigureAwait(false);
_inlineSchemaParser.ParseReaderNode();
_validationState = ValidatingReaderState.ParseInlineSchema;
}
else
{
_validationState = ValidatingReaderState.ClearAttributes;
}
}
else
{ //Validate element
//Clear previous data
_atomicValue = null;
_originalAtomicValueString = null;
_xmlSchemaInfo.Clear();
if (_manageNamespaces)
{
_nsManager.PushScope();
}
//Find Xsi attributes that need to be processed before validating the element
string xsiSchemaLocation = null;
string xsiNoNamespaceSL = null;
string xsiNil = null;
string xsiType = null;
if (_coreReader.MoveToFirstAttribute())
{
do
{
string objectNs = _coreReader.NamespaceURI;
string objectName = _coreReader.LocalName;
if (Ref.Equal(objectNs, _nsXsi))
{
if (Ref.Equal(objectName, _xsiSchemaLocation))
{
xsiSchemaLocation = _coreReader.Value;
}
else if (Ref.Equal(objectName, _xsiNoNamespaceSchemaLocation))
{
xsiNoNamespaceSL = _coreReader.Value;
}
else if (Ref.Equal(objectName, _xsiType))
{
xsiType = _coreReader.Value;
}
else if (Ref.Equal(objectName, _xsiNil))
{
xsiNil = _coreReader.Value;
}
}
if (_manageNamespaces && Ref.Equal(_coreReader.NamespaceURI, _nsXmlNs))
{
_nsManager.AddNamespace(_coreReader.Prefix.Length == 0 ? string.Empty : _coreReader.LocalName, _coreReader.Value);
}
} while (_coreReader.MoveToNextAttribute());
_coreReader.MoveToElement();
}
_validator.ValidateElement(_coreReader.LocalName, _coreReader.NamespaceURI, _xmlSchemaInfo, xsiType, xsiNil, xsiSchemaLocation, xsiNoNamespaceSL);
ValidateAttributes();
_validator.ValidateEndOfAttributes(_xmlSchemaInfo);
if (_coreReader.IsEmptyElement)
{
await ProcessEndElementEventAsync().ConfigureAwait(false);
}
_validationState = ValidatingReaderState.ClearAttributes;
}
}
private async Task ProcessEndElementEventAsync()
{
_atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo);
_originalAtomicValueString = GetOriginalAtomicValueStringOfElement();
if (_xmlSchemaInfo.IsDefault)
{ //The atomicValue returned is a default value
Debug.Assert(_atomicValue != null);
int depth = _coreReader.Depth;
_coreReader = GetCachingReader();
_cachingReader.RecordTextNode(_xmlSchemaInfo.XmlType.ValueConverter.ToString(_atomicValue), _originalAtomicValueString, depth + 1, 0, 0);
_cachingReader.RecordEndElementNode();
await _cachingReader.SetToReplayModeAsync().ConfigureAwait(false);
_replayCache = true;
}
else if (_manageNamespaces)
{
_nsManager.PopScope();
}
}
private async Task ProcessInlineSchemaAsync()
{
Debug.Assert(_inlineSchemaParser != null);
if (await _coreReader.ReadAsync().ConfigureAwait(false))
{
if (_coreReader.NodeType == XmlNodeType.Element)
{
_attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount;
}
else
{ //Clear attributes info if nodeType is not element
ClearAttributesInfo();
}
if (!_inlineSchemaParser.ParseReaderNode())
{
_inlineSchemaParser.FinishParsing();
XmlSchema schema = _inlineSchemaParser.XmlSchema;
_validator.AddSchema(schema);
_inlineSchemaParser = null;
_validationState = ValidatingReaderState.Read;
}
}
}
private Task<object> InternalReadContentAsObjectAsync()
{
return InternalReadContentAsObjectAsync(false);
}
private async Task<object> InternalReadContentAsObjectAsync(bool unwrapTypedValue)
{
var tuple_11 = await InternalReadContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false);
return tuple_11.Item2;
}
private async Task<Tuple<string, object>> InternalReadContentAsObjectTupleAsync(bool unwrapTypedValue)
{
Tuple<string, object> tuple;
string originalStringValue;
XmlNodeType nodeType = this.NodeType;
if (nodeType == XmlNodeType.Attribute)
{
originalStringValue = this.Value;
if (_attributePSVI != null && _attributePSVI.typedAttributeValue != null)
{
if (_validationState == ValidatingReaderState.OnDefaultAttribute)
{
XmlSchemaAttribute schemaAttr = _attributePSVI.attributeSchemaInfo.SchemaAttribute;
originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue;
}
tuple = new Tuple<string, object>(originalStringValue, ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType, unwrapTypedValue));
return tuple;
}
else
{ //return string value
tuple = new Tuple<string, object>(originalStringValue, this.Value);
return tuple;
}
}
else if (nodeType == XmlNodeType.EndElement)
{
if (_atomicValue != null)
{
originalStringValue = _originalAtomicValueString;
tuple = new Tuple<string, object>(originalStringValue, _atomicValue);
return tuple;
}
else
{
originalStringValue = string.Empty;
tuple = new Tuple<string, object>(originalStringValue, string.Empty);
return tuple;
}
}
else
{ //Positioned on text, CDATA, PI, Comment etc
if (_validator.CurrentContentType == XmlSchemaContentType.TextOnly)
{ //if current element is of simple type
object value = ReturnBoxedValue(await ReadTillEndElementAsync().ConfigureAwait(false), _xmlSchemaInfo.XmlType, unwrapTypedValue);
originalStringValue = _originalAtomicValueString;
tuple = new Tuple<string, object>(originalStringValue, value);
return tuple;
}
else
{
XsdCachingReader cachingReader = _coreReader as XsdCachingReader;
if (cachingReader != null)
{
originalStringValue = cachingReader.ReadOriginalContentAsString();
}
else
{
originalStringValue = await InternalReadContentAsStringAsync().ConfigureAwait(false);
}
tuple = new Tuple<string, object>(originalStringValue, originalStringValue);
return tuple;
}
}
}
private Task<Tuple<XmlSchemaType, object>> InternalReadElementContentAsObjectAsync()
{
return InternalReadElementContentAsObjectAsync(false);
}
private async Task<Tuple<XmlSchemaType, object>> InternalReadElementContentAsObjectAsync(bool unwrapTypedValue)
{
var tuple_13 = await InternalReadElementContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false);
return new Tuple<XmlSchemaType, object>(tuple_13.Item1, tuple_13.Item3);
}
private async Task<Tuple<XmlSchemaType, string, object>> InternalReadElementContentAsObjectTupleAsync(bool unwrapTypedValue)
{
Tuple<XmlSchemaType, string, object> tuple;
XmlSchemaType xmlType;
string originalString;
Debug.Assert(this.NodeType == XmlNodeType.Element);
object typedValue = null;
xmlType = null;
//If its an empty element, can have default/fixed value
if (this.IsEmptyElement)
{
if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly)
{
typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue);
}
else
{
typedValue = _atomicValue;
}
originalString = _originalAtomicValueString;
xmlType = ElementXmlType; //Set this for default values
await this.ReadAsync().ConfigureAwait(false);
tuple = new Tuple<XmlSchemaType, string, object>(xmlType, originalString, typedValue);
return tuple;
}
// move to content and read typed value
await this.ReadAsync().ConfigureAwait(false);
if (this.NodeType == XmlNodeType.EndElement)
{ //If IsDefault is true, the next node will be EndElement
if (_xmlSchemaInfo.IsDefault)
{
if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly)
{
typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue);
}
else
{ //anyType has default value
typedValue = _atomicValue;
}
originalString = _originalAtomicValueString;
}
else
{ //Empty content
typedValue = string.Empty;
originalString = string.Empty;
}
}
else if (this.NodeType == XmlNodeType.Element)
{ //the first child is again element node
throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo);
}
else
{
var tuple_14 = await InternalReadContentAsObjectTupleAsync(unwrapTypedValue).ConfigureAwait(false);
originalString = tuple_14.Item1;
typedValue = tuple_14.Item2;
// ReadElementContentAsXXX cannot be called on mixed content, if positioned on node other than EndElement, Error
if (this.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo);
}
}
xmlType = ElementXmlType; //Set this as we are moving ahead to the next node
// move to next node
await this.ReadAsync().ConfigureAwait(false);
tuple = new Tuple<XmlSchemaType, string, object>(xmlType, originalString, typedValue);
return tuple;
}
private async Task<object> ReadTillEndElementAsync()
{
if (_atomicValue == null)
{
while (await _coreReader.ReadAsync().ConfigureAwait(false))
{
if (_replayCache)
{ //If replaying nodes in the cache, they have already been validated
continue;
}
switch (_coreReader.NodeType)
{
case XmlNodeType.Element:
await ProcessReaderEventAsync().ConfigureAwait(false);
goto breakWhile;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
_validator.ValidateText(GetStringValue);
break;
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
_validator.ValidateWhitespace(GetStringValue);
break;
case XmlNodeType.Comment:
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.EndElement:
_atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo);
_originalAtomicValueString = GetOriginalAtomicValueStringOfElement();
if (_manageNamespaces)
{
_nsManager.PopScope();
}
goto breakWhile;
}
continue;
breakWhile:
break;
}
}
else
{ //atomicValue != null, meaning already read ahead - Switch reader
if (_atomicValue == this)
{ //switch back invalid marker; dont need it since coreReader moved to endElement
_atomicValue = null;
}
SwitchReader();
}
return _atomicValue;
}
}
}
| |
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 frmNewReportGroup : System.Windows.Forms.Form
{
private ADODB.Recordset withEventsField_adoPrimaryRS;
public ADODB.Recordset adoPrimaryRS {
get { return withEventsField_adoPrimaryRS; }
set {
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete -= adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord -= adoPrimaryRS_WillChangeRecord;
}
withEventsField_adoPrimaryRS = value;
if (withEventsField_adoPrimaryRS != null) {
withEventsField_adoPrimaryRS.MoveComplete += adoPrimaryRS_MoveComplete;
withEventsField_adoPrimaryRS.WillChangeRecord += adoPrimaryRS_WillChangeRecord;
}
}
}
bool mbChangedByCode;
int mvBookMark;
bool mbEditFlag;
bool mbAddNewFlag;
bool mbDataChanged;
string sgl;
int gID;
List<TextBox> txtFields = new List<TextBox>();
List<CheckBox> chkFields = new List<CheckBox>();
private void laodLanguage()
{
//frmNewReportGroup = No Code [Maintain Report Group]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then frmNewReportGroup.Caption = rsLang("LanguageLayoutLnk_Description"): frmNewReportGroup.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1074;
//Undo|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004;
//Exit|Checked
if (modRecordSet.rsLang.RecordCount){cmdCancel.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdCancel.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1010;
//General|Checked
if (modRecordSet.rsLang.RecordCount){_lbl_5.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_5.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;}
//lblLabels(38) = No Code [Report Group Name]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then lblLabels(38).Caption = rsLang("LanguageLayoutLnk_Description"): lblLabels(38).RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
//_chkFields_0 = No Code [Disable this Report Group]
//rsLang.filter = "LanguageLayoutLnk_LanguageID=" & 0000
//If rsLang.RecordCount Then _chkFields_0.Caption = rsLang("LanguageLayoutLnk_Description"): _chkFields_0.RightToLeft = rsLang("LanguageLayoutLnk_RightTL")
}
private void buildDataControls()
{
}
private void doDataControl(ref myDataGridView dataControl, ref string sql, ref string DataField, ref string boundColumn, ref string listField)
{
//Dim rs As ADODB.Recordset
//rs = getRS(sql)
//dataControl.DataSource = rs
//dataControl.DataSource = adoPrimaryRS
//dataControl.DataField = DataField
//dataControl.boundColumn = boundColumn
//dataControl.listField = listField
}
public void loadItem(ref int id)
{
System.Windows.Forms.TextBox oText = null;
System.Windows.Forms.CheckBox oCheck = null;
// ERROR: Not supported in C#: OnErrorStatement
if (id) {
adoPrimaryRS = modRecordSet.getRS(ref "select * from ReportGroup where ReportID = " + id);
} else {
adoPrimaryRS = modRecordSet.getRS(ref "select * from ReportGroup");
adoPrimaryRS.AddNew();
this.Text = this.Text + " [New record]";
mbAddNewFlag = true;
}
setup();
foreach (TextBox oText_loopVariable in txtFields) {
oText = oText_loopVariable;
oText.DataBindings.Add(adoPrimaryRS);
oText.MaxLength = adoPrimaryRS.Fields(oText.DataBindings).DefinedSize;
}
foreach (CheckBox oCheck_loopVariable in this.chkFields) {
oCheck = oCheck_loopVariable;
oCheck.DataBindings.Add(adoPrimaryRS);
}
buildDataControls();
mbDataChanged = false;
laodLanguage();
ShowDialog();
}
private void setup()
{
}
private void frmNewReportGroup_Load(object sender, System.EventArgs e)
{
txtFields.AddRange(new TextBox[] { _txtFields_0 });
chkFields.AddRange(new CheckBox[] { _chkFields_0 });
}
private void frmNewReportGroup_Resize(System.Object eventSender, System.EventArgs eventArgs)
{
Button cmdLast = new Button();
Button cmdnext = new Button();
Label lblStatus = new Label();
// ERROR: Not supported in C#: OnErrorStatement
lblStatus.Width = sizeConvertors.pixelToTwips(this.Width, true) - 1500;
cmdnext.Left = lblStatus.Width + 700;
cmdLast.Left = cmdnext.Left + 340;
}
private void frmNewReportGroup_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs)
{
short KeyAscii = Strings.Asc(eventArgs.KeyChar);
if (mbEditFlag | mbAddNewFlag)
goto EventExitSub;
switch (KeyAscii) {
case System.Windows.Forms.Keys.Escape:
KeyAscii = 0;
adoPrimaryRS.Move(0);
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
cmdClose_Click(cmdClose, new System.EventArgs());
break;
}
EventExitSub:
eventArgs.KeyChar = Strings.Chr(KeyAscii);
if (KeyAscii == 0) {
eventArgs.Handled = true;
}
}
private void frmNewReportGroup_FormClosed(System.Object eventSender, System.Windows.Forms.FormClosedEventArgs eventArgs)
{
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
}
private void adoPrimaryRS_MoveComplete(ADODB.EventReasonEnum adReason, ADODB.Error pError, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This will display the current record position for this recordset
}
private void adoPrimaryRS_WillChangeRecord(ADODB.EventReasonEnum adReason, int cRecords, ref ADODB.EventStatusEnum adStatus, ADODB.Recordset pRecordset)
{
//This is where you put validation code
//This event gets called when the following actions occur
bool bCancel = false;
switch (adReason) {
case ADODB.EventReasonEnum.adRsnAddNew:
break;
case ADODB.EventReasonEnum.adRsnClose:
break;
case ADODB.EventReasonEnum.adRsnDelete:
break;
case ADODB.EventReasonEnum.adRsnFirstChange:
break;
case ADODB.EventReasonEnum.adRsnMove:
break;
case ADODB.EventReasonEnum.adRsnRequery:
break;
case ADODB.EventReasonEnum.adRsnResynch:
break;
case ADODB.EventReasonEnum.adRsnUndoAddNew:
break;
case ADODB.EventReasonEnum.adRsnUndoDelete:
break;
case ADODB.EventReasonEnum.adRsnUndoUpdate:
break;
case ADODB.EventReasonEnum.adRsnUpdate:
break;
}
if (bCancel)
adStatus = ADODB.EventStatusEnum.adStatusCancel;
}
private void cmdCancel_Click(System.Object eventSender, System.EventArgs eventArgs)
{
// ERROR: Not supported in C#: OnErrorStatement
if (mbAddNewFlag) {
this.Close();
} else {
mbEditFlag = false;
mbAddNewFlag = false;
adoPrimaryRS.CancelUpdate();
if (mvBookMark > 0) {
adoPrimaryRS.Bookmark = mvBookMark;
} else {
adoPrimaryRS.MoveFirst();
}
mbDataChanged = false;
}
}
private bool update_Renamed()
{
bool functionReturnValue = false;
// ERROR: Not supported in C#: OnErrorStatement
functionReturnValue = true;
adoPrimaryRS.UpdateBatch(ADODB.AffectEnum.adAffectAll);
if (mbAddNewFlag) {
adoPrimaryRS.MoveLast();
//move to the new record
}
mbEditFlag = false;
mbAddNewFlag = false;
mbDataChanged = false;
return functionReturnValue;
UpdateErr:
Interaction.MsgBox(Err().Description);
functionReturnValue = false;
return functionReturnValue;
}
private void cmdClose_Click(System.Object eventSender, System.EventArgs eventArgs)
{
cmdClose.Focus();
System.Windows.Forms.Application.DoEvents();
if (update_Renamed()) {
this.Close();
}
}
private void txtFields_Enter(System.Object eventSender, System.EventArgs eventArgs)
{
int Index = 0;
TextBox textBox = new TextBox();
textBox = (TextBox)eventSender;
Index = GetIndex.GetIndexer(ref textBox, ref txtFields);
modUtilities.MyGotFocus(ref txtFields[Index]);
}
}
}
| |
namespace Schema.NET.Test;
using System;
using System.Collections.Generic;
using System.Linq;
using Xunit;
public class Values4Test
{
[Fact]
public void Constructor_Value1Passed_OnlyValue1HasValue()
{
var values = new Values<int, string, DayOfWeek, Person>(1);
Assert.True(values.HasValue1);
Assert.Single(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.Equal(new List<object>() { 1 }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_Value2Passed_OnlyValue2HasValue()
{
var values = new Values<int, string, DayOfWeek, Person>("Foo");
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.True(values.HasValue2);
Assert.Single(values.Value2);
Assert.Equal(new List<object>() { "Foo" }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_Value3Passed_OnlyValue3HasValue()
{
var values = new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday);
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.True(values.HasValue3);
Assert.Single(values.Value3);
Assert.Equal(new List<object>() { DayOfWeek.Friday }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_Value4Passed_OnlyValue4HasValue()
{
var values = new Values<int, string, DayOfWeek, Person>(new Person());
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.True(values.HasValue4);
Assert.Single(values.Value4);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<Person>(item);
}
[Fact]
public void Constructor_Items_HasAllItems()
{
var person = new Person();
var values = new Values<int, string, DayOfWeek, Person>(1, "Foo", DayOfWeek.Friday, person);
Assert.True(values.HasValue1);
Assert.Single(values.Value1);
Assert.True(values.HasValue2);
Assert.Single(values.Value2);
Assert.True(values.HasValue3);
Assert.Single(values.Value3);
Assert.True(values.HasValue4);
Assert.Single(values.Value4);
Assert.Equal(new List<object>() { 1, "Foo", DayOfWeek.Friday, person }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void Constructor_NullList_ThrowsArgumentNullException() =>
Assert.Throws<ArgumentNullException>(() => new Values<int, string, DayOfWeek, Person>((List<object>)null!));
[Theory]
[InlineData(0)]
[InlineData(1, 1)]
[InlineData(2, 1, 2)]
[InlineData(1, "Foo")]
[InlineData(2, "Foo", "Bar")]
[InlineData(1, DayOfWeek.Friday)]
[InlineData(2, DayOfWeek.Friday, DayOfWeek.Monday)]
[InlineData(3, 1, "Foo", DayOfWeek.Friday)]
[InlineData(6, 1, 2, "Foo", "Bar", DayOfWeek.Friday, DayOfWeek.Monday)]
public void Count_Items_ReturnsExpectedCount(int expectedCount, params object[] items) =>
Assert.Equal(expectedCount, new Values<int, string, DayOfWeek, Person>(items).Count);
[Fact]
public void HasValue_DoesntHaveValue_ReturnsFalse() =>
Assert.False(default(Values<int, string, DayOfWeek, Person>).HasValue);
[Theory]
[InlineData(1)]
[InlineData("Foo")]
[InlineData(DayOfWeek.Friday)]
public void HasValue_HasValue_ReturnsTrue(params object[] parameters) =>
Assert.True(new Values<int, string, DayOfWeek, Person>(parameters).HasValue);
[Fact]
public void HasValue1_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(1).HasValue1);
[Fact]
public void HasValue1_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>("Foo").HasValue1);
[Fact]
public void HasValue2_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>("Foo").HasValue2);
[Fact]
public void HasValue2_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(1).HasValue2);
[Fact]
public void HasValue3_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday).HasValue3);
[Fact]
public void HasValue3_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(1).HasValue3);
[Fact]
public void HasValue4_HasValue_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(new Person()).HasValue4);
[Fact]
public void HasValue4_DoesntHaveValue_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(1).HasValue4);
[Fact]
public void ImplicitConversionOperator_Value1Passed_OnlyValue1HasValue()
{
Values<int, string, DayOfWeek, Person> values = 1;
Assert.True(values.HasValue1);
Assert.Single(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.Equal(new List<object>() { 1 }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value2Passed_OnlyValue2HasValue()
{
Values<int, string, DayOfWeek, Person> values = "Foo";
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.True(values.HasValue2);
Assert.Single(values.Value2);
Assert.Equal(new List<object>() { "Foo" }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value3Passed_OnlyValue3HasValue()
{
Values<int, string, DayOfWeek, Person> values = DayOfWeek.Friday;
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.True(values.HasValue3);
Assert.Single(values.Value3);
Assert.Equal(new List<object>() { DayOfWeek.Friday }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value4Passed_OnlyValue4HasValue()
{
Values<int, string, DayOfWeek, Person> values = new Person();
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.True(values.HasValue4);
Assert.Single(values.Value4);
var item = Assert.Single(((IValues)values).Cast<object>().ToList());
Assert.IsType<Person>(item);
}
[Fact]
public void ImplicitConversionOperator_Value1CollectionPassed_OnlyValue1HasValue()
{
Values<int, string, DayOfWeek, Person> values = new List<int>() { 1, 2 };
Assert.True(values.HasValue1);
Assert.Equal(2, values.Value1.Count);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.Equal(new List<object>() { 1, 2 }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value2CollectionPassed_OnlyValue2HasValue()
{
Values<int, string, DayOfWeek, Person> values = new List<string>() { "Foo", "Bar" };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.True(values.HasValue2);
Assert.Equal(2, values.Value2.Count);
Assert.Equal(new List<object>() { "Foo", "Bar" }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value3CollectionPassed_OnlyValue3HasValue()
{
Values<int, string, DayOfWeek, Person> values = new List<DayOfWeek>() { DayOfWeek.Friday, DayOfWeek.Monday };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.True(values.HasValue3);
Assert.Equal(2, values.Value3.Count);
Assert.Equal(new List<object>() { DayOfWeek.Friday, DayOfWeek.Monday }, ((IValues)values).Cast<object>().ToList());
}
[Fact]
public void ImplicitConversionOperator_Value4CollectionPassed_OnlyValue4HasValue()
{
Values<int, string, DayOfWeek, Person> values = new List<Person>() { new Person(), new Person() };
Assert.False(values.HasValue1);
Assert.Empty(values.Value1);
Assert.False(values.HasValue2);
Assert.Empty(values.Value2);
Assert.False(values.HasValue3);
Assert.Empty(values.Value3);
Assert.True(values.HasValue4);
Assert.Equal(2, values.Value4.Count);
Assert.Equal(2, ((IValues)values).Cast<object>().ToList().Count);
}
[Fact]
public void ImplicitConversionToList_Value1Passed_ReturnsMatchingList()
{
List<int> values = new Values<int, string, DayOfWeek, Person>(1);
Assert.Equal(new List<int>() { 1 }, values);
}
[Fact]
public void ImplicitConversionToList_Value2Passed_ReturnsMatchingList()
{
List<string> values = new Values<int, string, DayOfWeek, Person>("Foo");
Assert.Equal(new List<string>() { "Foo" }, values);
}
[Fact]
public void ImplicitConversionToList_Value3Passed_ReturnsMatchingList()
{
List<DayOfWeek> values = new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday);
Assert.Equal(new List<DayOfWeek>() { DayOfWeek.Friday }, values);
}
[Fact]
public void ImplicitConversionToList_Value4Passed_ReturnsMatchingList()
{
var person = new Person();
List<Person> values = new Values<int, string, DayOfWeek, Person>(person);
Assert.Equal(new List<Person>() { person }, values);
}
[Fact]
public void Deconstruct_Values_ReturnsAllEnumerables()
{
var person = new Person();
var (integers, strings, daysOfWeek, people) = new Values<int, string, DayOfWeek, Person>(1, "Foo", DayOfWeek.Friday, person);
Assert.Equal(new List<int>() { 1 }, integers);
Assert.Equal(new List<string>() { "Foo" }, strings);
Assert.Equal(new List<DayOfWeek>() { DayOfWeek.Friday }, daysOfWeek);
Assert.Equal(new List<Person>() { person }, people);
}
[Fact]
public void EqualsOperator_EqualValue1Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(1) == new Values<int, string, DayOfWeek, Person>(1));
[Fact]
public void EqualsOperator_NotEqualValue1Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(1) == new Values<int, string, DayOfWeek, Person>(2));
[Fact]
public void EqualsOperator_EqualValue2Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>("Foo") == new Values<int, string, DayOfWeek, Person>("Foo"));
[Fact]
public void EqualsOperator_NotEqualValue2Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>("Foo") == new Values<int, string, DayOfWeek, Person>("Bar"));
[Fact]
public void EqualsOperator_EqualValue3Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday) == new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday));
[Fact]
public void EqualsOperator_NotEqualValue3Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday) == new Values<int, string, DayOfWeek, Person>(DayOfWeek.Monday));
[Fact]
public void EqualsOperator_EqualValue4Passed_ReturnsTrue()
{
var person = new Person();
Assert.True(new Values<int, string, DayOfWeek, Person>(person) == new Values<int, string, DayOfWeek, Person>(person));
}
[Fact]
public void EqualsOperator_NotEqualValue4Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new Person { Name = "A" }) == new Values<int, string, DayOfWeek, Person>(new Person { Name = "B" }));
[Fact]
public void NotEqualsOperator_EqualValue1Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(1) != new Values<int, string, DayOfWeek, Person>(1));
[Fact]
public void NotEqualsOperator_NotEqualValue1Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(1) != new Values<int, string, DayOfWeek, Person>(2));
[Fact]
public void NotEqualsOperator_EqualValue2Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>("Foo") != new Values<int, string, DayOfWeek, Person>("Foo"));
[Fact]
public void NotEqualsOperator_NotEqualValue2Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>("Foo") != new Values<int, string, DayOfWeek, Person>("Bar"));
[Fact]
public void NotEqualsOperator_EqualValue3Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday) != new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday));
[Fact]
public void NotEqualsOperator_NotEqualValue3Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday) != new Values<int, string, DayOfWeek, Person>(DayOfWeek.Monday));
[Fact]
public void NotEqualsOperator_EqualValue4Passed_ReturnsFalse()
{
var person = new Person();
Assert.False(new Values<int, string, DayOfWeek, Person>(person) != new Values<int, string, DayOfWeek, Person>(person));
}
[Fact]
public void NotEqualsOperator_NotEqualValue4Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(new Person { Name = "A" }) != new Values<int, string, DayOfWeek, Person>(new Person { Name = "B" }));
[Fact]
public void Equals_EqualValue1Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(1).Equals(new Values<int, string, DayOfWeek, Person>(1)));
[Fact]
public void Equals_NotEqualValue1Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(1).Equals(new Values<int, string, DayOfWeek, Person>(2)));
[Fact]
public void Equals_EqualValue2Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>("Foo").Equals(new Values<int, string, DayOfWeek, Person>("Foo")));
[Fact]
public void Equals_NotEqualValue2Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>("Foo").Equals(new Values<int, string, DayOfWeek, Person>("Bar")));
[Fact]
public void Equals_EqualValue3Passed_ReturnsTrue() =>
Assert.True(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday).Equals(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday)));
[Fact]
public void Equals_NotEqualValue3Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Friday).Equals(new Values<int, string, DayOfWeek, Person>(DayOfWeek.Monday)));
[Fact]
public void Equals_EqualValue4Passed_ReturnsTrue()
{
var person = new Person();
Assert.True(new Values<int, string, DayOfWeek, Person>(person).Equals(new Values<int, string, DayOfWeek, Person>(person)));
}
[Fact]
public void Equals_NotEqualValue4Passed_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new Person { Name = "A" }).Equals(new Values<int, string, DayOfWeek, Person>(new Person { Name = "B" })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2EqualValue3EqualValue4NotEqual_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person { Name = "Schema" } })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2EqualValue3NotEqualValue4Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Wednesday, new Person() })));
[Fact]
public void Equals_MixedTypes_Value1EqualValue2NotEqualValue3EqualValue4Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Bar", DayOfWeek.Tuesday, new Person() })));
[Fact]
public void Equals_MixedTypes_Value1NotEqualValue2EqualValue3EqualValue4Equal_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 1, "Foo", DayOfWeek.Tuesday, new Person() })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue4_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue3_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue2_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() })));
[Fact]
public void Equals_MixedTypes_ThisMissingValue1_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue4_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue3_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", new Person() })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue2_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { 0, DayOfWeek.Tuesday, new Person() })));
[Fact]
public void Equals_MixedTypes_OtherMissingValue1_ReturnsFalse() =>
Assert.False(new Values<int, string, DayOfWeek, Person>(new object[] { 0, "Foo", DayOfWeek.Tuesday, new Person() }).Equals(new Values<int, string, DayOfWeek, Person>(new object[] { "Foo", DayOfWeek.Tuesday, new Person() })));
[Fact]
public void GetHashCode_Value1Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
CombineHashCodes(CombineHashCodes(CombineHashCodes(1.GetHashCode(), 0), 0), 0),
new Values<int, string, DayOfWeek?, Person>(1).GetHashCode());
[Fact]
public void GetHashCode_Value2Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
CombineHashCodes(CombineHashCodes("Foo".GetHashCode(StringComparison.Ordinal), 0), 0),
new Values<int, string, DayOfWeek?, Person>("Foo").GetHashCode());
[Fact]
public void GetHashCode_Value3Passed_ReturnsMatchingHashCode() =>
Assert.Equal(
CombineHashCodes(DayOfWeek.Friday.GetHashCode(), 0),
new Values<int, string, DayOfWeek?, Person>(DayOfWeek.Friday).GetHashCode());
[Fact]
public void GetHashCode_Value4Passed_ReturnsMatchingHashCode()
{
var person = new Person();
Assert.Equal(person.GetHashCode(), new Values<int, string, DayOfWeek?, Person>(person).GetHashCode());
}
private static int CombineHashCodes(int h1, int h2) => ((h1 << 5) + h1) ^ h2;
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
#endregion
using System;
namespace Quartz.Impl.Triggers
{
/// <summary>
/// A concrete <see cref="ITrigger" /> that is used to fire a <see cref="IJobDetail" />
/// at a given moment in time, and optionally repeated at a specified interval.
/// </summary>
/// <seealso cref="ITrigger" />
/// <seealso cref="ICronTrigger" />
/// <author>James House</author>
/// <author>Contributions by Lieven Govaerts of Ebitec Nv, Belgium.</author>
/// <author>Marko Lahma (.NET)</author>
[Serializable]
public class SimpleTriggerImpl : AbstractTrigger, ISimpleTrigger
{
/// <summary>
/// Used to indicate the 'repeat count' of the trigger is indefinite. Or in
/// other words, the trigger should repeat continually until the trigger's
/// ending timestamp.
/// </summary>
public const int RepeatIndefinitely = -1;
private const int YearToGiveupSchedulingAt = 2299;
private DateTimeOffset? nextFireTimeUtc;
private DateTimeOffset? previousFireTimeUtc;
private int repeatCount;
private TimeSpan repeatInterval = TimeSpan.Zero;
private int timesTriggered;
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> with no settings.
/// </summary>
public SimpleTriggerImpl()
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name) : this(name, null)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group)
: this(name, group, SystemTime.UtcNow(), null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, int repeatCount, TimeSpan repeatInterval)
: this(name, null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur immediately, and
/// repeat at the given interval the given number of times.
/// </summary>
public SimpleTriggerImpl(string name, string group, int repeatCount, TimeSpan repeatInterval)
: this(name, group, SystemTime.UtcNow(), null, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc)
: this(name, null, startTimeUtc)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and not repeat.
/// </summary>
public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc)
: this(name, group, startTimeUtc, null, 0, TimeSpan.Zero)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: this(name, null, startTimeUtc, endTimeUtc, repeatCount, repeatInterval)
{
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// and repeat at the given interval the given number of times, or until
/// the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="startTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" /> to fire.</param>
/// <param name="endTimeUtc">A UTC <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use <see cref="RepeatIndefinitely "/> for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc, int repeatCount, TimeSpan repeatInterval)
: base(name, group)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Create a <see cref="SimpleTriggerImpl" /> that will occur at the given time,
/// fire the identified <see cref="IJob" /> and repeat at the given
/// interval the given number of times, or until the given end time.
/// </summary>
/// <param name="name">The name.</param>
/// <param name="group">The group.</param>
/// <param name="jobName">Name of the job.</param>
/// <param name="jobGroup">The job group.</param>
/// <param name="startTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to fire.</param>
/// <param name="endTimeUtc">A <see cref="DateTimeOffset" /> set to the time for the <see cref="ITrigger" />
/// to quit repeat firing.</param>
/// <param name="repeatCount">The number of times for the <see cref="ITrigger" /> to repeat
/// firing, use RepeatIndefinitely for unlimited times.</param>
/// <param name="repeatInterval">The time span to pause between the repeat firing.</param>
public SimpleTriggerImpl(string name, string group, string jobName, string jobGroup, DateTimeOffset startTimeUtc,
DateTimeOffset? endTimeUtc,
int repeatCount, TimeSpan repeatInterval)
: base(name, group, jobName, jobGroup)
{
StartTimeUtc = startTimeUtc;
EndTimeUtc = endTimeUtc;
RepeatCount = repeatCount;
RepeatInterval = repeatInterval;
}
/// <summary>
/// Get or set the number of times the <see cref="SimpleTriggerImpl" /> should
/// repeat, after which it will be automatically deleted.
/// </summary>
/// <seealso cref="RepeatIndefinitely" />
public int RepeatCount
{
get { return repeatCount; }
set
{
if (value < 0 && value != RepeatIndefinitely)
{
throw new ArgumentException("Repeat count must be >= 0, use the constant RepeatIndefinitely for infinite.");
}
repeatCount = value;
}
}
/// <summary>
/// Get or set the time interval at which the <see cref="ISimpleTrigger" /> should repeat.
/// </summary>
public TimeSpan RepeatInterval
{
get { return repeatInterval; }
set
{
if (value < TimeSpan.Zero)
{
throw new ArgumentException("Repeat interval must be >= 0");
}
repeatInterval = value;
}
}
/// <summary>
/// Get or set the number of times the <see cref="ISimpleTrigger" /> has already
/// fired.
/// </summary>
public virtual int TimesTriggered
{
get { return timesTriggered; }
set { timesTriggered = value; }
}
public override IScheduleBuilder GetScheduleBuilder()
{
SimpleScheduleBuilder sb = SimpleScheduleBuilder.Create()
.WithInterval(RepeatInterval)
.WithRepeatCount(RepeatCount);
switch (MisfireInstruction)
{
case Quartz.MisfireInstruction.SimpleTrigger.FireNow: sb.WithMisfireHandlingInstructionFireNow();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount: sb.WithMisfireHandlingInstructionNextWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount : sb.WithMisfireHandlingInstructionNextWithRemainingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount : sb.WithMisfireHandlingInstructionNowWithExistingCount();
break;
case Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount: sb.WithMisfireHandlingInstructionNowWithRemainingCount();
break;
}
return sb;
}
/// <summary>
/// Returns the final UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, if repeatCount is RepeatIndefinitely, null will be returned.
/// <para>
/// Note that the return time may be in the past.
/// </para>
/// </summary>
public override DateTimeOffset? FinalFireTimeUtc
{
get
{
if (repeatCount == 0)
{
return StartTimeUtc;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
if (repeatCount == RepeatIndefinitely && !EndTimeUtc.HasValue)
{
return null;
}
else if (repeatCount == RepeatIndefinitely)
{
return GetFireTimeBefore(EndTimeUtc);
}
DateTimeOffset lastTrigger = StartTimeUtc.AddMilliseconds(repeatCount * repeatInterval.TotalMilliseconds);
if (!EndTimeUtc.HasValue || lastTrigger < EndTimeUtc.Value)
{
return lastTrigger;
}
else
{
return GetFireTimeBefore(EndTimeUtc);
}
}
}
/// <summary>
/// Tells whether this Trigger instance can handle events
/// in millisecond precision.
/// </summary>
/// <value></value>
public override bool HasMillisecondPrecision
{
get { return true; }
}
/// <summary>
/// Validates the misfire instruction.
/// </summary>
/// <param name="misfireInstruction">The misfire instruction.</param>
/// <returns></returns>
protected override bool ValidateMisfireInstruction(int misfireInstruction)
{
if (misfireInstruction < Quartz.MisfireInstruction.IgnoreMisfirePolicy)
{
return false;
}
if (misfireInstruction > Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
return false;
}
return true;
}
/// <summary>
/// Updates the <see cref="ISimpleTrigger" />'s state based on the
/// MisfireInstruction value that was selected when the <see cref="ISimpleTrigger" />
/// was created.
/// </summary>
/// <remarks>
/// If MisfireSmartPolicyEnabled is set to true,
/// then the following scheme will be used: <br />
/// <ul>
/// <li>If the Repeat Count is 0, then the instruction will
/// be interpreted as <see cref="MisfireInstruction.SimpleTrigger.FireNow" />.</li>
/// <li>If the Repeat Count is <see cref="RepeatIndefinitely" />, then
/// the instruction will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount" />.
/// <b>WARNING:</b> using MisfirePolicy.SimpleTrigger.RescheduleNowWithRemainingRepeatCount
/// with a trigger that has a non-null end-time may cause the trigger to
/// never fire again if the end-time arrived during the misfire time span.
/// </li>
/// <li>If the Repeat Count is > 0, then the instruction
/// will be interpreted as <see cref="MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount" />.
/// </li>
/// </ul>
/// </remarks>
public override void UpdateAfterMisfire(ICalendar cal)
{
int instr = MisfireInstruction;
if (instr == Quartz.MisfireInstruction.SmartPolicy)
{
if (RepeatCount == 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.FireNow;
}
else if (RepeatCount == RepeatIndefinitely)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount;
}
else
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow && RepeatCount != 0)
{
instr = Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount;
}
if (instr == Quartz.MisfireInstruction.SimpleTrigger.FireNow)
{
nextFireTimeUtc = SystemTime.UtcNow();
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithExistingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNextWithRemainingCount)
{
DateTimeOffset? newFireTime = GetFireTimeAfter(SystemTime.UtcNow());
while (newFireTime.HasValue && cal != null && !cal.IsTimeIncluded(newFireTime.Value))
{
newFireTime = GetFireTimeAfter(newFireTime);
if (!newFireTime.HasValue)
{
break;
}
//avoid infinite loop
if (newFireTime.Value.Year > YearToGiveupSchedulingAt)
{
newFireTime = null;
}
}
if (newFireTime.HasValue)
{
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);
TimesTriggered = TimesTriggered + timesMissed;
}
nextFireTimeUtc = newFireTime;
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithExistingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
RepeatCount = RepeatCount - TimesTriggered;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
else if (instr == Quartz.MisfireInstruction.SimpleTrigger.RescheduleNowWithRemainingRepeatCount)
{
DateTimeOffset newFireTime = SystemTime.UtcNow();
int timesMissed = ComputeNumTimesFiredBetween(nextFireTimeUtc, newFireTime);
if (repeatCount != 0 && repeatCount != RepeatIndefinitely)
{
int remainingCount = RepeatCount - (TimesTriggered + timesMissed);
if (remainingCount <= 0)
{
remainingCount = 0;
}
RepeatCount = remainingCount;
TimesTriggered = 0;
}
if (EndTimeUtc.HasValue && EndTimeUtc.Value < newFireTime)
{
nextFireTimeUtc = null; // We are past the end time
}
else
{
StartTimeUtc = newFireTime;
nextFireTimeUtc = newFireTime;
}
}
}
/// <summary>
/// Called when the <see cref="IScheduler" /> has decided to 'fire'
/// the trigger (Execute the associated <see cref="IJob" />), in order to
/// give the <see cref="ITrigger" /> a chance to update itself for its next
/// triggering (if any).
/// </summary>
/// <seealso cref="JobExecutionException" />
public override void Triggered(ICalendar cal)
{
timesTriggered++;
previousFireTimeUtc = nextFireTimeUtc;
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
while (nextFireTimeUtc.HasValue && cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
}
}
/// <summary>
/// Updates the instance with new calendar.
/// </summary>
/// <param name="calendar">The calendar.</param>
/// <param name="misfireThreshold">The misfire threshold.</param>
public override void UpdateWithNewCalendar(ICalendar calendar, TimeSpan misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(previousFireTimeUtc);
if (nextFireTimeUtc == null || calendar == null)
{
return;
}
DateTimeOffset now = SystemTime.UtcNow();
while (nextFireTimeUtc.HasValue && !calendar.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
nextFireTimeUtc = null;
}
if (nextFireTimeUtc != null && nextFireTimeUtc.Value < now)
{
TimeSpan diff = now - nextFireTimeUtc.Value;
if (diff >= misfireThreshold)
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
}
}
}
}
/// <summary>
/// Called by the scheduler at the time a <see cref="ITrigger" /> is first
/// added to the scheduler, in order to have the <see cref="ITrigger" />
/// compute its first fire time, based on any associated calendar.
/// <para>
/// After this method has been called, <see cref="GetNextFireTimeUtc" />
/// should return a valid answer.
/// </para>
/// </summary>
/// <returns>
/// The first time at which the <see cref="ITrigger" /> will be fired
/// by the scheduler, which is also the same value <see cref="GetNextFireTimeUtc" />
/// will return (until after the first firing of the <see cref="ITrigger" />).
/// </returns>
public override DateTimeOffset? ComputeFirstFireTimeUtc(ICalendar cal)
{
nextFireTimeUtc = StartTimeUtc;
while (cal != null && !cal.IsTimeIncluded(nextFireTimeUtc.Value))
{
nextFireTimeUtc = GetFireTimeAfter(nextFireTimeUtc);
if (!nextFireTimeUtc.HasValue)
{
break;
}
//avoid infinite loop
if (nextFireTimeUtc.Value.Year > YearToGiveupSchedulingAt)
{
return null;
}
}
return nextFireTimeUtc;
}
/// <summary>
/// Returns the next time at which the <see cref="ISimpleTrigger" /> will
/// fire. If the trigger will not fire again, <see langword="null" /> will be
/// returned. The value returned is not guaranteed to be valid until after
/// the <see cref="ITrigger" /> has been added to the scheduler.
/// </summary>
public override DateTimeOffset? GetNextFireTimeUtc()
{
return nextFireTimeUtc;
}
public override void SetNextFireTimeUtc(DateTimeOffset? nextFireTime)
{
nextFireTimeUtc = nextFireTime;
}
public override void SetPreviousFireTimeUtc(DateTimeOffset? previousFireTime)
{
previousFireTimeUtc = previousFireTime;
}
/// <summary>
/// Returns the previous time at which the <see cref="ISimpleTrigger" /> fired.
/// If the trigger has not yet fired, <see langword="null" /> will be
/// returned.
/// </summary>
public override DateTimeOffset? GetPreviousFireTimeUtc()
{
return previousFireTimeUtc;
}
/// <summary>
/// Returns the next UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, after the given UTC time. If the trigger will not fire after the given
/// time, <see langword="null" /> will be returned.
/// </summary>
public override DateTimeOffset? GetFireTimeAfter(DateTimeOffset? afterTimeUtc)
{
if ((timesTriggered > repeatCount) && (repeatCount != RepeatIndefinitely))
{
return null;
}
if (!afterTimeUtc.HasValue)
{
afterTimeUtc = SystemTime.UtcNow();
}
if (repeatCount == 0 && afterTimeUtc.Value.CompareTo(StartTimeUtc) >= 0)
{
return null;
}
DateTimeOffset startMillis = StartTimeUtc;
DateTimeOffset afterMillis = afterTimeUtc.Value;
DateTimeOffset endMillis = !EndTimeUtc.HasValue ? DateTimeOffset.MaxValue : EndTimeUtc.Value;
if (endMillis <= afterMillis)
{
return null;
}
if (afterMillis < startMillis)
{
return startMillis;
}
long numberOfTimesExecuted = (long) (((long) (afterMillis - startMillis).TotalMilliseconds / repeatInterval.TotalMilliseconds) + 1);
if ((numberOfTimesExecuted > repeatCount) &&
(repeatCount != RepeatIndefinitely))
{
return null;
}
DateTimeOffset time = startMillis.AddMilliseconds(numberOfTimesExecuted * repeatInterval.TotalMilliseconds);
if (endMillis <= time)
{
return null;
}
return time;
}
/// <summary>
/// Returns the last UTC time at which the <see cref="ISimpleTrigger" /> will
/// fire, before the given time. If the trigger will not fire before the
/// given time, <see langword="null" /> will be returned.
/// </summary>
public virtual DateTimeOffset? GetFireTimeBefore(DateTimeOffset? endUtc)
{
if (endUtc.Value < StartTimeUtc)
{
return null;
}
int numFires = ComputeNumTimesFiredBetween(StartTimeUtc, endUtc);
return StartTimeUtc.AddMilliseconds(numFires*repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Computes the number of times fired between the two UTC date times.
/// </summary>
/// <param name="startTimeUtc">The UTC start date and time.</param>
/// <param name="endTimeUtc">The UTC end date and time.</param>
/// <returns></returns>
public virtual int ComputeNumTimesFiredBetween(DateTimeOffset? startTimeUtc, DateTimeOffset? endTimeUtc)
{
long time = (long) (endTimeUtc.Value - startTimeUtc.Value).TotalMilliseconds;
return (int) (time/repeatInterval.TotalMilliseconds);
}
/// <summary>
/// Determines whether or not the <see cref="ISimpleTrigger" /> will occur
/// again.
/// </summary>
public override bool GetMayFireAgain()
{
return GetNextFireTimeUtc().HasValue;
}
/// <summary>
/// Validates whether the properties of the <see cref="IJobDetail" /> are
/// valid for submission into a <see cref="IScheduler" />.
/// </summary>
public override void Validate()
{
base.Validate();
if (repeatCount != 0 && repeatInterval.TotalMilliseconds < 1)
{
throw new SchedulerException("Repeat Interval cannot be zero.");
}
}
}
}
| |
// 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.Tests;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.WebSockets.Client.Tests
{
/// <summary>
/// ClientWebSocket tests that do require a remote server.
/// </summary>
public class ClientWebSocketTest
{
public readonly static object[][] EchoServers = WebSocketTestServers.EchoServers;
public readonly static object[][] EchoHeadersServers = WebSocketTestServers.EchoHeadersServers;
private const int TimeOutMilliseconds = 10000;
private const int CloseDescriptionMaxLength = 123;
private readonly ITestOutputHelper _output;
public ClientWebSocketTest(ITestOutputHelper output)
{
_output = output;
}
public static IEnumerable<object[]> UnavailableWebSocketServers
{
get
{
Uri server;
// Unknown server.
{
server = new Uri(string.Format("ws://{0}", Guid.NewGuid().ToString()));
yield return new object[] { server };
}
// Known server but not a real websocket endpoint.
{
server = HttpTestServers.RemoteEchoServer;
var ub = new UriBuilder("ws", server.Host, server.Port, server.PathAndQuery);
yield return new object[] { ub.Uri };
}
}
}
private static bool WebSocketsSupported { get { return WebSocketHelper.WebSocketsSupported; } }
#region Connect
[ConditionalTheory("WebSocketsSupported"), MemberData("UnavailableWebSocketServers")]
public async Task ConnectAsync_NotWebSocketServer_ThrowsWebSocketExceptionWithMessage(Uri server)
{
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ConnectAsync(server, cts.Token));
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task EchoBinaryMessage_Success(Uri server)
{
await WebSocketHelper.TestEcho(server, WebSocketMessageType.Binary, TimeOutMilliseconds, _output);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task EchoTextMessage_Success(Uri server)
{
await WebSocketHelper.TestEcho(server, WebSocketMessageType.Text, TimeOutMilliseconds, _output);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoHeadersServers")]
public async Task ConnectAsync_AddCustomHeaders_Success(Uri server)
{
using (var cws = new ClientWebSocket())
{
cws.Options.SetRequestHeader("X-CustomHeader1", "Value1");
cws.Options.SetRequestHeader("X-CustomHeader2", "Value2");
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
Task taskConnect = cws.ConnectAsync(server, cts.Token);
Assert.True(
(cws.State == WebSocketState.None) ||
(cws.State == WebSocketState.Connecting) ||
(cws.State == WebSocketState.Open),
"State immediately after ConnectAsync incorrect: " + cws.State);
await taskConnect;
}
Assert.Equal(WebSocketState.Open, cws.State);
byte[] buffer = new byte[65536];
var segment = new ArraySegment<byte>(buffer, 0, buffer.Length);
WebSocketReceiveResult recvResult;
using (var cts = new CancellationTokenSource(TimeOutMilliseconds))
{
recvResult = await cws.ReceiveAsync(segment, cts.Token);
}
Assert.Equal(WebSocketMessageType.Text, recvResult.MessageType);
string headers = WebSocketData.GetTextFromBuffer(segment);
Assert.True(headers.Contains("X-CustomHeader1:Value1"));
Assert.True(headers.Contains("X-CustomHeader2:Value2"));
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task ConnectAsync_PassNoSubProtocol_ServerRequires_ThrowsWebSocketExceptionWithMessage(Uri server)
{
const string AcceptedProtocol = "CustomProtocol";
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "subprotocol=" + AcceptedProtocol;
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ConnectAsync(ub.Uri, cts.Token));
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task ConnectAsync_PassMultipleSubProtocols_ServerRequires_ConnectionUsesAgreedSubProtocol(Uri server)
{
const string AcceptedProtocol = "AcceptedProtocol";
const string OtherProtocol = "OtherProtocol";
using (var cws = new ClientWebSocket())
{
cws.Options.AddSubProtocol(AcceptedProtocol);
cws.Options.AddSubProtocol(OtherProtocol);
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "subprotocol=" + AcceptedProtocol;
await cws.ConnectAsync(ub.Uri, cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
Assert.Equal(AcceptedProtocol, cws.SubProtocol);
}
}
#endregion
#region SendReceive
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task SendReceive_PartialMessage_Success(Uri server)
{
var sendBuffer = new byte[1024];
var sendSegment = new ArraySegment<byte>(sendBuffer);
var receiveBuffer = new byte[1024];
var receiveSegment = new ArraySegment<byte>(receiveBuffer);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
// The server will read buffers and aggregate it up to 64KB before echoing back a complete message.
// But since this test uses a receive buffer that is small, we will get back partial message fragments
// as we read them until we read the complete message payload.
for (int i = 0; i < 63; i++)
{
await cws.SendAsync(sendSegment, WebSocketMessageType.Binary, false, ctsDefault.Token);
}
await cws.SendAsync(sendSegment, WebSocketMessageType.Binary, true, ctsDefault.Token);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(receiveSegment, ctsDefault.Token);
Assert.Equal(false, recvResult.EndOfMessage);
while (recvResult.EndOfMessage == false)
{
recvResult = await cws.ReceiveAsync(receiveSegment, ctsDefault.Token);
}
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "PartialMessageTest", ctsDefault.Token);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task SendAsync_SendCloseMessageType_ThrowsArgumentExceptionWithMessage(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
"net_WebSockets_Argument_InvalidMessageType",
"Close",
"SendAsync",
"Binary",
"Text",
"CloseOutputAsync");
var expectedException = new ArgumentException(expectedInnerMessage, "messageType");
string expectedMessage = expectedException.Message;
Assert.Throws<ArgumentException>(() => {
Task t = cws.SendAsync(new ArraySegment<byte>(), WebSocketMessageType.Close, true, cts.Token); } );
Assert.Equal(WebSocketState.Open, cws.State);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task SendAsync__MultipleOutstandingSendOperations_Throws(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task [] tasks = new Task[10];
try
{
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = cws.SendAsync(
WebSocketData.GetBufferFromText("hello"),
WebSocketMessageType.Text,
true,
cts.Token);
}
Task.WaitAll(tasks);
Assert.Equal(WebSocketState.Open, cws.State);
}
catch (AggregateException ag)
{
foreach (var ex in ag.InnerExceptions)
{
if (ex is InvalidOperationException)
{
Assert.Equal(
ResourceHelper.GetExceptionMessage(
"net_Websockets_AlreadyOneOutstandingOperation",
"SendAsync"),
ex.Message);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
else if (ex is WebSocketException)
{
// Multiple cases.
Assert.Equal(WebSocketState.Aborted, cws.State);
WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode;
Assert.True(
(errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success),
"WebSocketErrorCode");
}
else
{
Assert.True(false, "Unexpected exception: " + ex.Message);
}
}
}
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task ReceiveAsync_MultipleOutstandingReceiveOperations_Throws(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task[] tasks = new Task[2];
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
cts.Token);
var recvBuffer = new byte[100];
var recvSegment = new ArraySegment<byte>(recvBuffer);
try
{
for (int i = 0; i < tasks.Length; i++)
{
tasks[i] = cws.ReceiveAsync(recvSegment, cts.Token);
}
Task.WaitAll(tasks);
Assert.Equal(WebSocketState.Open, cws.State);
}
catch (AggregateException ag)
{
foreach (var ex in ag.InnerExceptions)
{
if (ex is InvalidOperationException)
{
Assert.Equal(
ResourceHelper.GetExceptionMessage(
"net_Websockets_AlreadyOneOutstandingOperation",
"ReceiveAsync"),
ex.Message);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
else if (ex is WebSocketException)
{
// Multiple cases.
Assert.Equal(WebSocketState.Aborted, cws.State);
WebSocketError errCode = (ex as WebSocketException).WebSocketErrorCode;
Assert.True(
(errCode == WebSocketError.InvalidState) || (errCode == WebSocketError.Success),
"WebSocketErrorCode");
}
else
{
Assert.True(false, "Unexpected exception: " + ex.Message);
}
}
}
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task SendAsync_SendZeroLengthPayloadAsEndOfMessage_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string message = "hello";
await cws.SendAsync(
WebSocketData.GetBufferFromText(message),
WebSocketMessageType.Text,
false,
cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
await cws.SendAsync(new ArraySegment<byte>(new byte[0]),
WebSocketMessageType.Text,
true,
cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
var recvBuffer = new byte[100];
var receiveSegment = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvRet = await cws.ReceiveAsync(receiveSegment, cts.Token);
Assert.Equal(WebSocketState.Open, cws.State);
Assert.Equal(message.Length, recvRet.Count);
Assert.Equal(WebSocketMessageType.Text, recvRet.MessageType);
Assert.Equal(true, recvRet.EndOfMessage);
Assert.Equal(null, recvRet.CloseStatus);
Assert.Equal(null, recvRet.CloseStatusDescription);
var recvSegment = new ArraySegment<byte>(receiveSegment.Array, receiveSegment.Offset, recvRet.Count);
Assert.Equal(message, WebSocketData.GetTextFromBuffer(recvSegment));
}
}
#endregion
#region Close
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseAsync_ServerInitiatedClose_Success(Uri server)
{
const string closeWebSocketMetaCommand = ".close";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
_output.WriteLine("SendAsync starting.");
await cws.SendAsync(
WebSocketData.GetBufferFromText(closeWebSocketMetaCommand),
WebSocketMessageType.Text,
true,
cts.Token);
_output.WriteLine("SendAsync done.");
var recvBuffer = new byte[256];
_output.WriteLine("ReceiveAsync starting.");
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(new ArraySegment<byte>(recvBuffer), cts.Token);
_output.WriteLine("ReceiveAsync done.");
// Verify received server-initiated close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, recvResult.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, recvResult.CloseStatusDescription);
// Verify current websocket state as CloseReceived which indicates only partial close.
Assert.Equal(WebSocketState.CloseReceived, cws.State);
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
// Send back close message to acknowledge server-initiated close.
_output.WriteLine("CloseAsync starting.");
await cws.CloseAsync(WebSocketCloseStatus.InvalidMessageType, string.Empty, cts.Token);
_output.WriteLine("CloseAsync done.");
Assert.Equal(WebSocketState.Closed, cws.State);
// Verify that there is no follow-up echo close message back from the server by
// making sure the close code and message are the same as from the first server close message.
Assert.Equal(WebSocketCloseStatus.NormalClosure, cws.CloseStatus);
Assert.Equal(closeWebSocketMetaCommand, cws.CloseStatusDescription);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseAsync_ClientInitiatedClose_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Assert.Equal(WebSocketState.Open, cws.State);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_InvalidMessageType";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(WebSocketState.Closed, cws.State);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseAsync_CloseDescriptionIsMaxLength_Success(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseAsync_CloseDescriptionIsMaxLengthPlusOne_ThrowsArgumentException(Uri server)
{
string closeDescription = new string('C', CloseDescriptionMaxLength + 1);
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
string expectedInnerMessage = ResourceHelper.GetExceptionMessage(
"net_WebSockets_InvalidCloseStatusDescription",
closeDescription,
CloseDescriptionMaxLength);
var expectedException = new ArgumentException(expectedInnerMessage, "statusDescription");
string expectedMessage = expectedException.Message;
Assert.Throws<ArgumentException>(() =>
{ Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, closeDescription, cts.Token); });
Assert.Equal(WebSocketState.Open, cws.State);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseAsync_CloseDescriptionHasUnicode_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidMessageType;
string closeDescription = "CloseAsync_Containing\u016Cnicode.";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(true, String.IsNullOrEmpty(cws.CloseStatusDescription));
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseOutputAsync_ClientInitiated_CanReceive_CanClose(Uri server)
{
string message = "Hello WebSockets!";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
string closeDescription = "CloseOutputAsync_Client_InvalidPayloadData";
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Need a short delay as per WebSocket rfc6455 section 5.5.1 there isn't a requirement to receive any
// data fragments after a close has been sent. The delay allows the received data fragment to be
// available before calling close. The WinRT MessageWebSocket implementation doesn't allow receiving
// after a call to Close.
await Task.Delay(100);
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
// Should be able to receive the message echoed by the server.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(message.Length, recvResult.Count);
segmentRecv = new ArraySegment<byte>(segmentRecv.Array, 0, recvResult.Count);
Assert.Equal(message, WebSocketData.GetTextFromBuffer(segmentRecv));
Assert.Equal(null, recvResult.CloseStatus);
Assert.Equal(null, recvResult.CloseStatusDescription);
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(closeStatus, cws.CloseStatus);
Assert.Equal(closeDescription, cws.CloseStatusDescription);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseOutputAsync_ServerInitiated_CanSend(Uri server)
{
string message = "Hello WebSockets!";
var expectedCloseStatus = WebSocketCloseStatus.NormalClosure;
var expectedCloseDescription = ".shutdown";
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".shutdown"),
WebSocketMessageType.Text,
true,
cts.Token);
// Should be able to receive a shutdown message.
var recvBuffer = new byte[100];
var segmentRecv = new ArraySegment<byte>(recvBuffer);
WebSocketReceiveResult recvResult = await cws.ReceiveAsync(segmentRecv, cts.Token);
Assert.Equal(0, recvResult.Count);
Assert.Equal(expectedCloseStatus, recvResult.CloseStatus);
Assert.Equal(expectedCloseDescription, recvResult.CloseStatusDescription);
// Verify WebSocket state
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.CloseReceived, cws.State);
// Should be able to send.
await cws.SendAsync(WebSocketData.GetBufferFromText(message), WebSocketMessageType.Text, true, cts.Token);
// Cannot change the close status/description with the final close.
var closeStatus = WebSocketCloseStatus.InvalidPayloadData;
var closeDescription = "CloseOutputAsync_Client_Description";
await cws.CloseAsync(closeStatus, closeDescription, cts.Token);
Assert.Equal(expectedCloseStatus, cws.CloseStatus);
Assert.Equal(expectedCloseDescription, cws.CloseStatusDescription);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseOutputAsync_CloseDescriptionIsNull_Success(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var closeStatus = WebSocketCloseStatus.NormalClosure;
string closeDescription = null;
await cws.CloseOutputAsync(closeStatus, closeDescription, cts.Token);
}
}
#endregion
#region Abort
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public void Abort_ConnectAndAbort_ThrowsWebSocketExceptionWithmessage(Uri server)
{
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(TimeOutMilliseconds);
var ub = new UriBuilder(server);
ub.Query = "delay10sec";
Task t = cws.ConnectAsync(ub.Uri, cts.Token);
cws.Abort();
WebSocketException ex = Assert.Throws<WebSocketException>(() => t.GetAwaiter().GetResult());
Assert.Equal(ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"), ex.Message);
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task Abort_SendAndAbort_Success(Uri server)
{
await TestCancellation(async (cws) => {
var cts = new CancellationTokenSource(TimeOutMilliseconds);
Task t = cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
cts.Token);
cws.Abort();
await t;
}, server);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task Abort_ReceiveAndAbort_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
Task t = cws.ReceiveAsync(segment, ctsDefault.Token);
cws.Abort();
await t;
}, server);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task Abort_CloseAndAbort_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
Task t = cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "AbortClose", ctsDefault.Token);
cws.Abort();
await t;
}, server);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task ClientWebSocket_Abort_CloseOutputAsync(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
Task t = cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "AbortShutdown", ctsDefault.Token);
cws.Abort();
await t;
}, server);
}
#endregion
#region Cancellation
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task ConnectAsync_Cancel_ThrowsWebSocketExceptionWithMessage(Uri server)
{
using (var cws = new ClientWebSocket())
{
var cts = new CancellationTokenSource(500);
var ub = new UriBuilder(server);
ub.Query = "delay10sec";
WebSocketException ex =
await Assert.ThrowsAsync<WebSocketException>(() => cws.ConnectAsync(ub.Uri, cts.Token));
Assert.Equal(
ResourceHelper.GetExceptionMessage("net_webstatus_ConnectFailure"),
ex.Message);
Assert.Equal(WebSocketError.Success, ex.WebSocketErrorCode);
Assert.Equal(WebSocketState.Closed, cws.State);
}
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task SendAsync_Cancel_Success(Uri server)
{
await TestCancellation((cws) => {
var cts = new CancellationTokenSource(5);
return cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
cts.Token);
}, server);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task ReceiveAsync_Cancel_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
var cts = new CancellationTokenSource(5);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
await cws.ReceiveAsync(segment, cts.Token);
}, server);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseAsync_Cancel_Success(Uri server)
{
await TestCancellation(async (cws) => {
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
var cts = new CancellationTokenSource(5);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
await cws.CloseAsync(WebSocketCloseStatus.NormalClosure, "CancelClose", cts.Token);
}, server);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task CloseOutputAsync_Cancel_Success(Uri server)
{
await TestCancellation(async (cws) => {
var cts = new CancellationTokenSource(5);
var ctsDefault = new CancellationTokenSource(TimeOutMilliseconds);
await cws.SendAsync(
WebSocketData.GetBufferFromText(".delay5sec"),
WebSocketMessageType.Text,
true,
ctsDefault.Token);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
await cws.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "CancelShutdown", cts.Token);
}, server);
}
[ConditionalTheory("WebSocketsSupported"), MemberData("EchoServers")]
public async Task ReceiveAsync_CancelAndReceive_ThrowsWebSocketExceptionWithMessage(Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
var cts = new CancellationTokenSource(500);
var recvBuffer = new byte[100];
var segment = new ArraySegment<byte>(recvBuffer);
try
{
await cws.ReceiveAsync(segment, cts.Token);
Assert.True(false, "Receive should not complete.");
}
catch (OperationCanceledException) { }
catch (ObjectDisposedException) { }
catch (WebSocketException) { }
WebSocketException ex = await Assert.ThrowsAsync<WebSocketException>(() =>
cws.ReceiveAsync(segment, CancellationToken.None));
Assert.Equal(
ResourceHelper.GetExceptionMessage("net_WebSockets_InvalidState", "Aborted", "Open, CloseSent"),
ex.Message);
}
}
private async Task TestCancellation(Func<ClientWebSocket, Task> action, Uri server)
{
using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket(server, TimeOutMilliseconds, _output))
{
try
{
await action(cws);
// Operation finished before CTS expired.
}
catch (OperationCanceledException)
{
// Expected exception
Assert.Equal(WebSocketState.Aborted, cws.State);
}
catch (ObjectDisposedException)
{
// Expected exception
Assert.Equal(WebSocketState.Aborted, cws.State);
}
catch (WebSocketException exception)
{
Assert.Equal(ResourceHelper.GetExceptionMessage(
"net_WebSockets_InvalidState_ClosedOrAborted",
"System.Net.WebSockets.InternalClientWebSocket",
"Aborted"),
exception.Message);
Assert.Equal(WebSocketError.InvalidState, exception.WebSocketErrorCode);
Assert.Equal(WebSocketState.Aborted, cws.State);
}
}
}
#endregion
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_OXCMSG
{
using System;
using System.Collections.Generic;
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
/// <summary>
/// A driver for property initialization.
/// </summary>
public static class PropertyHelper
{
/// <summary>
/// The dictionary for Property name and PropertyTag.
/// </summary>
private static Dictionary<PropertyNames, PropertyTag> propertyTagDic = new Dictionary<PropertyNames, PropertyTag>();
/// <summary>
/// The error code of response: access denied
/// </summary>
private static byte[] resultDeny = new byte[] { 0x05, 0x00, 0x07, 0x80 };
/// <summary>
/// The error code of response: not found
/// </summary>
private static byte[] resultNotFound = new byte[] { 0x0f, 0x01, 0x04, 0x80 };
/// <summary>
/// The error code of response: no value
/// </summary>
private static byte[] resultNullReference = new byte[] { 0xB9, 0x04, 0x00, 0x00 };
/// <summary>
/// Transfer ITestSite into adapter, make adapter can use ITestSite's function.
/// </summary>
private static ITestSite site;
/// <summary>
/// Gets the dictionary for Property name and PropertyTag.
/// </summary>
public static Dictionary<PropertyNames, PropertyTag> PropertyTagDic
{
get { return propertyTagDic; }
}
/// <summary>
/// Initialize the AdapterHelper class.
/// </summary>
/// <param name="testSite">The instance of ITestSite.</param>
public static void Initialize(ITestSite testSite)
{
site = testSite;
}
/// <summary>
/// Check whether the return value in response is error.
/// </summary>
/// <param name="responseValue">The response value</param>
/// <returns>If the response is error code, return true</returns>
public static bool IsErrorCode(byte[] responseValue)
{
return Common.CompareByteArray(responseValue, resultDeny)
|| Common.CompareByteArray(responseValue, resultNotFound)
|| Common.CompareByteArray(responseValue, resultNullReference);
}
/// <summary>
/// Check whether the return value in response is error.
/// </summary>
/// <param name="responseValue">The response value</param>
/// <returns>If the response is error code, return true</returns>
public static bool IsErrorCode(object responseValue)
{
return (responseValue is byte[]) && IsErrorCode((byte[])responseValue);
}
/// <summary>
/// Initialize the dictionary for Property name and PropertyTag.
/// </summary>
public static void InitializePropertyTagDic()
{
AddPropertyTagToDic(PropertyNames.PidTagHasAttachments, new PropertyTag(0x0E1B, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagMessageClass, new PropertyTag(0x001A, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagMessageCodepage, new PropertyTag(0x3FFD, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagMessageLocaleId, new PropertyTag(0x3FF1, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagMessageSize, new PropertyTag(0x0E08, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagMessageStatus, new PropertyTag(0x0E17, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagSubjectPrefix, new PropertyTag(0x003D, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagNormalizedSubject, new PropertyTag(0x0E1D, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagImportance, new PropertyTag(0x0017, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagPriority, new PropertyTag(0x0026, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagSensitivity, new PropertyTag(0x0036, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidNameKeywords, new PropertyTag(0x0000, (ushort)PropertyType.PtypMultipleString));
AddPropertyTagToDic(PropertyNames.PidTagAutoForwardComment, new PropertyTag(0x0004, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagBody, new PropertyTag(0x1000, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagNativeBody, new PropertyTag(0x1016, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagBodyHtml, new PropertyTag(0x1013, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagRtfCompressed, new PropertyTag(0x1009, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagRtfInSync, new PropertyTag(0x0E1F, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagInternetCodepage, new PropertyTag(0x3FDE, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagArchiveTag, new PropertyTag(0x3018, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagPolicyTag, new PropertyTag(0x3019, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagRetentionPeriod, new PropertyTag(0x301A, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagStartDateEtc, new PropertyTag(0x301B, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagRetentionDate, new PropertyTag(0x301C, (ushort)PropertyType.PtypTime));
AddPropertyTagToDic(PropertyNames.PidTagRetentionFlags, new PropertyTag(0x301D, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagArchivePeriod, new PropertyTag(0x301E, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagArchiveDate, new PropertyTag(0x301F, (ushort)PropertyType.PtypTime));
AddPropertyTagToDic(PropertyNames.PidTagLastModificationTime, new PropertyTag(0x3008, (ushort)PropertyType.PtypTime));
AddPropertyTagToDic(PropertyNames.PidTagCreationTime, new PropertyTag(0x3007, (ushort)PropertyType.PtypTime));
AddPropertyTagToDic(PropertyNames.PidTagDisplayName, new PropertyTag(0x3001, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachSize, new PropertyTag(0x0E20, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAttachNumber, new PropertyTag(0x0E21, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAttachPathname, new PropertyTag(0x3708, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachDataBinary, new PropertyTag(0x3701, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagAttachMethod, new PropertyTag(0x3705, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAttachFilename, new PropertyTag(0x3704, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachLongFilename, new PropertyTag(0x3707, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachExtension, new PropertyTag(0x3703, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachLongPathname, new PropertyTag(0x370D, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachTag, new PropertyTag(0x370A, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagRenderingPosition, new PropertyTag(0X370B, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAttachRendering, new PropertyTag(0x3709, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagAttachFlags, new PropertyTag(0x3714, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAttachTransportName, new PropertyTag(0x370C, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachEncoding, new PropertyTag(0x3702, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagAttachAdditionalInformation, new PropertyTag(0x370F, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagAttachmentLinkId, new PropertyTag(0x7FFA, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAttachmentFlags, new PropertyTag(0x7FFD, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAttachmentHidden, new PropertyTag(0x7FFE, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagAttachMimeTag, new PropertyTag(0x370E, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachContentId, new PropertyTag(0x3712, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachContentLocation, new PropertyTag(0x3713, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachContentBase, new PropertyTag(0x3711, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachDataObject, new PropertyTag(0x3701, (ushort)PropertyType.PtypObject));
AddPropertyTagToDic(PropertyNames.PidTagMessageFlags, new PropertyTag(0x0E07, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagAccessLevel, new PropertyTag(0x0FF7, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagDisplayBcc, new PropertyTag(0x0E02, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagDisplayCc, new PropertyTag(0x0E03, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagDisplayTo, new PropertyTag(0x0E04, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagSecurityDescriptor, new PropertyTag(0x0E27, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagUrlCompNameSet, new PropertyTag(0x0E62, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagTrustSender, new PropertyTag(0x0E79, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagUrlCompName, new PropertyTag(0x10F3, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagSearchKey, new PropertyTag(0x300B, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagAccess, new PropertyTag(0x0FF4, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagCreatorName, new PropertyTag(0x3FF8, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagCreatorEntryId, new PropertyTag(0x3FF9, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagLastModifierName, new PropertyTag(0x3FFA, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagLastModifierEntryId, new PropertyTag(0x3FFB, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagHasNamedProperties, new PropertyTag(0x664A, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagLocaleId, new PropertyTag(0x66A1, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagChangeKey, new PropertyTag(0x65E2, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagObjectType, new PropertyTag(0x0FFE, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagRecordKey, new PropertyTag(0x0FF9, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagLocalCommitTime, new PropertyTag(0x6709, (ushort)PropertyType.PtypTime));
AddPropertyTagToDic(PropertyNames.PidTagAutoForwarded, new PropertyTag(0x0005, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagAddressBookDisplayNamePrintable, new PropertyTag(0x39FF, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagRowid, new PropertyTag(0x3000, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagRecipientOrder, new PropertyTag(0x5FDF, (ushort)PropertyType.PtypInteger32));
AddPropertyTagToDic(PropertyNames.PidTagSubject, new PropertyTag(0x0037, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagInternetReferences, new PropertyTag(0x1039, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagMimeSkeleton, new PropertyTag(0x64F0, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagTnefCorrelationKey, new PropertyTag(0x007F, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagAlternateRecipientAllowed, new PropertyTag(0x0002, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagResponsibility, new PropertyTag(0x0E0F, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagPurportedSenderDomain, new PropertyTag(0x4083, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagStoreEntryId, new PropertyTag(0x0FFB, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagMessageRecipients, new PropertyTag(0x0E12, (ushort)PropertyType.PtypObject));
AddPropertyTagToDic(PropertyNames.PidTagBodyContentId, new PropertyTag(0x1015, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagBodyContentLocation, new PropertyTag(0x1014, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagHtml, new PropertyTag(0x1013, (ushort)PropertyType.PtypBinary));
AddPropertyTagToDic(PropertyNames.PidTagTextAttachmentCharset, new PropertyTag(0x371B, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachPayloadClass, new PropertyTag(0x371A, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagAttachPayloadProviderGuidString, new PropertyTag(0x3719, (ushort)PropertyType.PtypString));
AddPropertyTagToDic(PropertyNames.PidTagRead, new PropertyTag(0x0E69, (ushort)PropertyType.PtypBoolean));
AddPropertyTagToDic(PropertyNames.PidTagRecipientDisplayName, new PropertyTag(0x5FF6, (ushort)PropertyType.PtypString));
}
/// <summary>
/// Find a property name from dictionary by property ID.
/// </summary>
/// <param name="propertyID">A unsigned integer value</param>
/// <param name="propertyType">Property type code</param>
/// <returns>Return Property Name value</returns>
public static PropertyNames GetPropertyNameByID(uint propertyID, uint propertyType)
{
if (PropertyTagDic == null)
{
InitializePropertyTagDic();
}
PropertyNames keyTarget = PropertyNames.UserSpecified;
foreach (PropertyNames propertyName in PropertyTagDic.Keys)
{
if ((uint)PropertyTagDic[propertyName].PropertyId == propertyID && (uint)PropertyTagDic[propertyName].PropertyType == propertyType)
{
keyTarget = propertyName;
break;
}
}
return keyTarget;
}
/// <summary>
/// Override GetPropertyObjFromBuffer with PropertyTag list type.
/// </summary>
/// <param name="propertyTags">List of PropertyTag</param>
/// <param name="response">RopGetPropertiesSpecificResponse packet</param>
/// <returns>List of PropertyObj</returns>
public static List<PropertyObj> GetPropertyObjFromBuffer(PropertyTag[] propertyTags, RopGetPropertiesSpecificResponse response)
{
List<PropertyObj> propertyList = new List<PropertyObj>();
for (int i = 0; i < propertyTags.Length; i++)
{
PropertyNames propertyName = GetPropertyNameByID(propertyTags[i].PropertyId, propertyTags[i].PropertyType);
propertyList.Add(GetPropertyObjFromBuffer(new PropertyObj(propertyName), response.RowData.PropertyValues[i].Value));
}
return propertyList;
}
/// <summary>
/// Override GetPropertyObjFromBuffer without PropertyTag list type. Instead of that the properties will be collected from response.
/// </summary>
/// <param name="response">RopGetPropertiesAllResponse packet</param>
/// <returns>List of PropertyObj</returns>
public static List<PropertyObj> GetPropertyObjFromBuffer(RopGetPropertiesAllResponse response)
{
List<PropertyObj> propertyList = new List<PropertyObj>();
foreach (TaggedPropertyValue taggedPropertyValue in response.PropertyValues)
{
if (GetPropertyNameByID(taggedPropertyValue.PropertyTag.PropertyId, taggedPropertyValue.PropertyTag.PropertyType) == PropertyNames.UserSpecified)
{
continue;
}
PropertyObj property = new PropertyObj(taggedPropertyValue.PropertyTag.PropertyId, taggedPropertyValue.PropertyTag.PropertyType);
propertyList.Add(GetPropertyObjFromBuffer(property, taggedPropertyValue.Value));
}
return propertyList;
}
/// <summary>
/// The extended method for List of PropertyObj to find the exact one by property name.
/// </summary>
/// <param name="propertyList">List of PropertyObj</param>
/// <param name="propertyName">A property name value</param>
/// <returns>Return propertyObj</returns>
public static PropertyObj GetPropertyByName(List<PropertyObj> propertyList, PropertyNames propertyName)
{
PropertyObj property = null;
foreach (PropertyObj pt in propertyList)
{
if (pt.PropertyName == propertyName)
{
property = pt;
break;
}
}
return property;
}
/// <summary>
/// Determine whether the property value is valid.
/// </summary>
/// <param name="property">The input PropertyObj.</param>
/// <returns>Returns Boolean value that indicate whether property value is valid.</returns>
public static bool IsPropertyValid(PropertyObj property)
{
if (property == null)
{
return false;
}
return !IsErrorCode(property.Value);
}
/// <summary>
/// Returns a byte array which append the length of the Input as the first two bytes of input Byte array.
/// </summary>
/// <param name="bytes">The input Byte array</param>
/// <returns>The Byte array corresponding to the Input</returns>
public static byte[] GetBinaryFromGeneral(byte[] bytes)
{
List<byte> lstBytes = new List<byte>();
byte[] bytesSize = BitConverter.GetBytes(bytes.Length);
lstBytes.Add(bytesSize[0]);
lstBytes.Add(bytesSize[1]);
lstBytes.AddRange(bytes);
return lstBytes.ToArray();
}
/// <summary>
/// Get a property's value from bytes.
/// </summary>
/// <param name="property">Send the property</param>
/// <param name="bytes">The response buffer binary bytes</param>
/// <returns>Return PropertyObj</returns>
public static PropertyObj GetPropertyObjFromBuffer(PropertyObj property, byte[] bytes)
{
if (IsErrorCode(bytes))
{
property.Value = bytes;
return property;
}
switch (property.ValueType)
{
case PropertyType.PtypInteger32:
property.Value = BitConverter.ToInt32(bytes, 0);
break;
case PropertyType.PtypString:
string strResult = string.Empty;
foreach (byte b in bytes)
{
if (b == 0x00)
{
continue;
}
strResult += (char)b;
}
property.Value = strResult;
break;
case PropertyType.PtypBoolean:
site.Assert.AreEqual<int>(1, bytes.Length, "PtypBoolean should be 1 byte");
site.Assert.IsTrue(bytes[0] == 0x00 || bytes[0] == 0x01, "PtypBoolean should be restricted to 1 or 0.");
property.Value = BitConverter.ToBoolean(bytes, 0);
break;
case PropertyType.PtypMultipleString:
List<byte> lstBytes = new List<byte>();
List<string> lstStrs = new List<string>();
for (int i = 2; i < bytes.Length; i += 2)
{
if (bytes[i] == 0x00)
{
// Find the 0x0000 end flag to convert each string.
string strSingleResult = string.Empty;
foreach (byte b in lstBytes)
{
strSingleResult += (char)b;
}
lstStrs.Add(strSingleResult);
lstBytes.Clear();
}
else
{
lstBytes.Add(bytes[i]);
}
}
property.Value = lstStrs.ToArray();
break;
case PropertyType.PtypTime:
property.Value = DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, 0));
break;
case PropertyType.PtypBinary:
case PropertyType.PtypObject:
property.Value = bytes;
break;
default:
break;
}
return property;
}
/// <summary>
/// Add a PropertyTag object to PropertyTag dictionary.
/// </summary>
/// <param name="propertyName">The name of property.</param>
/// <param name="propertyTag">The PropertyTag object.</param>
private static void AddPropertyTagToDic(PropertyNames propertyName, PropertyTag propertyTag)
{
if (PropertyTagDic.ContainsKey(propertyName) == false)
{
PropertyTagDic.Add(propertyName, propertyTag);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// A matrix of type uint with 2 columns and 3 rows.
/// </summary>
[Serializable]
[StructLayout(LayoutKind.Sequential)]
public struct umat2x3 : IEnumerable<uint>, IEquatable<umat2x3>
{
#region Fields
/// <summary>
/// Column 0, Rows 0
/// </summary>
public uint m00;
/// <summary>
/// Column 0, Rows 1
/// </summary>
public uint m01;
/// <summary>
/// Column 0, Rows 2
/// </summary>
public uint m02;
/// <summary>
/// Column 1, Rows 0
/// </summary>
public uint m10;
/// <summary>
/// Column 1, Rows 1
/// </summary>
public uint m11;
/// <summary>
/// Column 1, Rows 2
/// </summary>
public uint m12;
#endregion
#region Constructors
/// <summary>
/// Component-wise constructor
/// </summary>
public umat2x3(uint m00, uint m01, uint m02, uint m10, uint m11, uint m12)
{
this.m00 = m00;
this.m01 = m01;
this.m02 = m02;
this.m10 = m10;
this.m11 = m11;
this.m12 = m12;
}
/// <summary>
/// Constructs this matrix from a umat2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0u;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0u;
}
/// <summary>
/// Constructs this matrix from a umat3x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat3x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0u;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0u;
}
/// <summary>
/// Constructs this matrix from a umat4x2. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat4x2 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = 0u;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = 0u;
}
/// <summary>
/// Constructs this matrix from a umat2x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat2x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a umat3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a umat4x3. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat4x3 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a umat2x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat2x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a umat3x4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat3x4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a umat4. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(umat4 m)
{
this.m00 = m.m00;
this.m01 = m.m01;
this.m02 = m.m02;
this.m10 = m.m10;
this.m11 = m.m11;
this.m12 = m.m12;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(uvec2 c0, uvec2 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = 0u;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = 0u;
}
/// <summary>
/// Constructs this matrix from a series of column vectors. Non-overwritten fields are from an Identity matrix.
/// </summary>
public umat2x3(uvec3 c0, uvec3 c1)
{
this.m00 = c0.x;
this.m01 = c0.y;
this.m02 = c0.z;
this.m10 = c1.x;
this.m11 = c1.y;
this.m12 = c1.z;
}
#endregion
#region Properties
/// <summary>
/// Creates a 2D array with all values (address: Values[x, y])
/// </summary>
public uint[,] Values => new[,] { { m00, m01, m02 }, { m10, m11, m12 } };
/// <summary>
/// Creates a 1D array with all values (internal order)
/// </summary>
public uint[] Values1D => new[] { m00, m01, m02, m10, m11, m12 };
/// <summary>
/// Gets or sets the column nr 0
/// </summary>
public uvec3 Column0
{
get
{
return new uvec3(m00, m01, m02);
}
set
{
m00 = value.x;
m01 = value.y;
m02 = value.z;
}
}
/// <summary>
/// Gets or sets the column nr 1
/// </summary>
public uvec3 Column1
{
get
{
return new uvec3(m10, m11, m12);
}
set
{
m10 = value.x;
m11 = value.y;
m12 = value.z;
}
}
/// <summary>
/// Gets or sets the row nr 0
/// </summary>
public uvec2 Row0
{
get
{
return new uvec2(m00, m10);
}
set
{
m00 = value.x;
m10 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 1
/// </summary>
public uvec2 Row1
{
get
{
return new uvec2(m01, m11);
}
set
{
m01 = value.x;
m11 = value.y;
}
}
/// <summary>
/// Gets or sets the row nr 2
/// </summary>
public uvec2 Row2
{
get
{
return new uvec2(m02, m12);
}
set
{
m02 = value.x;
m12 = value.y;
}
}
#endregion
#region Static Properties
/// <summary>
/// Predefined all-zero matrix
/// </summary>
public static umat2x3 Zero { get; } = new umat2x3(0u, 0u, 0u, 0u, 0u, 0u);
/// <summary>
/// Predefined all-ones matrix
/// </summary>
public static umat2x3 Ones { get; } = new umat2x3(1u, 1u, 1u, 1u, 1u, 1u);
/// <summary>
/// Predefined identity matrix
/// </summary>
public static umat2x3 Identity { get; } = new umat2x3(1u, 0u, 0u, 0u, 1u, 0u);
/// <summary>
/// Predefined all-MaxValue matrix
/// </summary>
public static umat2x3 AllMaxValue { get; } = new umat2x3(uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue, uint.MaxValue);
/// <summary>
/// Predefined diagonal-MaxValue matrix
/// </summary>
public static umat2x3 DiagonalMaxValue { get; } = new umat2x3(uint.MaxValue, 0u, 0u, 0u, uint.MaxValue, 0u);
/// <summary>
/// Predefined all-MinValue matrix
/// </summary>
public static umat2x3 AllMinValue { get; } = new umat2x3(uint.MinValue, uint.MinValue, uint.MinValue, uint.MinValue, uint.MinValue, uint.MinValue);
/// <summary>
/// Predefined diagonal-MinValue matrix
/// </summary>
public static umat2x3 DiagonalMinValue { get; } = new umat2x3(uint.MinValue, 0u, 0u, 0u, uint.MinValue, 0u);
#endregion
#region Functions
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
public IEnumerator<uint> GetEnumerator()
{
yield return m00;
yield return m01;
yield return m02;
yield return m10;
yield return m11;
yield return m12;
}
/// <summary>
/// Returns an enumerator that iterates through all fields.
/// </summary>
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
#endregion
/// <summary>
/// Returns the number of Fields (2 x 3 = 6).
/// </summary>
public int Count => 6;
/// <summary>
/// Gets/Sets a specific indexed component (a bit slower than direct access).
/// </summary>
public uint this[int fieldIndex]
{
get
{
switch (fieldIndex)
{
case 0: return m00;
case 1: return m01;
case 2: return m02;
case 3: return m10;
case 4: return m11;
case 5: return m12;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
set
{
switch (fieldIndex)
{
case 0: this.m00 = value; break;
case 1: this.m01 = value; break;
case 2: this.m02 = value; break;
case 3: this.m10 = value; break;
case 4: this.m11 = value; break;
case 5: this.m12 = value; break;
default: throw new ArgumentOutOfRangeException("fieldIndex");
}
}
}
/// <summary>
/// Gets/Sets a specific 2D-indexed component (a bit slower than direct access).
/// </summary>
public uint this[int col, int row]
{
get
{
return this[col * 3 + row];
}
set
{
this[col * 3 + row] = value;
}
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public bool Equals(umat2x3 rhs) => (((m00.Equals(rhs.m00) && m01.Equals(rhs.m01)) && m02.Equals(rhs.m02)) && ((m10.Equals(rhs.m10) && m11.Equals(rhs.m11)) && m12.Equals(rhs.m12)));
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is umat2x3 && Equals((umat2x3) obj);
}
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool operator ==(umat2x3 lhs, umat2x3 rhs) => lhs.Equals(rhs);
/// <summary>
/// Returns true iff this does not equal rhs (component-wise).
/// </summary>
public static bool operator !=(umat2x3 lhs, umat2x3 rhs) => !lhs.Equals(rhs);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public override int GetHashCode()
{
unchecked
{
return ((((((((((m00.GetHashCode()) * 397) ^ m01.GetHashCode()) * 397) ^ m02.GetHashCode()) * 397) ^ m10.GetHashCode()) * 397) ^ m11.GetHashCode()) * 397) ^ m12.GetHashCode();
}
}
/// <summary>
/// Returns a transposed version of this matrix.
/// </summary>
public umat3x2 Transposed => new umat3x2(m00, m10, m01, m11, m02, m12);
/// <summary>
/// Returns the minimal component of this matrix.
/// </summary>
public uint MinElement => Math.Min(Math.Min(Math.Min(Math.Min(Math.Min(m00, m01), m02), m10), m11), m12);
/// <summary>
/// Returns the maximal component of this matrix.
/// </summary>
public uint MaxElement => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m10), m11), m12);
/// <summary>
/// Returns the euclidean length of this matrix.
/// </summary>
public float Length => (float)Math.Sqrt((((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12)));
/// <summary>
/// Returns the squared euclidean length of this matrix.
/// </summary>
public float LengthSqr => (((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12));
/// <summary>
/// Returns the sum of all fields.
/// </summary>
public uint Sum => (((m00 + m01) + m02) + ((m10 + m11) + m12));
/// <summary>
/// Returns the euclidean norm of this matrix.
/// </summary>
public float Norm => (float)Math.Sqrt((((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12)));
/// <summary>
/// Returns the one-norm of this matrix.
/// </summary>
public float Norm1 => (((m00 + m01) + m02) + ((m10 + m11) + m12));
/// <summary>
/// Returns the two-norm of this matrix.
/// </summary>
public float Norm2 => (float)Math.Sqrt((((m00*m00 + m01*m01) + m02*m02) + ((m10*m10 + m11*m11) + m12*m12)));
/// <summary>
/// Returns the max-norm of this matrix.
/// </summary>
public uint NormMax => Math.Max(Math.Max(Math.Max(Math.Max(Math.Max(m00, m01), m02), m10), m11), m12);
/// <summary>
/// Returns the p-norm of this matrix.
/// </summary>
public double NormP(double p) => Math.Pow((((Math.Pow((double)m00, p) + Math.Pow((double)m01, p)) + Math.Pow((double)m02, p)) + ((Math.Pow((double)m10, p) + Math.Pow((double)m11, p)) + Math.Pow((double)m12, p))), 1 / p);
/// <summary>
/// Executes a matrix-matrix-multiplication umat2x3 * umat2 -> umat2x3.
/// </summary>
public static umat2x3 operator*(umat2x3 lhs, umat2 rhs) => new umat2x3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11));
/// <summary>
/// Executes a matrix-matrix-multiplication umat2x3 * umat3x2 -> umat3.
/// </summary>
public static umat3 operator*(umat2x3 lhs, umat3x2 rhs) => new umat3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21));
/// <summary>
/// Executes a matrix-matrix-multiplication umat2x3 * umat4x2 -> umat4x3.
/// </summary>
public static umat4x3 operator*(umat2x3 lhs, umat4x2 rhs) => new umat4x3((lhs.m00 * rhs.m00 + lhs.m10 * rhs.m01), (lhs.m01 * rhs.m00 + lhs.m11 * rhs.m01), (lhs.m02 * rhs.m00 + lhs.m12 * rhs.m01), (lhs.m00 * rhs.m10 + lhs.m10 * rhs.m11), (lhs.m01 * rhs.m10 + lhs.m11 * rhs.m11), (lhs.m02 * rhs.m10 + lhs.m12 * rhs.m11), (lhs.m00 * rhs.m20 + lhs.m10 * rhs.m21), (lhs.m01 * rhs.m20 + lhs.m11 * rhs.m21), (lhs.m02 * rhs.m20 + lhs.m12 * rhs.m21), (lhs.m00 * rhs.m30 + lhs.m10 * rhs.m31), (lhs.m01 * rhs.m30 + lhs.m11 * rhs.m31), (lhs.m02 * rhs.m30 + lhs.m12 * rhs.m31));
/// <summary>
/// Executes a matrix-vector-multiplication.
/// </summary>
public static uvec3 operator*(umat2x3 m, uvec2 v) => new uvec3((m.m00 * v.x + m.m10 * v.y), (m.m01 * v.x + m.m11 * v.y), (m.m02 * v.x + m.m12 * v.y));
/// <summary>
/// Executes a component-wise * (multiply).
/// </summary>
public static umat2x3 CompMul(umat2x3 A, umat2x3 B) => new umat2x3(A.m00 * B.m00, A.m01 * B.m01, A.m02 * B.m02, A.m10 * B.m10, A.m11 * B.m11, A.m12 * B.m12);
/// <summary>
/// Executes a component-wise / (divide).
/// </summary>
public static umat2x3 CompDiv(umat2x3 A, umat2x3 B) => new umat2x3(A.m00 / B.m00, A.m01 / B.m01, A.m02 / B.m02, A.m10 / B.m10, A.m11 / B.m11, A.m12 / B.m12);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static umat2x3 CompAdd(umat2x3 A, umat2x3 B) => new umat2x3(A.m00 + B.m00, A.m01 + B.m01, A.m02 + B.m02, A.m10 + B.m10, A.m11 + B.m11, A.m12 + B.m12);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static umat2x3 CompSub(umat2x3 A, umat2x3 B) => new umat2x3(A.m00 - B.m00, A.m01 - B.m01, A.m02 - B.m02, A.m10 - B.m10, A.m11 - B.m11, A.m12 - B.m12);
/// <summary>
/// Executes a component-wise + (add).
/// </summary>
public static umat2x3 operator+(umat2x3 lhs, umat2x3 rhs) => new umat2x3(lhs.m00 + rhs.m00, lhs.m01 + rhs.m01, lhs.m02 + rhs.m02, lhs.m10 + rhs.m10, lhs.m11 + rhs.m11, lhs.m12 + rhs.m12);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static umat2x3 operator+(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 + rhs, lhs.m01 + rhs, lhs.m02 + rhs, lhs.m10 + rhs, lhs.m11 + rhs, lhs.m12 + rhs);
/// <summary>
/// Executes a component-wise + (add) with a scalar.
/// </summary>
public static umat2x3 operator+(uint lhs, umat2x3 rhs) => new umat2x3(lhs + rhs.m00, lhs + rhs.m01, lhs + rhs.m02, lhs + rhs.m10, lhs + rhs.m11, lhs + rhs.m12);
/// <summary>
/// Executes a component-wise - (subtract).
/// </summary>
public static umat2x3 operator-(umat2x3 lhs, umat2x3 rhs) => new umat2x3(lhs.m00 - rhs.m00, lhs.m01 - rhs.m01, lhs.m02 - rhs.m02, lhs.m10 - rhs.m10, lhs.m11 - rhs.m11, lhs.m12 - rhs.m12);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static umat2x3 operator-(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 - rhs, lhs.m01 - rhs, lhs.m02 - rhs, lhs.m10 - rhs, lhs.m11 - rhs, lhs.m12 - rhs);
/// <summary>
/// Executes a component-wise - (subtract) with a scalar.
/// </summary>
public static umat2x3 operator-(uint lhs, umat2x3 rhs) => new umat2x3(lhs - rhs.m00, lhs - rhs.m01, lhs - rhs.m02, lhs - rhs.m10, lhs - rhs.m11, lhs - rhs.m12);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static umat2x3 operator/(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 / rhs, lhs.m01 / rhs, lhs.m02 / rhs, lhs.m10 / rhs, lhs.m11 / rhs, lhs.m12 / rhs);
/// <summary>
/// Executes a component-wise / (divide) with a scalar.
/// </summary>
public static umat2x3 operator/(uint lhs, umat2x3 rhs) => new umat2x3(lhs / rhs.m00, lhs / rhs.m01, lhs / rhs.m02, lhs / rhs.m10, lhs / rhs.m11, lhs / rhs.m12);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static umat2x3 operator*(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 * rhs, lhs.m01 * rhs, lhs.m02 * rhs, lhs.m10 * rhs, lhs.m11 * rhs, lhs.m12 * rhs);
/// <summary>
/// Executes a component-wise * (multiply) with a scalar.
/// </summary>
public static umat2x3 operator*(uint lhs, umat2x3 rhs) => new umat2x3(lhs * rhs.m00, lhs * rhs.m01, lhs * rhs.m02, lhs * rhs.m10, lhs * rhs.m11, lhs * rhs.m12);
/// <summary>
/// Executes a component-wise % (modulo).
/// </summary>
public static umat2x3 operator%(umat2x3 lhs, umat2x3 rhs) => new umat2x3(lhs.m00 % rhs.m00, lhs.m01 % rhs.m01, lhs.m02 % rhs.m02, lhs.m10 % rhs.m10, lhs.m11 % rhs.m11, lhs.m12 % rhs.m12);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static umat2x3 operator%(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 % rhs, lhs.m01 % rhs, lhs.m02 % rhs, lhs.m10 % rhs, lhs.m11 % rhs, lhs.m12 % rhs);
/// <summary>
/// Executes a component-wise % (modulo) with a scalar.
/// </summary>
public static umat2x3 operator%(uint lhs, umat2x3 rhs) => new umat2x3(lhs % rhs.m00, lhs % rhs.m01, lhs % rhs.m02, lhs % rhs.m10, lhs % rhs.m11, lhs % rhs.m12);
/// <summary>
/// Executes a component-wise ^ (xor).
/// </summary>
public static umat2x3 operator^(umat2x3 lhs, umat2x3 rhs) => new umat2x3(lhs.m00 ^ rhs.m00, lhs.m01 ^ rhs.m01, lhs.m02 ^ rhs.m02, lhs.m10 ^ rhs.m10, lhs.m11 ^ rhs.m11, lhs.m12 ^ rhs.m12);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static umat2x3 operator^(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 ^ rhs, lhs.m01 ^ rhs, lhs.m02 ^ rhs, lhs.m10 ^ rhs, lhs.m11 ^ rhs, lhs.m12 ^ rhs);
/// <summary>
/// Executes a component-wise ^ (xor) with a scalar.
/// </summary>
public static umat2x3 operator^(uint lhs, umat2x3 rhs) => new umat2x3(lhs ^ rhs.m00, lhs ^ rhs.m01, lhs ^ rhs.m02, lhs ^ rhs.m10, lhs ^ rhs.m11, lhs ^ rhs.m12);
/// <summary>
/// Executes a component-wise | (bitwise-or).
/// </summary>
public static umat2x3 operator|(umat2x3 lhs, umat2x3 rhs) => new umat2x3(lhs.m00 | rhs.m00, lhs.m01 | rhs.m01, lhs.m02 | rhs.m02, lhs.m10 | rhs.m10, lhs.m11 | rhs.m11, lhs.m12 | rhs.m12);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static umat2x3 operator|(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 | rhs, lhs.m01 | rhs, lhs.m02 | rhs, lhs.m10 | rhs, lhs.m11 | rhs, lhs.m12 | rhs);
/// <summary>
/// Executes a component-wise | (bitwise-or) with a scalar.
/// </summary>
public static umat2x3 operator|(uint lhs, umat2x3 rhs) => new umat2x3(lhs | rhs.m00, lhs | rhs.m01, lhs | rhs.m02, lhs | rhs.m10, lhs | rhs.m11, lhs | rhs.m12);
/// <summary>
/// Executes a component-wise & (bitwise-and).
/// </summary>
public static umat2x3 operator&(umat2x3 lhs, umat2x3 rhs) => new umat2x3(lhs.m00 & rhs.m00, lhs.m01 & rhs.m01, lhs.m02 & rhs.m02, lhs.m10 & rhs.m10, lhs.m11 & rhs.m11, lhs.m12 & rhs.m12);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static umat2x3 operator&(umat2x3 lhs, uint rhs) => new umat2x3(lhs.m00 & rhs, lhs.m01 & rhs, lhs.m02 & rhs, lhs.m10 & rhs, lhs.m11 & rhs, lhs.m12 & rhs);
/// <summary>
/// Executes a component-wise & (bitwise-and) with a scalar.
/// </summary>
public static umat2x3 operator&(uint lhs, umat2x3 rhs) => new umat2x3(lhs & rhs.m00, lhs & rhs.m01, lhs & rhs.m02, lhs & rhs.m10, lhs & rhs.m11, lhs & rhs.m12);
/// <summary>
/// Executes a component-wise left-shift with a scalar.
/// </summary>
public static umat2x3 operator<<(umat2x3 lhs, int rhs) => new umat2x3(lhs.m00 << rhs, lhs.m01 << rhs, lhs.m02 << rhs, lhs.m10 << rhs, lhs.m11 << rhs, lhs.m12 << rhs);
/// <summary>
/// Executes a component-wise right-shift with a scalar.
/// </summary>
public static umat2x3 operator>>(umat2x3 lhs, int rhs) => new umat2x3(lhs.m00 >> rhs, lhs.m01 >> rhs, lhs.m02 >> rhs, lhs.m10 >> rhs, lhs.m11 >> rhs, lhs.m12 >> rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison.
/// </summary>
public static bmat2x3 operator<(umat2x3 lhs, umat2x3 rhs) => new bmat2x3(lhs.m00 < rhs.m00, lhs.m01 < rhs.m01, lhs.m02 < rhs.m02, lhs.m10 < rhs.m10, lhs.m11 < rhs.m11, lhs.m12 < rhs.m12);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator<(umat2x3 lhs, uint rhs) => new bmat2x3(lhs.m00 < rhs, lhs.m01 < rhs, lhs.m02 < rhs, lhs.m10 < rhs, lhs.m11 < rhs, lhs.m12 < rhs);
/// <summary>
/// Executes a component-wise lesser-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator<(uint lhs, umat2x3 rhs) => new bmat2x3(lhs < rhs.m00, lhs < rhs.m01, lhs < rhs.m02, lhs < rhs.m10, lhs < rhs.m11, lhs < rhs.m12);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison.
/// </summary>
public static bmat2x3 operator<=(umat2x3 lhs, umat2x3 rhs) => new bmat2x3(lhs.m00 <= rhs.m00, lhs.m01 <= rhs.m01, lhs.m02 <= rhs.m02, lhs.m10 <= rhs.m10, lhs.m11 <= rhs.m11, lhs.m12 <= rhs.m12);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator<=(umat2x3 lhs, uint rhs) => new bmat2x3(lhs.m00 <= rhs, lhs.m01 <= rhs, lhs.m02 <= rhs, lhs.m10 <= rhs, lhs.m11 <= rhs, lhs.m12 <= rhs);
/// <summary>
/// Executes a component-wise lesser-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator<=(uint lhs, umat2x3 rhs) => new bmat2x3(lhs <= rhs.m00, lhs <= rhs.m01, lhs <= rhs.m02, lhs <= rhs.m10, lhs <= rhs.m11, lhs <= rhs.m12);
/// <summary>
/// Executes a component-wise greater-than comparison.
/// </summary>
public static bmat2x3 operator>(umat2x3 lhs, umat2x3 rhs) => new bmat2x3(lhs.m00 > rhs.m00, lhs.m01 > rhs.m01, lhs.m02 > rhs.m02, lhs.m10 > rhs.m10, lhs.m11 > rhs.m11, lhs.m12 > rhs.m12);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator>(umat2x3 lhs, uint rhs) => new bmat2x3(lhs.m00 > rhs, lhs.m01 > rhs, lhs.m02 > rhs, lhs.m10 > rhs, lhs.m11 > rhs, lhs.m12 > rhs);
/// <summary>
/// Executes a component-wise greater-than comparison with a scalar.
/// </summary>
public static bmat2x3 operator>(uint lhs, umat2x3 rhs) => new bmat2x3(lhs > rhs.m00, lhs > rhs.m01, lhs > rhs.m02, lhs > rhs.m10, lhs > rhs.m11, lhs > rhs.m12);
/// <summary>
/// Executes a component-wise greater-or-equal comparison.
/// </summary>
public static bmat2x3 operator>=(umat2x3 lhs, umat2x3 rhs) => new bmat2x3(lhs.m00 >= rhs.m00, lhs.m01 >= rhs.m01, lhs.m02 >= rhs.m02, lhs.m10 >= rhs.m10, lhs.m11 >= rhs.m11, lhs.m12 >= rhs.m12);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator>=(umat2x3 lhs, uint rhs) => new bmat2x3(lhs.m00 >= rhs, lhs.m01 >= rhs, lhs.m02 >= rhs, lhs.m10 >= rhs, lhs.m11 >= rhs, lhs.m12 >= rhs);
/// <summary>
/// Executes a component-wise greater-or-equal comparison with a scalar.
/// </summary>
public static bmat2x3 operator>=(uint lhs, umat2x3 rhs) => new bmat2x3(lhs >= rhs.m00, lhs >= rhs.m01, lhs >= rhs.m02, lhs >= rhs.m10, lhs >= rhs.m11, lhs >= rhs.m12);
}
}
| |
// Lucene version compatibility level 4.8.1
using Lucene.Net.Analysis.Core;
using Lucene.Net.Analysis.TokenAttributes;
using NUnit.Framework;
using System;
using System.IO;
namespace Lucene.Net.Analysis.Shingle
{
/*
* 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.
*/
public class ShingleFilterTest : BaseTokenStreamTestCase
{
public static readonly Token[] TEST_TOKEN = new Token[] { CreateToken("please", 0, 6), CreateToken("divide", 7, 13), CreateToken("this", 14, 18), CreateToken("sentence", 19, 27), CreateToken("into", 28, 32), CreateToken("shingles", 33, 39) };
public static readonly int[] UNIGRAM_ONLY_POSITION_INCREMENTS = new int[] { 1, 1, 1, 1, 1, 1 };
public static readonly string[] UNIGRAM_ONLY_TYPES = new string[] { "word", "word", "word", "word", "word", "word" };
public static Token[] testTokenWithHoles;
public static readonly Token[] BI_GRAM_TOKENS = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide", 0, 13), CreateToken("divide", 7, 13), CreateToken("divide this", 7, 18), CreateToken("this", 14, 18), CreateToken("this sentence", 14, 27), CreateToken("sentence", 19, 27), CreateToken("sentence into", 19, 32), CreateToken("into", 28, 32), CreateToken("into shingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS = new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] BI_GRAM_TYPES = new string[] { "word", "shingle", "word", "shingle", "word", "shingle", "word", "shingle", "word", "shingle", "word" };
public static readonly Token[] BI_GRAM_TOKENS_WITH_HOLES = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide", 0, 13), CreateToken("divide", 7, 13), CreateToken("divide _", 7, 19), CreateToken("_ sentence", 19, 27), CreateToken("sentence", 19, 27), CreateToken("sentence _", 19, 33), CreateToken("_ shingles", 33, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS_WITH_HOLES = new int[] { 1, 0, 1, 0, 1, 1, 0, 1, 1 };
private static readonly string[] BI_GRAM_TYPES_WITH_HOLES = new string[] { "word", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word" };
public static readonly Token[] BI_GRAM_TOKENS_WITHOUT_UNIGRAMS = new Token[] { CreateToken("please divide", 0, 13), CreateToken("divide this", 7, 18), CreateToken("this sentence", 14, 27), CreateToken("sentence into", 19, 32), CreateToken("into shingles", 28, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS = new int[] { 1, 1, 1, 1, 1 };
public static readonly string[] BI_GRAM_TYPES_WITHOUT_UNIGRAMS = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] BI_GRAM_TOKENS_WITH_HOLES_WITHOUT_UNIGRAMS = new Token[] { CreateToken("please divide", 0, 13), CreateToken("divide _", 7, 19), CreateToken("_ sentence", 19, 27), CreateToken("sentence _", 19, 33), CreateToken("_ shingles", 33, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS_WITH_HOLES_WITHOUT_UNIGRAMS = new int[] { 1, 1, 1, 1, 1, 1 };
public static readonly Token[] TEST_SINGLE_TOKEN = new Token[] { CreateToken("please", 0, 6) };
public static readonly Token[] SINGLE_TOKEN = new Token[] { CreateToken("please", 0, 6) };
public static readonly int[] SINGLE_TOKEN_INCREMENTS = new int[] { 1 };
public static readonly string[] SINGLE_TOKEN_TYPES = new string[] { "word" };
public static readonly Token[] EMPTY_TOKEN_ARRAY = new Token[] { };
public static readonly int[] EMPTY_TOKEN_INCREMENTS_ARRAY = new int[] { };
public static readonly string[] EMPTY_TOKEN_TYPES_ARRAY = new string[] { };
public static readonly Token[] TRI_GRAM_TOKENS = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide", 0, 13), CreateToken("please divide this", 0, 18), CreateToken("divide", 7, 13), CreateToken("divide this", 7, 18), CreateToken("divide this sentence", 7, 27), CreateToken("this", 14, 18), CreateToken("this sentence", 14, 27), CreateToken("this sentence into", 14, 32), CreateToken("sentence", 19, 27), CreateToken("sentence into", 19, 32), CreateToken("sentence into shingles", 19, 39), CreateToken("into", 28, 32), CreateToken("into shingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS = new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES = new string[] { "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word" };
public static readonly Token[] TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS = new Token[] { CreateToken("please divide", 0, 13), CreateToken("please divide this", 0, 18), CreateToken("divide this", 7, 18), CreateToken("divide this sentence", 7, 27), CreateToken("this sentence", 14, 27), CreateToken("this sentence into", 14, 32), CreateToken("sentence into", 19, 32), CreateToken("sentence into shingles", 19, 39), CreateToken("into shingles", 28, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS = new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_WITHOUT_UNIGRAMS = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] FOUR_GRAM_TOKENS = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide", 0, 13), CreateToken("please divide this", 0, 18), CreateToken("please divide this sentence", 0, 27), CreateToken("divide", 7, 13), CreateToken("divide this", 7, 18), CreateToken("divide this sentence", 7, 27), CreateToken("divide this sentence into", 7, 32), CreateToken("this", 14, 18), CreateToken("this sentence", 14, 27), CreateToken("this sentence into", 14, 32), CreateToken("this sentence into shingles", 14, 39), CreateToken("sentence", 19, 27), CreateToken("sentence into", 19, 32), CreateToken("sentence into shingles", 19, 39), CreateToken("into", 28, 32), CreateToken("into shingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] FOUR_GRAM_POSITION_INCREMENTS = new int[] { 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] FOUR_GRAM_TYPES = new string[] { "word", "shingle", "shingle", "shingle", "word", "shingle", "shingle", "shingle", "word", "shingle", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word" };
public static readonly Token[] FOUR_GRAM_TOKENS_WITHOUT_UNIGRAMS = new Token[] { CreateToken("please divide", 0, 13), CreateToken("please divide this", 0, 18), CreateToken("please divide this sentence", 0, 27), CreateToken("divide this", 7, 18), CreateToken("divide this sentence", 7, 27), CreateToken("divide this sentence into", 7, 32), CreateToken("this sentence", 14, 27), CreateToken("this sentence into", 14, 32), CreateToken("this sentence into shingles", 14, 39), CreateToken("sentence into", 19, 32), CreateToken("sentence into shingles", 19, 39), CreateToken("into shingles", 28, 39) };
public static readonly int[] FOUR_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS = new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] FOUR_GRAM_TYPES_WITHOUT_UNIGRAMS = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] TRI_GRAM_TOKENS_MIN_TRI_GRAM = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide this", 0, 18), CreateToken("divide", 7, 13), CreateToken("divide this sentence", 7, 27), CreateToken("this", 14, 18), CreateToken("this sentence into", 14, 32), CreateToken("sentence", 19, 27), CreateToken("sentence into shingles", 19, 39), CreateToken("into", 28, 32), CreateToken("shingles", 33, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_MIN_TRI_GRAM = new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1, 1 };
public static readonly string[] TRI_GRAM_TYPES_MIN_TRI_GRAM = new string[] { "word", "shingle", "word", "shingle", "word", "shingle", "word", "shingle", "word", "word" };
public static readonly Token[] TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM = new Token[] { CreateToken("please divide this", 0, 18), CreateToken("divide this sentence", 7, 27), CreateToken("this sentence into", 14, 32), CreateToken("sentence into shingles", 19, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM = new int[] { 1, 1, 1, 1 };
public static readonly string[] TRI_GRAM_TYPES_WITHOUT_UNIGRAMS_MIN_TRI_GRAM = new string[] { "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] FOUR_GRAM_TOKENS_MIN_TRI_GRAM = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide this", 0, 18), CreateToken("please divide this sentence", 0, 27), CreateToken("divide", 7, 13), CreateToken("divide this sentence", 7, 27), CreateToken("divide this sentence into", 7, 32), CreateToken("this", 14, 18), CreateToken("this sentence into", 14, 32), CreateToken("this sentence into shingles", 14, 39), CreateToken("sentence", 19, 27), CreateToken("sentence into shingles", 19, 39), CreateToken("into", 28, 32), CreateToken("shingles", 33, 39) };
public static readonly int[] FOUR_GRAM_POSITION_INCREMENTS_MIN_TRI_GRAM = new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1 };
public static readonly string[] FOUR_GRAM_TYPES_MIN_TRI_GRAM = new string[] { "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word", "word" };
public static readonly Token[] FOUR_GRAM_TOKENS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM = new Token[] { CreateToken("please divide this", 0, 18), CreateToken("please divide this sentence", 0, 27), CreateToken("divide this sentence", 7, 27), CreateToken("divide this sentence into", 7, 32), CreateToken("this sentence into", 14, 32), CreateToken("this sentence into shingles", 14, 39), CreateToken("sentence into shingles", 19, 39) };
public static readonly int[] FOUR_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM = new int[] { 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] FOUR_GRAM_TYPES_WITHOUT_UNIGRAMS_MIN_TRI_GRAM = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] FOUR_GRAM_TOKENS_MIN_FOUR_GRAM = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide this sentence", 0, 27), CreateToken("divide", 7, 13), CreateToken("divide this sentence into", 7, 32), CreateToken("this", 14, 18), CreateToken("this sentence into shingles", 14, 39), CreateToken("sentence", 19, 27), CreateToken("into", 28, 32), CreateToken("shingles", 33, 39) };
public static readonly int[] FOUR_GRAM_POSITION_INCREMENTS_MIN_FOUR_GRAM = new int[] { 1, 0, 1, 0, 1, 0, 1, 1, 1 };
public static readonly string[] FOUR_GRAM_TYPES_MIN_FOUR_GRAM = new string[] { "word", "shingle", "word", "shingle", "word", "shingle", "word", "word", "word" };
public static readonly Token[] FOUR_GRAM_TOKENS_WITHOUT_UNIGRAMS_MIN_FOUR_GRAM = new Token[] { CreateToken("please divide this sentence", 0, 27), CreateToken("divide this sentence into", 7, 32), CreateToken("this sentence into shingles", 14, 39) };
public static readonly int[] FOUR_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_MIN_FOUR_GRAM = new int[] { 1, 1, 1 };
public static readonly string[] FOUR_GRAM_TYPES_WITHOUT_UNIGRAMS_MIN_FOUR_GRAM = new string[] { "shingle", "shingle", "shingle" };
public static readonly Token[] BI_GRAM_TOKENS_NO_SEPARATOR = new Token[] { CreateToken("please", 0, 6), CreateToken("pleasedivide", 0, 13), CreateToken("divide", 7, 13), CreateToken("dividethis", 7, 18), CreateToken("this", 14, 18), CreateToken("thissentence", 14, 27), CreateToken("sentence", 19, 27), CreateToken("sentenceinto", 19, 32), CreateToken("into", 28, 32), CreateToken("intoshingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS_NO_SEPARATOR = new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] BI_GRAM_TYPES_NO_SEPARATOR = new string[] { "word", "shingle", "word", "shingle", "word", "shingle", "word", "shingle", "word", "shingle", "word" };
public static readonly Token[] BI_GRAM_TOKENS_WITHOUT_UNIGRAMS_NO_SEPARATOR = new Token[] { CreateToken("pleasedivide", 0, 13), CreateToken("dividethis", 7, 18), CreateToken("thissentence", 14, 27), CreateToken("sentenceinto", 19, 32), CreateToken("intoshingles", 28, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_NO_SEPARATOR = new int[] { 1, 1, 1, 1, 1 };
public static readonly string[] BI_GRAM_TYPES_WITHOUT_UNIGRAMS_NO_SEPARATOR = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] TRI_GRAM_TOKENS_NO_SEPARATOR = new Token[] { CreateToken("please", 0, 6), CreateToken("pleasedivide", 0, 13), CreateToken("pleasedividethis", 0, 18), CreateToken("divide", 7, 13), CreateToken("dividethis", 7, 18), CreateToken("dividethissentence", 7, 27), CreateToken("this", 14, 18), CreateToken("thissentence", 14, 27), CreateToken("thissentenceinto", 14, 32), CreateToken("sentence", 19, 27), CreateToken("sentenceinto", 19, 32), CreateToken("sentenceintoshingles", 19, 39), CreateToken("into", 28, 32), CreateToken("intoshingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_NO_SEPARATOR = new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_NO_SEPARATOR = new string[] { "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word" };
public static readonly Token[] TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS_NO_SEPARATOR = new Token[] { CreateToken("pleasedivide", 0, 13), CreateToken("pleasedividethis", 0, 18), CreateToken("dividethis", 7, 18), CreateToken("dividethissentence", 7, 27), CreateToken("thissentence", 14, 27), CreateToken("thissentenceinto", 14, 32), CreateToken("sentenceinto", 19, 32), CreateToken("sentenceintoshingles", 19, 39), CreateToken("intoshingles", 28, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_NO_SEPARATOR = new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_WITHOUT_UNIGRAMS_NO_SEPARATOR = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] BI_GRAM_TOKENS_ALT_SEPARATOR = new Token[] { CreateToken("please", 0, 6), CreateToken("please<SEP>divide", 0, 13), CreateToken("divide", 7, 13), CreateToken("divide<SEP>this", 7, 18), CreateToken("this", 14, 18), CreateToken("this<SEP>sentence", 14, 27), CreateToken("sentence", 19, 27), CreateToken("sentence<SEP>into", 19, 32), CreateToken("into", 28, 32), CreateToken("into<SEP>shingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS_ALT_SEPARATOR = new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] BI_GRAM_TYPES_ALT_SEPARATOR = new string[] { "word", "shingle", "word", "shingle", "word", "shingle", "word", "shingle", "word", "shingle", "word" };
public static readonly Token[] BI_GRAM_TOKENS_WITHOUT_UNIGRAMS_ALT_SEPARATOR = new Token[] { CreateToken("please<SEP>divide", 0, 13), CreateToken("divide<SEP>this", 7, 18), CreateToken("this<SEP>sentence", 14, 27), CreateToken("sentence<SEP>into", 19, 32), CreateToken("into<SEP>shingles", 28, 39) };
public static readonly int[] BI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_ALT_SEPARATOR = new int[] { 1, 1, 1, 1, 1 };
public static readonly string[] BI_GRAM_TYPES_WITHOUT_UNIGRAMS_ALT_SEPARATOR = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] TRI_GRAM_TOKENS_ALT_SEPARATOR = new Token[] { CreateToken("please", 0, 6), CreateToken("please<SEP>divide", 0, 13), CreateToken("please<SEP>divide<SEP>this", 0, 18), CreateToken("divide", 7, 13), CreateToken("divide<SEP>this", 7, 18), CreateToken("divide<SEP>this<SEP>sentence", 7, 27), CreateToken("this", 14, 18), CreateToken("this<SEP>sentence", 14, 27), CreateToken("this<SEP>sentence<SEP>into", 14, 32), CreateToken("sentence", 19, 27), CreateToken("sentence<SEP>into", 19, 32), CreateToken("sentence<SEP>into<SEP>shingles", 19, 39), CreateToken("into", 28, 32), CreateToken("into<SEP>shingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_ALT_SEPARATOR = new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_ALT_SEPARATOR = new string[] { "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word" };
public static readonly Token[] TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS_ALT_SEPARATOR = new Token[] { CreateToken("please<SEP>divide", 0, 13), CreateToken("please<SEP>divide<SEP>this", 0, 18), CreateToken("divide<SEP>this", 7, 18), CreateToken("divide<SEP>this<SEP>sentence", 7, 27), CreateToken("this<SEP>sentence", 14, 27), CreateToken("this<SEP>sentence<SEP>into", 14, 32), CreateToken("sentence<SEP>into", 19, 32), CreateToken("sentence<SEP>into<SEP>shingles", 19, 39), CreateToken("into<SEP>shingles", 28, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_ALT_SEPARATOR = new int[] { 1, 0, 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_WITHOUT_UNIGRAMS_ALT_SEPARATOR = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] TRI_GRAM_TOKENS_NULL_SEPARATOR = new Token[] { CreateToken("please", 0, 6), CreateToken("pleasedivide", 0, 13), CreateToken("pleasedividethis", 0, 18), CreateToken("divide", 7, 13), CreateToken("dividethis", 7, 18), CreateToken("dividethissentence", 7, 27), CreateToken("this", 14, 18), CreateToken("thissentence", 14, 27), CreateToken("thissentenceinto", 14, 32), CreateToken("sentence", 19, 27), CreateToken("sentenceinto", 19, 32), CreateToken("sentenceintoshingles", 19, 39), CreateToken("into", 28, 32), CreateToken("intoshingles", 28, 39), CreateToken("shingles", 33, 39) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_NULL_SEPARATOR = new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_NULL_SEPARATOR = new string[] { "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word" };
public static readonly Token[] TEST_TOKEN_POS_INCR_EQUAL_TO_N = new Token[] { CreateToken("please", 0, 6), CreateToken("divide", 7, 13), CreateToken("this", 14, 18), CreateToken("sentence", 29, 37, 3), CreateToken("into", 38, 42), CreateToken("shingles", 43, 49) };
public static readonly Token[] TRI_GRAM_TOKENS_POS_INCR_EQUAL_TO_N = new Token[] { CreateToken("please", 0, 6), CreateToken("please divide", 0, 13), CreateToken("please divide this", 0, 18), CreateToken("divide", 7, 13), CreateToken("divide this", 7, 18), CreateToken("divide this _", 7, 29), CreateToken("this", 14, 18), CreateToken("this _", 14, 29), CreateToken("this _ _", 14, 29), CreateToken("_ _ sentence", 29, 37), CreateToken("_ sentence", 29, 37), CreateToken("_ sentence into", 29, 42), CreateToken("sentence", 29, 37), CreateToken("sentence into", 29, 42), CreateToken("sentence into shingles", 29, 49), CreateToken("into", 38, 42), CreateToken("into shingles", 38, 49), CreateToken("shingles", 43, 49) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_POS_INCR_EQUAL_TO_N = new int[] { 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_POS_INCR_EQUAL_TO_N = new string[] { "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "shingle", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word" };
public static readonly Token[] TRI_GRAM_TOKENS_POS_INCR_EQUAL_TO_N_WITHOUT_UNIGRAMS = new Token[] { CreateToken("please divide", 0, 13), CreateToken("please divide this", 0, 18), CreateToken("divide this", 7, 18), CreateToken("divide this _", 7, 29), CreateToken("this _", 14, 29), CreateToken("this _ _", 14, 29), CreateToken("_ _ sentence", 29, 37), CreateToken("_ sentence", 29, 37), CreateToken("_ sentence into", 29, 42), CreateToken("sentence into", 29, 42), CreateToken("sentence into shingles", 29, 49), CreateToken("into shingles", 38, 49) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_POS_INCR_EQUAL_TO_N_WITHOUT_UNIGRAMS = new int[] { 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1 };
public static readonly string[] TRI_GRAM_TYPES_POS_INCR_EQUAL_TO_N_WITHOUT_UNIGRAMS = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle" };
public static readonly Token[] TEST_TOKEN_POS_INCR_GREATER_THAN_N = new Token[] { CreateToken("please", 0, 6), CreateToken("divide", 57, 63, 8), CreateToken("this", 64, 68), CreateToken("sentence", 69, 77), CreateToken("into", 78, 82), CreateToken("shingles", 83, 89) };
public static readonly Token[] TRI_GRAM_TOKENS_POS_INCR_GREATER_THAN_N = new Token[] { CreateToken("please", 0, 6), CreateToken("please _", 0, 57), CreateToken("please _ _", 0, 57), CreateToken("_ _ divide", 57, 63), CreateToken("_ divide", 57, 63), CreateToken("_ divide this", 57, 68), CreateToken("divide", 57, 63), CreateToken("divide this", 57, 68), CreateToken("divide this sentence", 57, 77), CreateToken("this", 64, 68), CreateToken("this sentence", 64, 77), CreateToken("this sentence into", 64, 82), CreateToken("sentence", 69, 77), CreateToken("sentence into", 69, 82), CreateToken("sentence into shingles", 69, 89), CreateToken("into", 78, 82), CreateToken("into shingles", 78, 89), CreateToken("shingles", 83, 89) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_POS_INCR_GREATER_THAN_N = new int[] { 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_POS_INCR_GREATER_THAN_N = new string[] { "word", "shingle", "shingle", "shingle", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "shingle", "word", "shingle", "word" };
public static readonly Token[] TRI_GRAM_TOKENS_POS_INCR_GREATER_THAN_N_WITHOUT_UNIGRAMS = new Token[] { CreateToken("please _", 0, 57), CreateToken("please _ _", 0, 57), CreateToken("_ _ divide", 57, 63), CreateToken("_ divide", 57, 63), CreateToken("_ divide this", 57, 68), CreateToken("divide this", 57, 68), CreateToken("divide this sentence", 57, 77), CreateToken("this sentence", 64, 77), CreateToken("this sentence into", 64, 82), CreateToken("sentence into", 69, 82), CreateToken("sentence into shingles", 69, 89), CreateToken("into shingles", 78, 89) };
public static readonly int[] TRI_GRAM_POSITION_INCREMENTS_POS_INCR_GREATER_THAN_N_WITHOUT_UNIGRAMS = new int[] { 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1 };
public static readonly string[] TRI_GRAM_TYPES_POS_INCR_GREATER_THAN_N_WITHOUT_UNIGRAMS = new string[] { "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle", "shingle" };
public override void SetUp()
{
base.SetUp();
testTokenWithHoles = new Token[] { CreateToken("please", 0, 6), CreateToken("divide", 7, 13), CreateToken("sentence", 19, 27, 2), CreateToken("shingles", 33, 39, 2) };
}
/*
* Class under test for void ShingleFilter(TokenStream, int)
*/
[Test]
public virtual void TestBiGramFilter()
{
this.shingleFilterTest(2, TEST_TOKEN, BI_GRAM_TOKENS, BI_GRAM_POSITION_INCREMENTS, BI_GRAM_TYPES, true);
}
[Test]
public virtual void TestBiGramFilterWithHoles()
{
this.shingleFilterTest(2, testTokenWithHoles, BI_GRAM_TOKENS_WITH_HOLES, BI_GRAM_POSITION_INCREMENTS_WITH_HOLES, BI_GRAM_TYPES_WITH_HOLES, true);
}
[Test]
public virtual void TestBiGramFilterWithoutUnigrams()
{
this.shingleFilterTest(2, TEST_TOKEN, BI_GRAM_TOKENS_WITHOUT_UNIGRAMS, BI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS, BI_GRAM_TYPES_WITHOUT_UNIGRAMS, false);
}
[Test]
public virtual void TestBiGramFilterWithHolesWithoutUnigrams()
{
this.shingleFilterTest(2, testTokenWithHoles, BI_GRAM_TOKENS_WITH_HOLES_WITHOUT_UNIGRAMS, BI_GRAM_POSITION_INCREMENTS_WITH_HOLES_WITHOUT_UNIGRAMS, BI_GRAM_TYPES_WITHOUT_UNIGRAMS, false);
}
[Test]
public virtual void TestBiGramFilterWithSingleToken()
{
this.shingleFilterTest(2, TEST_SINGLE_TOKEN, SINGLE_TOKEN, SINGLE_TOKEN_INCREMENTS, SINGLE_TOKEN_TYPES, true);
}
[Test]
public virtual void TestBiGramFilterWithSingleTokenWithoutUnigrams()
{
this.shingleFilterTest(2, TEST_SINGLE_TOKEN, EMPTY_TOKEN_ARRAY, EMPTY_TOKEN_INCREMENTS_ARRAY, EMPTY_TOKEN_TYPES_ARRAY, false);
}
[Test]
public virtual void TestBiGramFilterWithEmptyTokenStream()
{
this.shingleFilterTest(2, EMPTY_TOKEN_ARRAY, EMPTY_TOKEN_ARRAY, EMPTY_TOKEN_INCREMENTS_ARRAY, EMPTY_TOKEN_TYPES_ARRAY, true);
}
[Test]
public virtual void TestBiGramFilterWithEmptyTokenStreamWithoutUnigrams()
{
this.shingleFilterTest(2, EMPTY_TOKEN_ARRAY, EMPTY_TOKEN_ARRAY, EMPTY_TOKEN_INCREMENTS_ARRAY, EMPTY_TOKEN_TYPES_ARRAY, false);
}
[Test]
public virtual void TestTriGramFilter()
{
this.shingleFilterTest(3, TEST_TOKEN, TRI_GRAM_TOKENS, TRI_GRAM_POSITION_INCREMENTS, TRI_GRAM_TYPES, true);
}
[Test]
public virtual void TestTriGramFilterWithoutUnigrams()
{
this.shingleFilterTest(3, TEST_TOKEN, TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS, TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS, TRI_GRAM_TYPES_WITHOUT_UNIGRAMS, false);
}
[Test]
public virtual void TestFourGramFilter()
{
this.shingleFilterTest(4, TEST_TOKEN, FOUR_GRAM_TOKENS, FOUR_GRAM_POSITION_INCREMENTS, FOUR_GRAM_TYPES, true);
}
[Test]
public virtual void TestFourGramFilterWithoutUnigrams()
{
this.shingleFilterTest(4, TEST_TOKEN, FOUR_GRAM_TOKENS_WITHOUT_UNIGRAMS, FOUR_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS, FOUR_GRAM_TYPES_WITHOUT_UNIGRAMS, false);
}
[Test]
public virtual void TestTriGramFilterMinTriGram()
{
this.shingleFilterTest(3, 3, TEST_TOKEN, TRI_GRAM_TOKENS_MIN_TRI_GRAM, TRI_GRAM_POSITION_INCREMENTS_MIN_TRI_GRAM, TRI_GRAM_TYPES_MIN_TRI_GRAM, true);
}
[Test]
public virtual void TestTriGramFilterWithoutUnigramsMinTriGram()
{
this.shingleFilterTest(3, 3, TEST_TOKEN, TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM, TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM, TRI_GRAM_TYPES_WITHOUT_UNIGRAMS_MIN_TRI_GRAM, false);
}
[Test]
public virtual void TestFourGramFilterMinTriGram()
{
this.shingleFilterTest(3, 4, TEST_TOKEN, FOUR_GRAM_TOKENS_MIN_TRI_GRAM, FOUR_GRAM_POSITION_INCREMENTS_MIN_TRI_GRAM, FOUR_GRAM_TYPES_MIN_TRI_GRAM, true);
}
[Test]
public virtual void TestFourGramFilterWithoutUnigramsMinTriGram()
{
this.shingleFilterTest(3, 4, TEST_TOKEN, FOUR_GRAM_TOKENS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM, FOUR_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_MIN_TRI_GRAM, FOUR_GRAM_TYPES_WITHOUT_UNIGRAMS_MIN_TRI_GRAM, false);
}
[Test]
public virtual void TestFourGramFilterMinFourGram()
{
this.shingleFilterTest(4, 4, TEST_TOKEN, FOUR_GRAM_TOKENS_MIN_FOUR_GRAM, FOUR_GRAM_POSITION_INCREMENTS_MIN_FOUR_GRAM, FOUR_GRAM_TYPES_MIN_FOUR_GRAM, true);
}
[Test]
public virtual void TestFourGramFilterWithoutUnigramsMinFourGram()
{
this.shingleFilterTest(4, 4, TEST_TOKEN, FOUR_GRAM_TOKENS_WITHOUT_UNIGRAMS_MIN_FOUR_GRAM, FOUR_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_MIN_FOUR_GRAM, FOUR_GRAM_TYPES_WITHOUT_UNIGRAMS_MIN_FOUR_GRAM, false);
}
[Test]
public virtual void TestBiGramFilterNoSeparator()
{
this.shingleFilterTest("", 2, 2, TEST_TOKEN, BI_GRAM_TOKENS_NO_SEPARATOR, BI_GRAM_POSITION_INCREMENTS_NO_SEPARATOR, BI_GRAM_TYPES_NO_SEPARATOR, true);
}
[Test]
public virtual void TestBiGramFilterWithoutUnigramsNoSeparator()
{
this.shingleFilterTest("", 2, 2, TEST_TOKEN, BI_GRAM_TOKENS_WITHOUT_UNIGRAMS_NO_SEPARATOR, BI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_NO_SEPARATOR, BI_GRAM_TYPES_WITHOUT_UNIGRAMS_NO_SEPARATOR, false);
}
[Test]
public virtual void TestTriGramFilterNoSeparator()
{
this.shingleFilterTest("", 2, 3, TEST_TOKEN, TRI_GRAM_TOKENS_NO_SEPARATOR, TRI_GRAM_POSITION_INCREMENTS_NO_SEPARATOR, TRI_GRAM_TYPES_NO_SEPARATOR, true);
}
[Test]
public virtual void TestTriGramFilterWithoutUnigramsNoSeparator()
{
this.shingleFilterTest("", 2, 3, TEST_TOKEN, TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS_NO_SEPARATOR, TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_NO_SEPARATOR, TRI_GRAM_TYPES_WITHOUT_UNIGRAMS_NO_SEPARATOR, false);
}
[Test]
public virtual void TestBiGramFilterAltSeparator()
{
this.shingleFilterTest("<SEP>", 2, 2, TEST_TOKEN, BI_GRAM_TOKENS_ALT_SEPARATOR, BI_GRAM_POSITION_INCREMENTS_ALT_SEPARATOR, BI_GRAM_TYPES_ALT_SEPARATOR, true);
}
[Test]
public virtual void TestBiGramFilterWithoutUnigramsAltSeparator()
{
this.shingleFilterTest("<SEP>", 2, 2, TEST_TOKEN, BI_GRAM_TOKENS_WITHOUT_UNIGRAMS_ALT_SEPARATOR, BI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_ALT_SEPARATOR, BI_GRAM_TYPES_WITHOUT_UNIGRAMS_ALT_SEPARATOR, false);
}
[Test]
public virtual void TestTriGramFilterAltSeparator()
{
this.shingleFilterTest("<SEP>", 2, 3, TEST_TOKEN, TRI_GRAM_TOKENS_ALT_SEPARATOR, TRI_GRAM_POSITION_INCREMENTS_ALT_SEPARATOR, TRI_GRAM_TYPES_ALT_SEPARATOR, true);
}
[Test]
public virtual void TestTriGramFilterWithoutUnigramsAltSeparator()
{
this.shingleFilterTest("<SEP>", 2, 3, TEST_TOKEN, TRI_GRAM_TOKENS_WITHOUT_UNIGRAMS_ALT_SEPARATOR, TRI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS_ALT_SEPARATOR, TRI_GRAM_TYPES_WITHOUT_UNIGRAMS_ALT_SEPARATOR, false);
}
[Test]
public virtual void TestTriGramFilterNullSeparator()
{
this.shingleFilterTest(null, 2, 3, TEST_TOKEN, TRI_GRAM_TOKENS_NULL_SEPARATOR, TRI_GRAM_POSITION_INCREMENTS_NULL_SEPARATOR, TRI_GRAM_TYPES_NULL_SEPARATOR, true);
}
[Test]
public virtual void TestPositionIncrementEqualToN()
{
this.shingleFilterTest(2, 3, TEST_TOKEN_POS_INCR_EQUAL_TO_N, TRI_GRAM_TOKENS_POS_INCR_EQUAL_TO_N, TRI_GRAM_POSITION_INCREMENTS_POS_INCR_EQUAL_TO_N, TRI_GRAM_TYPES_POS_INCR_EQUAL_TO_N, true);
}
[Test]
public virtual void TestPositionIncrementEqualToNWithoutUnigrams()
{
this.shingleFilterTest(2, 3, TEST_TOKEN_POS_INCR_EQUAL_TO_N, TRI_GRAM_TOKENS_POS_INCR_EQUAL_TO_N_WITHOUT_UNIGRAMS, TRI_GRAM_POSITION_INCREMENTS_POS_INCR_EQUAL_TO_N_WITHOUT_UNIGRAMS, TRI_GRAM_TYPES_POS_INCR_EQUAL_TO_N_WITHOUT_UNIGRAMS, false);
}
[Test]
public virtual void TestPositionIncrementGreaterThanN()
{
this.shingleFilterTest(2, 3, TEST_TOKEN_POS_INCR_GREATER_THAN_N, TRI_GRAM_TOKENS_POS_INCR_GREATER_THAN_N, TRI_GRAM_POSITION_INCREMENTS_POS_INCR_GREATER_THAN_N, TRI_GRAM_TYPES_POS_INCR_GREATER_THAN_N, true);
}
[Test]
public virtual void TestPositionIncrementGreaterThanNWithoutUnigrams()
{
this.shingleFilterTest(2, 3, TEST_TOKEN_POS_INCR_GREATER_THAN_N, TRI_GRAM_TOKENS_POS_INCR_GREATER_THAN_N_WITHOUT_UNIGRAMS, TRI_GRAM_POSITION_INCREMENTS_POS_INCR_GREATER_THAN_N_WITHOUT_UNIGRAMS, TRI_GRAM_TYPES_POS_INCR_GREATER_THAN_N_WITHOUT_UNIGRAMS, false);
}
[Test]
public virtual void TestReset()
{
Tokenizer wsTokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader("please divide this sentence"));
TokenStream filter = new ShingleFilter(wsTokenizer, 2);
AssertTokenStreamContents(filter, new string[] { "please", "please divide", "divide", "divide this", "this", "this sentence", "sentence" }, new int[] { 0, 0, 7, 7, 14, 14, 19 }, new int[] { 6, 13, 13, 18, 18, 27, 27 }, new string[] { TypeAttribute.DEFAULT_TYPE, "shingle", TypeAttribute.DEFAULT_TYPE, "shingle", TypeAttribute.DEFAULT_TYPE, "shingle", TypeAttribute.DEFAULT_TYPE }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
wsTokenizer.SetReader(new StringReader("please divide this sentence"));
AssertTokenStreamContents(filter, new string[] { "please", "please divide", "divide", "divide this", "this", "this sentence", "sentence" }, new int[] { 0, 0, 7, 7, 14, 14, 19 }, new int[] { 6, 13, 13, 18, 18, 27, 27 }, new string[] { TypeAttribute.DEFAULT_TYPE, "shingle", TypeAttribute.DEFAULT_TYPE, "shingle", TypeAttribute.DEFAULT_TYPE, "shingle", TypeAttribute.DEFAULT_TYPE }, new int[] { 1, 0, 1, 0, 1, 0, 1 });
}
[Test]
public virtual void TestOutputUnigramsIfNoShinglesSingleTokenCase()
{
// Single token input with outputUnigrams==false is the primary case where
// enabling this option should alter program behavior.
this.shingleFilterTest(2, 2, TEST_SINGLE_TOKEN, SINGLE_TOKEN, SINGLE_TOKEN_INCREMENTS, SINGLE_TOKEN_TYPES, false, true);
}
[Test]
public virtual void TestOutputUnigramsIfNoShinglesWithSimpleBigram()
{
// Here we expect the same result as with testBiGramFilter().
this.shingleFilterTest(2, 2, TEST_TOKEN, BI_GRAM_TOKENS, BI_GRAM_POSITION_INCREMENTS, BI_GRAM_TYPES, true, true);
}
[Test]
public virtual void TestOutputUnigramsIfNoShinglesWithSimpleUnigramlessBigram()
{
// Here we expect the same result as with testBiGramFilterWithoutUnigrams().
this.shingleFilterTest(2, 2, TEST_TOKEN, BI_GRAM_TOKENS_WITHOUT_UNIGRAMS, BI_GRAM_POSITION_INCREMENTS_WITHOUT_UNIGRAMS, BI_GRAM_TYPES_WITHOUT_UNIGRAMS, false, true);
}
[Test]
public virtual void TestOutputUnigramsIfNoShinglesWithMultipleInputTokens()
{
// Test when the minimum shingle size is greater than the number of input tokens
this.shingleFilterTest(7, 7, TEST_TOKEN, TEST_TOKEN, UNIGRAM_ONLY_POSITION_INCREMENTS, UNIGRAM_ONLY_TYPES, false, true);
}
protected internal virtual void shingleFilterTest(int maxSize, Token[] tokensToShingle, Token[] tokensToCompare, int[] positionIncrements, string[] types, bool outputUnigrams)
{
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(tokensToShingle), maxSize);
filter.SetOutputUnigrams(outputUnigrams);
shingleFilterTestCommon(filter, tokensToCompare, positionIncrements, types);
}
protected internal virtual void shingleFilterTest(int minSize, int maxSize, Token[] tokensToShingle, Token[] tokensToCompare, int[] positionIncrements, string[] types, bool outputUnigrams)
{
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(tokensToShingle), minSize, maxSize);
filter.SetOutputUnigrams(outputUnigrams);
shingleFilterTestCommon(filter, tokensToCompare, positionIncrements, types);
}
protected internal virtual void shingleFilterTest(int minSize, int maxSize, Token[] tokensToShingle, Token[] tokensToCompare, int[] positionIncrements, string[] types, bool outputUnigrams, bool outputUnigramsIfNoShingles)
{
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(tokensToShingle), minSize, maxSize);
filter.SetOutputUnigrams(outputUnigrams);
filter.SetOutputUnigramsIfNoShingles(outputUnigramsIfNoShingles);
shingleFilterTestCommon(filter, tokensToCompare, positionIncrements, types);
}
protected internal virtual void shingleFilterTest(string tokenSeparator, int minSize, int maxSize, Token[] tokensToShingle, Token[] tokensToCompare, int[] positionIncrements, string[] types, bool outputUnigrams)
{
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(tokensToShingle), minSize, maxSize);
filter.SetTokenSeparator(tokenSeparator);
filter.SetOutputUnigrams(outputUnigrams);
shingleFilterTestCommon(filter, tokensToCompare, positionIncrements, types);
}
protected internal virtual void shingleFilterTestCommon(ShingleFilter filter, Token[] tokensToCompare, int[] positionIncrements, string[] types)
{
string[] text = new string[tokensToCompare.Length];
int[] startOffsets = new int[tokensToCompare.Length];
int[] endOffsets = new int[tokensToCompare.Length];
for (int i = 0; i < tokensToCompare.Length; i++)
{
text[i] = new string(tokensToCompare[i].Buffer, 0, tokensToCompare[i].Length);
startOffsets[i] = tokensToCompare[i].StartOffset;
endOffsets[i] = tokensToCompare[i].EndOffset;
}
AssertTokenStreamContents(filter, text, startOffsets, endOffsets, types, positionIncrements);
}
private static Token CreateToken(string term, int start, int offset)
{
return CreateToken(term, start, offset, 1);
}
private static Token CreateToken(string term, int start, int offset, int positionIncrement)
{
Token token = new Token(start, offset);
token.CopyBuffer(term.ToCharArray(), 0, term.Length);
token.PositionIncrement = positionIncrement;
return token;
}
/// <summary>
/// blast some random strings through the analyzer </summary>
[Test]
public virtual void TestRandomStrings()
{
Analyzer a = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new ShingleFilter(tokenizer));
});
CheckRandomData(Random, a, 1000 * RandomMultiplier);
}
/// <summary>
/// blast some random large strings through the analyzer </summary>
[Test]
public virtual void TestRandomHugeStrings()
{
Random random = Random;
Analyzer a = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
Tokenizer tokenizer = new MockTokenizer(reader, MockTokenizer.WHITESPACE, false);
return new TokenStreamComponents(tokenizer, new ShingleFilter(tokenizer));
});
CheckRandomData(random, a, 100 * RandomMultiplier, 8192);
}
[Test]
public virtual void TestEmptyTerm()
{
Analyzer a = Analyzer.NewAnonymous(createComponents: (fieldName, reader) =>
{
Tokenizer tokenizer = new KeywordTokenizer(reader);
return new TokenStreamComponents(tokenizer, new ShingleFilter(tokenizer));
});
CheckOneTerm(a, "", "");
}
[Test]
public virtual void TestTrailingHole1()
{
// Analyzing "wizard of", where of is removed as a
// stopword leaving a trailing hole:
Token[] inputTokens = new Token[] { CreateToken("wizard", 0, 6) };
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(1, 9, inputTokens), 2, 2);
AssertTokenStreamContents(filter, new string[] { "wizard", "wizard _" }, new int[] { 0, 0 }, new int[] { 6, 9 }, new int[] { 1, 0 }, 9);
}
[Test]
public virtual void TestTrailingHole2()
{
// Analyzing "purple wizard of", where of is removed as a
// stopword leaving a trailing hole:
Token[] inputTokens = new Token[] { CreateToken("purple", 0, 6), CreateToken("wizard", 7, 13) };
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(1, 16, inputTokens), 2, 2);
AssertTokenStreamContents(filter, new string[] { "purple", "purple wizard", "wizard", "wizard _" }, new int[] { 0, 0, 7, 7 }, new int[] { 6, 13, 13, 16 }, new int[] { 1, 0, 1, 0 }, 16);
}
[Test]
public virtual void TestTwoTrailingHoles()
{
// Analyzing "purple wizard of the", where of and the are removed as a
// stopwords, leaving two trailing holes:
Token[] inputTokens = new Token[] { CreateToken("purple", 0, 6), CreateToken("wizard", 7, 13) };
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(2, 20, inputTokens), 2, 2);
AssertTokenStreamContents(filter, new string[] { "purple", "purple wizard", "wizard", "wizard _" }, new int[] { 0, 0, 7, 7 }, new int[] { 6, 13, 13, 20 }, new int[] { 1, 0, 1, 0 }, 20);
}
[Test]
public virtual void TestTwoTrailingHolesTriShingle()
{
// Analyzing "purple wizard of the", where of and the are removed as a
// stopwords, leaving two trailing holes:
Token[] inputTokens = new Token[] { CreateToken("purple", 0, 6), CreateToken("wizard", 7, 13) };
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(2, 20, inputTokens), 2, 3);
AssertTokenStreamContents(filter, new string[] { "purple", "purple wizard", "purple wizard _", "wizard", "wizard _", "wizard _ _" }, new int[] { 0, 0, 0, 7, 7, 7 }, new int[] { 6, 13, 20, 13, 20, 20 }, new int[] { 1, 0, 0, 1, 0, 0 }, 20);
}
[Test]
public virtual void TestTwoTrailingHolesTriShingleWithTokenFiller()
{
// Analyzing "purple wizard of the", where of and the are removed as a
// stopwords, leaving two trailing holes:
Token[] inputTokens = new Token[] { CreateToken("purple", 0, 6), CreateToken("wizard", 7, 13) };
ShingleFilter filter = new ShingleFilter(new CannedTokenStream(2, 20, inputTokens), 2, 3);
filter.SetFillerToken("--");
AssertTokenStreamContents(filter, new string[] { "purple", "purple wizard", "purple wizard --", "wizard", "wizard --", "wizard -- --" }, new int[] { 0, 0, 0, 7, 7, 7 }, new int[] { 6, 13, 20, 13, 20, 20 }, new int[] { 1, 0, 0, 1, 0, 0 }, 20);
filter = new ShingleFilter(new CannedTokenStream(2, 20, inputTokens), 2, 3);
filter.SetFillerToken("");
AssertTokenStreamContents(filter, new string[] { "purple", "purple wizard", "purple wizard ", "wizard", "wizard ", "wizard " }, new int[] { 0, 0, 0, 7, 7, 7 }, new int[] { 6, 13, 20, 13, 20, 20 }, new int[] { 1, 0, 0, 1, 0, 0 }, 20);
filter = new ShingleFilter(new CannedTokenStream(2, 20, inputTokens), 2, 3);
filter.SetFillerToken(null);
AssertTokenStreamContents(filter, new string[] { "purple", "purple wizard", "purple wizard ", "wizard", "wizard ", "wizard " }, new int[] { 0, 0, 0, 7, 7, 7 }, new int[] { 6, 13, 20, 13, 20, 20 }, new int[] { 1, 0, 0, 1, 0, 0 }, 20);
filter = new ShingleFilter(new CannedTokenStream(2, 20, inputTokens), 2, 3);
filter.SetFillerToken(null);
filter.SetTokenSeparator(null);
AssertTokenStreamContents(filter, new string[] { "purple", "purplewizard", "purplewizard", "wizard", "wizard", "wizard" }, new int[] { 0, 0, 0, 7, 7, 7 }, new int[] { 6, 13, 20, 13, 20, 20 }, new int[] { 1, 0, 0, 1, 0, 0 }, 20);
}
}
}
| |
/********************************************************************************************
Copyright (c) Microsoft Corporation
All rights reserved.
Microsoft Public License:
This license governs use of the accompanying software. If you use the software, you
accept this license. If you do not accept the license, do not use the software.
1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" have the
same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the software.
A "contributor" is any person that distributes its contribution under this license.
"Licensed patents" are a contributor's patent claims that read directly on its contribution.
2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free copyright license to reproduce its contribution, prepare derivative works of
its contribution, and distribute its contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license conditions
and limitations in section 3, each contributor grants you a non-exclusive, worldwide,
royalty-free license under its licensed patents to make, have made, use, sell, offer for
sale, import, and/or otherwise dispose of its contribution in the software or derivative
works of the contribution in the software.
3. Conditions and Limitations
(A) No Trademark License- This license does not grant you rights to use any contributors'
name, logo, or trademarks.
(B) If you bring a patent claim against any contributor over patents that you claim are
infringed by the software, your patent license from such contributor to the software ends
automatically.
(C) If you distribute any portion of the software, you must retain all copyright, patent,
trademark, and attribution notices that are present in the software.
(D) If you distribute any portion of the software in source code form, you may do so only
under this license by including a complete copy of this license with your distribution.
If you distribute any portion of the software in compiled or object code form, you may only
do so under a license that complies with this license.
(E) The software is licensed "as-is." You bear the risk of using it. The contributors give
no express warranties, guarantees or conditions. You may have additional consumer rights
under your local laws which this license cannot change. To the extent permitted under your
local laws, the contributors exclude the implied warranties of merchantability, fitness for
a particular purpose and non-infringement.
********************************************************************************************/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.Win32;
using System.Collections.Generic;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
namespace Microsoft.VisualStudio.Project
{
/// <summary>
/// This type of node is used for references to COM components.
/// </summary>
[CLSCompliant(false)]
[ComVisible(true)]
public class ComReferenceNode : ReferenceNode
{
#region fields
private string typeName;
private Guid typeGuid;
private string projectRelativeFilePath;
private string installedFilePath;
private string minorVersionNumber;
private string majorVersionNumber;
private string lcid;
#endregion
#region properties
public override string Caption
{
get { return this.typeName; }
}
public override string Url
{
get
{
return this.projectRelativeFilePath;
}
}
/// <summary>
/// Returns the Guid of the COM object.
/// </summary>
public Guid TypeGuid
{
get { return this.typeGuid; }
}
/// <summary>
/// Returns the path where the COM object is installed.
/// </summary>
public string InstalledFilePath
{
get { return this.installedFilePath; }
}
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "LCID")]
public string LCID
{
get { return lcid; }
}
public int MajorVersionNumber
{
get
{
if(string.IsNullOrEmpty(majorVersionNumber))
{
return 0;
}
return int.Parse(majorVersionNumber, CultureInfo.CurrentCulture);
}
}
public bool EmbedInteropTypes
{
get
{
bool value;
bool.TryParse(this.ItemNode.GetMetadata(ProjectFileConstants.EmbedInteropTypes), out value);
return value;
}
set
{
this.ItemNode.SetMetadata(ProjectFileConstants.EmbedInteropTypes, value.ToString());
}
}
public string WrapperTool
{
get { return this.ItemNode.GetMetadata(ProjectFileConstants.WrapperTool); }
set { this.ItemNode.SetMetadata(ProjectFileConstants.WrapperTool, value); }
}
public int MinorVersionNumber
{
get
{
if(string.IsNullOrEmpty(minorVersionNumber))
{
return 0;
}
return int.Parse(minorVersionNumber, CultureInfo.CurrentCulture);
}
}
private Automation.OAComReference comReference;
internal override object Object
{
get
{
if(null == comReference)
{
comReference = new Automation.OAComReference(this);
}
return comReference;
}
}
#endregion
#region ctors
/// <summary>
/// Constructor for the ComReferenceNode.
/// </summary>
public ComReferenceNode(ProjectNode root, ProjectElement element)
: base(root, element)
{
this.typeName = this.ItemNode.GetMetadata(ProjectFileConstants.Include);
string typeGuidAsString = this.ItemNode.GetMetadata(ProjectFileConstants.Guid);
if(typeGuidAsString != null)
{
this.typeGuid = new Guid(typeGuidAsString);
}
this.majorVersionNumber = this.ItemNode.GetMetadata(ProjectFileConstants.VersionMajor);
this.minorVersionNumber = this.ItemNode.GetMetadata(ProjectFileConstants.VersionMinor);
this.lcid = this.ItemNode.GetMetadata(ProjectFileConstants.Lcid);
this.SetProjectItemsThatRelyOnReferencesToBeResolved(false);
this.SetInstalledFilePath();
}
/// <summary>
/// Overloaded constructor for creating a ComReferenceNode from selector data
/// </summary>
/// <param name="root">The Project node</param>
/// <param name="selectorData">The component selctor data.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2201:DoNotRaiseReservedExceptionTypes")]
public ComReferenceNode(ProjectNode root, VSCOMPONENTSELECTORDATA selectorData, string wrapperTool = null)
: base(root)
{
if(root == null)
{
throw new ArgumentNullException("root");
}
if(selectorData.type == VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project
|| selectorData.type == VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus)
{
throw new ArgumentException("SelectorData cannot be of type VSCOMPONENTTYPE.VSCOMPONENTTYPE_Project or VSCOMPONENTTYPE.VSCOMPONENTTYPE_ComPlus", "selectorData");
}
// Initialize private state
this.typeName = selectorData.bstrTitle;
this.typeGuid = selectorData.guidTypeLibrary;
this.majorVersionNumber = selectorData.wTypeLibraryMajorVersion.ToString(CultureInfo.InvariantCulture);
this.minorVersionNumber = selectorData.wTypeLibraryMinorVersion.ToString(CultureInfo.InvariantCulture);
this.lcid = selectorData.lcidTypeLibrary.ToString(CultureInfo.InvariantCulture);
this.WrapperTool = wrapperTool;
// Check to see if the COM object actually exists.
this.SetInstalledFilePath();
// If the value cannot be set throw.
if(String.IsNullOrEmpty(this.installedFilePath))
{
throw new InvalidOperationException();
}
}
#endregion
#region methods
protected override NodeProperties CreatePropertiesObject()
{
return new ComReferenceProperties(this);
}
/// <summary>
/// Links a reference node to the project and hierarchy.
/// </summary>
protected override void BindReferenceData()
{
Debug.Assert(this.ItemNode != null, "The AssemblyName field has not been initialized");
// We need to create the project element at this point if it has not been created.
// We cannot do that from the ctor if input comes from a component selector data, since had we been doing that we would have added a project element to the project file.
// The problem with that approach is that we would need to remove the project element if the item cannot be added to the hierachy (E.g. It already exists).
// It is just safer to update the project file now. This is the intent of this method.
// Call MSBuild to build the target ResolveComReferences
if(this.ItemNode == null || this.ItemNode.Item == null)
{
this.ItemNode = this.GetProjectElementBasedOnInputFromComponentSelectorData();
}
this.SetProjectItemsThatRelyOnReferencesToBeResolved(true);
}
/// <summary>
/// Checks if a reference is already added. The method parses all references and compares the the FinalItemSpec and the Guid.
/// </summary>
/// <returns>true if the assembly has already been added.</returns>
protected internal override bool IsAlreadyAdded(out ReferenceNode existingReference)
{
ReferenceContainerNode referencesFolder = this.ProjectMgr.FindChild(ReferenceContainerNode.ReferencesNodeVirtualName) as ReferenceContainerNode;
Debug.Assert(referencesFolder != null, "Could not find the References node");
for(HierarchyNode n = referencesFolder.FirstChild; n != null; n = n.NextSibling)
{
ComReferenceNode referenceNode = n as ComReferenceNode;
if(referenceNode != null)
{
// We check if the name and guids are the same
if(referenceNode.TypeGuid == this.TypeGuid && String.Compare(referenceNode.Caption, this.Caption, StringComparison.OrdinalIgnoreCase) == 0)
{
existingReference = referenceNode;
return true;
}
}
}
existingReference = null;
return false;
}
/// <summary>
/// Determines if this is node a valid node for painting the default reference icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon()
{
return !String.IsNullOrEmpty(this.installedFilePath);
}
/// <summary>
/// This is an helper method to convert the VSCOMPONENTSELECTORDATA recieved by the
/// implementer of IVsComponentUser into a ProjectElement that can be used to create
/// an instance of this class.
/// This should not be called for project reference or reference to managed assemblies.
/// </summary>
/// <returns>ProjectElement corresponding to the COM component passed in</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")]
private ProjectElement GetProjectElementBasedOnInputFromComponentSelectorData()
{
ProjectElement element = new ProjectElement(this.ProjectMgr, this.typeName, ProjectFileConstants.COMReference);
// Set the basic information regarding this COM component
element.SetMetadata(ProjectFileConstants.Guid, this.typeGuid.ToString("B"));
element.SetMetadata(ProjectFileConstants.VersionMajor, this.majorVersionNumber);
element.SetMetadata(ProjectFileConstants.VersionMinor, this.minorVersionNumber);
element.SetMetadata(ProjectFileConstants.Lcid, this.lcid);
element.SetMetadata(ProjectFileConstants.Isolated, false.ToString());
// See if a PIA exist for this component
TypeLibConverter typelib = new TypeLibConverter();
string assemblyName;
string assemblyCodeBase;
if(typelib.GetPrimaryInteropAssembly(this.typeGuid, Int32.Parse(this.majorVersionNumber, CultureInfo.InvariantCulture), Int32.Parse(this.minorVersionNumber, CultureInfo.InvariantCulture), Int32.Parse(this.lcid, CultureInfo.InvariantCulture), out assemblyName, out assemblyCodeBase))
{
element.SetMetadata(ProjectFileConstants.WrapperTool, WrapperToolAttributeValue.Primary.ToString().ToLowerInvariant());
}
else
{
// MSBuild will have to generate an interop assembly
element.SetMetadata(ProjectFileConstants.WrapperTool, WrapperToolAttributeValue.TlbImp.ToString().ToLowerInvariant());
element.SetMetadata(ProjectFileConstants.EmbedInteropTypes, true.ToString());
element.SetMetadata(ProjectFileConstants.Private, true.ToString());
}
return element;
}
private void SetProjectItemsThatRelyOnReferencesToBeResolved(bool renameItemNode)
{
// Call MSBuild to build the target ResolveComReferences
bool success;
ErrorHandler.ThrowOnFailure(this.ProjectMgr.BuildTarget(MsBuildTarget.ResolveComReferences, out success));
if(!success)
throw new InvalidOperationException();
// Now loop through the generated COM References to find the corresponding one
IEnumerable<ProjectItem> comReferences = this.ProjectMgr.BuildProject.GetItems(MsBuildGeneratedItemType.ComReferenceWrappers);
foreach (ProjectItem reference in comReferences)
{
if(String.Compare(reference.GetMetadataValue(ProjectFileConstants.Guid), this.typeGuid.ToString("B"), StringComparison.OrdinalIgnoreCase) == 0
&& String.Compare(reference.GetMetadataValue(ProjectFileConstants.VersionMajor), this.majorVersionNumber, StringComparison.OrdinalIgnoreCase) == 0
&& String.Compare(reference.GetMetadataValue(ProjectFileConstants.VersionMinor), this.minorVersionNumber, StringComparison.OrdinalIgnoreCase) == 0
&& String.Compare(reference.GetMetadataValue(ProjectFileConstants.Lcid), this.lcid, StringComparison.OrdinalIgnoreCase) == 0)
{
string name = reference.EvaluatedInclude;
if(Path.IsPathRooted(name))
{
this.projectRelativeFilePath = name;
}
else
{
this.projectRelativeFilePath = Path.Combine(this.ProjectMgr.ProjectFolder, name);
}
if(renameItemNode)
{
this.ItemNode.Rename(Path.GetFileNameWithoutExtension(name));
}
break;
}
}
}
/// <summary>
/// Verify that the TypeLib is registered and set the the installed file path of the com reference.
/// </summary>
/// <returns></returns>
private void SetInstalledFilePath()
{
string registryPath = string.Format(CultureInfo.InvariantCulture, @"TYPELIB\{0:B}\{1:x}.{2:x}", this.typeGuid, this.MajorVersionNumber, this.MinorVersionNumber);
using(RegistryKey typeLib = Registry.ClassesRoot.OpenSubKey(registryPath))
{
if(typeLib != null)
{
// Check if we need to set the name for this type.
if(string.IsNullOrEmpty(this.typeName))
{
this.typeName = typeLib.GetValue(string.Empty) as string;
}
// Now get the path to the file that contains this type library.
using(RegistryKey installKey = typeLib.OpenSubKey(string.Format(CultureInfo.InvariantCulture, @"{0}\win32", this.LCID)))
{
this.installedFilePath = installKey.GetValue(String.Empty) as String;
}
}
}
}
#endregion
}
}
| |
/*
* SQLitePluginModule.cs
*
* A React Native module that wraps SQLite.
*
* Thread-safety. Except where otherwise noted, all of this class's code runs on a single
* ActionQueue which frees us from having to worry about thread-safety. We have a programming
* model similar to that of the UI thread.
*
* All ReactMethods must run on the same AwaitingQueue. This prevents the ReactMethods from
* interleaving when an `await` happens. This design enables us to think of each ReactMethod
* as being atomic relative to the other ReactMethods.
*/
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Org.PGSQLite.SQLitePlugin
{
/// <summary>
/// A module that allows JS to utilize sqlite databases.
/// </summary>
public class SQLitePluginModule : NativeModuleBase
{
public enum WebSQLError
{
Unknown = 0,
Database = 1,
Version = 2,
TooLarge = 3,
Quota = 4,
Syntax = 5,
Constraint = 6,
Timeout = 7
}
private static readonly IntPtr NegativePointer = new IntPtr(-1);
private static WebSQLError sqliteToWebSQLError(SQLite.Net.Interop.Result sqliteError)
{
switch (sqliteError)
{
case SQLite.Net.Interop.Result.Error:
return WebSQLError.Syntax;
case SQLite.Net.Interop.Result.Full:
return WebSQLError.Quota;
case SQLite.Net.Interop.Result.Constraint:
return WebSQLError.Constraint;
default:
return WebSQLError.Unknown;
}
}
public class SQLiteError
{
public WebSQLError code { get; private set; }
public string message { get; private set; }
public SQLiteError(WebSQLError aCode, string aMessage)
{
code = aCode;
message = aMessage;
}
}
private class RNSQLiteException : Exception
{
public object JsonMessage { get; private set; }
public RNSQLiteException() : base()
{
}
public RNSQLiteException(object jsonMessage) : base()
{
JsonMessage = jsonMessage;
}
public RNSQLiteException(string message) : base(message)
{
JsonMessage = message;
}
public RNSQLiteException(string message, Exception inner) : base(message, inner)
{
JsonMessage = message;
}
}
private static byte[] GetNullTerminatedUtf8(string s)
{
var utf8Length = Encoding.UTF8.GetByteCount(s);
var bytes = new byte[utf8Length + 1];
Encoding.UTF8.GetBytes(s, 0, s.Length, bytes, 0);
return bytes;
}
// Throws when the file already exists.
private static Windows.Foundation.IAsyncOperation<Windows.Storage.StorageFile> CopyDbAsync(Windows.Storage.StorageFile srcDbFile, string destDbFileName)
{
// This implementation is closely related to ResolveDbFilePath.
return srcDbFile.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, destDbFileName, Windows.Storage.NameCollisionOption.FailIfExists);
}
private static string ResolveDbFilePath(string dbFileName)
{
// This implementation is closely related to CopyDbAsync.
return Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, dbFileName);
}
private static Windows.Foundation.IAsyncOperation<Windows.Storage.StorageFile> ResolveAssetFile(string assetFilePath, string dbFileName)
{
if (assetFilePath == null || assetFilePath.Length == 0)
{
return null;
}
else if (assetFilePath == "1")
{
// Built path to pre-populated DB asset from app bundle www subdirectory
return Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(
"ms-appx:///www/" + dbFileName));
}
else if (assetFilePath[0] == '~')
{
// Built path to pre-populated DB asset from app bundle subdirectory
return Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(
"ms-appx:///" + assetFilePath.Substring(1)));
}
else
{
// Built path to pre-populated DB asset from app sandbox directory
return Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri(
"ms-appdata:///local/" + assetFilePath));
}
}
private class OpenDB
{
public SQLite.Net.Interop.IDbHandle Handle { get; private set; }
public string Path { get; private set; }
public OpenDB(SQLite.Net.Interop.IDbHandle handle, string path)
{
Handle = handle;
Path = path;
}
}
private readonly SQLite.Net.Platform.WinRT.SQLiteApiWinRT _sqliteAPI;
private readonly Dictionary<string, OpenDB> _openDBs = new Dictionary<string, OpenDB>();
private readonly AwaitingQueue _awaitingQueue = new AwaitingQueue();
private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource();
/// <summary>
/// Instantiates the <see cref="SQLitePluginModule"/>.
/// </summary>
internal SQLitePluginModule()
{
_sqliteAPI = new SQLite.Net.Platform.WinRT.SQLiteApiWinRT(tempFolderPath: null, useWinSqlite: true);
}
public override void OnReactInstanceDispose()
{
_cancellationTokenSource.Cancel();
// TODO: When React Native Windows introduces asynchronous disposal
// (`OnReactInstanceDisposeAsync`), we should start using that and
// we should run this work on the awaiting queue. Currently, there's
// a race condition where we might close the database while one of
// the ReactMethods is in the middle of an `await`.
// https://github.com/Microsoft/react-native-windows/issues/1873
foreach (var dbInfoPair in _openDBs)
{
if (_sqliteAPI.Close(dbInfoPair.Value.Handle) != SQLite.Net.Interop.Result.OK)
{
System.Diagnostics.Debug.WriteLine("SQLitePluginModule: Error closing database: " + dbInfoPair.Value.Path);
}
}
_openDBs.Clear();
}
/// <summary>
/// The name of the native module.
/// </summary>
public override string Name
{
get
{
return "SQLite";
}
}
private async void QueueWithCancellation(Func<Task> work)
{
await _awaitingQueue.RunOrQueue(work, _cancellationTokenSource.Token);
}
public class EchoStringValueOptions
{
public string Value { get; set; }
}
[ReactMethod]
public void echoStringValue(EchoStringValueOptions options, ICallback success, ICallback error)
{
QueueWithCancellation(() =>
{
success.Invoke(options.Value);
return Task.CompletedTask;
});
}
public class OpenOptions
{
// Path at which to store the database
public string Name { get; set; }
// Optional. When creating the DB, uses this file as the initial state.
public string AssetFileName { get; set; }
public bool ReadOnly { get; set; }
}
[ReactMethod]
public void open(OpenOptions options, ICallback success, ICallback error)
{
QueueWithCancellation(async () =>
{
var dbFileName = options.Name;
if (dbFileName == null)
{
error.Invoke("You must specify database name");
return;
}
if (_openDBs.ContainsKey(dbFileName))
{
success.Invoke("Database opened");
return;
}
var assetFileOp = ResolveAssetFile(options.AssetFileName, dbFileName);
var assetFile = assetFileOp == null ? null : await assetFileOp;
// NoMutex means SQLite can be safely used by multiple threads provided that no
// single database connection is used simultaneously in two or more threads.
SQLite.Net.Interop.SQLiteOpenFlags sqlOpenFlags = SQLite.Net.Interop.SQLiteOpenFlags.NoMutex;
string absoluteDbPath;
if (options.ReadOnly && assetFileOp != null)
{
sqlOpenFlags |= SQLite.Net.Interop.SQLiteOpenFlags.ReadOnly;
absoluteDbPath = assetFile.Path;
}
else
{
sqlOpenFlags |= SQLite.Net.Interop.SQLiteOpenFlags.ReadWrite | SQLite.Net.Interop.SQLiteOpenFlags.Create;
absoluteDbPath = ResolveDbFilePath(dbFileName);
// Option to create from resource (pre-populated) if db does not exist:
if (assetFileOp != null)
{
try
{
await CopyDbAsync(assetFile, dbFileName);
}
catch (Exception)
{
// CopyDbAsync throws when the file already exists.
}
}
}
SQLite.Net.Interop.IDbHandle dbHandle;
if (_sqliteAPI.Open(GetNullTerminatedUtf8(absoluteDbPath), out dbHandle, (int)sqlOpenFlags, IntPtr.Zero) == SQLite.Net.Interop.Result.OK)
{
_openDBs[dbFileName] = new OpenDB(dbHandle, absoluteDbPath);
success.Invoke("Database opened");
}
else
{
error.Invoke("Unable to open DB");
}
});
}
public class CloseOptions
{
public string Path { get; set; }
}
[ReactMethod]
public void close(CloseOptions options, ICallback success, ICallback error)
{
QueueWithCancellation(() =>
{
var dbFileName = options.Path;
if (dbFileName == null)
{
error.Invoke("You must specify database path");
return Task.CompletedTask;
}
if (!_openDBs.ContainsKey(dbFileName))
{
error.Invoke("Specified db was not open");
return Task.CompletedTask;
}
var dbInfo = _openDBs[dbFileName];
_openDBs.Remove(dbFileName);
if (_sqliteAPI.Close(dbInfo.Handle) != SQLite.Net.Interop.Result.OK)
{
System.Diagnostics.Debug.WriteLine("SQLitePluginModule: Error closing database: " + dbInfo.Path);
}
success.Invoke("DB closed");
return Task.CompletedTask;
});
}
[ReactMethod]
public void attach(JObject options, ICallback success, ICallback error)
{
QueueWithCancellation(() =>
{
error.Invoke("attach isn't supported on this platform");
return Task.CompletedTask;
});
}
public class DeleteOptions
{
public string Path { get; set; }
}
[ReactMethod]
public void delete(DeleteOptions options, ICallback success, ICallback error)
{
QueueWithCancellation(async () =>
{
var dbFileName = options.Path;
if (dbFileName == null)
{
error.Invoke("You must specify database path");
return;
}
if (_openDBs.ContainsKey(dbFileName))
{
var dbInfo = _openDBs[dbFileName];
_openDBs.Remove(dbFileName);
if (_sqliteAPI.Close(dbInfo.Handle) != SQLite.Net.Interop.Result.OK)
{
System.Diagnostics.Debug.WriteLine("SQLitePluginModule: Error closing database: " + dbInfo.Path);
}
}
var absoluteDbPath = ResolveDbFilePath(dbFileName);
try
{
var dbFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(absoluteDbPath);
await dbFile.DeleteAsync();
}
catch (FileNotFoundException)
{
error.Invoke("The database does not exist on that path");
return;
}
success.Invoke("DB deleted");
});
}
public class DBArgs
{
public string DBName { get; set; }
}
public class DBQuery
{
public int QID { get; set; }
public JArray Params { get; set; } // optional
public string SQL { get; set; }
}
public class ExecuteSqlBatchOptions
{
public DBArgs DBArgs { get; set; }
public List<DBQuery> Executes { get; set; }
}
private void BindStatement(SQLite.Net.Interop.IDbStatement statement, int argIndex, JToken arg)
{
switch (arg.Type)
{
case JTokenType.Undefined:
case JTokenType.Null:
_sqliteAPI.BindNull(statement, argIndex);
break;
case JTokenType.Boolean:
_sqliteAPI.BindInt(statement, argIndex, arg.ToObject<bool>() ? 1 : 0);
break;
case JTokenType.Integer:
_sqliteAPI.BindInt64(statement, argIndex, arg.ToObject<long>());
break;
case JTokenType.Float:
_sqliteAPI.BindDouble(statement, argIndex, arg.ToObject<double>());
break;
case JTokenType.String:
_sqliteAPI.BindText16(statement, argIndex, arg.ToObject<string>(), -1, NegativePointer);
break;
default:
_sqliteAPI.BindText16(statement, argIndex, arg.ToObject<string>(), -1, NegativePointer);
break;
}
}
private object ExtractColumn(SQLite.Net.Interop.IDbStatement statement, int columnIndex)
{
var columnType = _sqliteAPI.ColumnType(statement, columnIndex);
switch (columnType)
{
case SQLite.Net.Interop.ColType.Integer:
return _sqliteAPI.ColumnInt64(statement, columnIndex);
case SQLite.Net.Interop.ColType.Float:
return _sqliteAPI.ColumnDouble(statement, columnIndex);
case SQLite.Net.Interop.ColType.Blob:
return _sqliteAPI.ColumnBlob(statement, columnIndex);
case SQLite.Net.Interop.ColType.Text:
return _sqliteAPI.ColumnText16(statement, columnIndex);
case SQLite.Net.Interop.ColType.Null:
default:
return null;
}
}
private Dictionary<string, object> ExtractRow(SQLite.Net.Interop.IDbStatement statement)
{
var row = new Dictionary<string, object>();
var columnCount = _sqliteAPI.ColumnCount(statement);
for (var i = 0; i < columnCount; i++)
{
var columnName = _sqliteAPI.ColumnName16(statement, i);
var columnValue = ExtractColumn(statement, i);
if (columnValue != null)
{
row[columnName] = columnValue;
}
}
return row;
}
public delegate void SQLiteErrorEvent(SQLiteError error);
public event SQLiteErrorEvent OnSQLiteError;
private bool _isExecutingQuery = false;
private Dictionary<string, object> ExecuteQuery(OpenDB dbInfo, DBQuery query)
{
System.Diagnostics.Debug.Assert(!_isExecutingQuery, "SQLitePluginModule: Only 1 query should be executing at a time.");
_isExecutingQuery = true;
try
{
if (query.SQL == null)
{
throw new RNSQLiteException("You must specify a sql query to execute");
}
try
{
var previousRowsAffected = _sqliteAPI.TotalChanges(dbInfo.Handle);
var statement = _sqliteAPI.Prepare2(dbInfo.Handle, query.SQL);
if (query.Params != null)
{
var argIndex = 0;
foreach (var arg in query.Params.Children())
{
// sqlite bind uses 1-based indexing for the arguments
BindStatement(statement, argIndex + 1, arg);
argIndex++;
}
}
var resultRows = new List<Dictionary<string, object>>();
long? insertId = null;
var rowsAffected = 0;
SQLiteError error = null;
var keepGoing = true;
while (keepGoing)
{
switch (_sqliteAPI.Step(statement))
{
case SQLite.Net.Interop.Result.Row:
resultRows.Add(ExtractRow(statement));
break;
case SQLite.Net.Interop.Result.Done:
var nowRowsAffected = _sqliteAPI.TotalChanges(dbInfo.Handle);
rowsAffected = nowRowsAffected - previousRowsAffected;
var nowInsertId = _sqliteAPI.LastInsertRowid(dbInfo.Handle);
if (rowsAffected > 0 && nowInsertId != 0)
{
insertId = nowInsertId;
}
keepGoing = false;
break;
default:
var webErrorCode = sqliteToWebSQLError(_sqliteAPI.ErrCode(dbInfo.Handle));
var message = _sqliteAPI.Errmsg16(dbInfo.Handle);
error = new SQLiteError(webErrorCode, message);
keepGoing = false;
break;
}
}
_sqliteAPI.Finalize(statement);
if (error != null)
{
NotifyOnSQLiteException(error);
throw new RNSQLiteException(error);
}
var resultSet = new Dictionary<string, object>
{
{ "rows", resultRows },
{ "rowsAffected", rowsAffected }
};
if (insertId != null)
{
resultSet["insertId"] = insertId;
}
return resultSet;
}
catch (SQLite.Net.SQLiteException ex)
{
var error = new SQLiteError(sqliteToWebSQLError(ex.Result), ex.Message);
NotifyOnSQLiteException(error);
throw new RNSQLiteException(error);
}
}
finally
{
_isExecutingQuery = false;
}
}
private void NotifyOnSQLiteException(SQLiteError error)
{
try
{
OnSQLiteError?.Invoke(error);
}
catch (Exception)
{
// no-op
}
}
[ReactMethod]
public void executeSqlBatch(ExecuteSqlBatchOptions options, ICallback success, ICallback error)
{
QueueWithCancellation(() =>
{
var dbFileName = options.DBArgs.DBName;
if (dbFileName == null)
{
error.Invoke("You must specify database path");
return Task.CompletedTask;
}
OpenDB dbInfo;
if (!_openDBs.TryGetValue(dbFileName, out dbInfo))
{
error.Invoke("No such database, you must open it first");
return Task.CompletedTask;
}
var results = new List<Dictionary<string, object>>();
foreach (var query in options.Executes)
{
try
{
var rawResult = ExecuteQuery(dbInfo, query);
results.Add(new Dictionary<string, object>
{
{ "qid", query.QID },
{ "type", "success" },
{ "result", rawResult }
});
}
catch (RNSQLiteException ex)
{
results.Add(new Dictionary<string, object>
{
{ "qid", query.QID },
{ "type", "error" },
{ "error", ex.JsonMessage },
{ "result", ex.JsonMessage }
});
}
}
success.Invoke(results);
return Task.CompletedTask;
});
}
[ReactMethod]
public void backgroundExecuteSqlBatch(ExecuteSqlBatchOptions options, ICallback success, ICallback error)
{
// Currently, all ReactMethods are run on the same ActionQueue. This prevents
// queries from being able to run in parallel but it makes the code simpler.
//
// `executeSqlBatch` takes care of putting the work on the awaiting queue
// so we don't have to.
executeSqlBatch(options, success, error);
}
}
}
| |
// Copyright (c) Microsoft. 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.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Testing;
using Microsoft.CodeAnalysis.Text;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Text.Analyzers.IdentifiersShouldBeSpelledCorrectlyAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Text.Analyzers.UnitTests
{
public class IdentifiersShouldBeSpelledCorrectlyTests
{
public enum DictionaryType
{
Xml,
Dic,
}
public static IEnumerable<object[]> MisspelledMembers
=> new[]
{
new object[] { CreateTypeWithConstructor("Clazz", constructorName: "{|#0:Clazz|}", isStatic: false), "Clazz", "Clazz.Clazz()" },
new object[] { CreateTypeWithConstructor("Clazz", constructorName: "{|#0:Clazz|}", isStatic: true), "Clazz", "Clazz.Clazz()" },
new object[] { CreateTypeWithField("Program", "{|#0:_fild|}"), "fild", "Program._fild" },
new object[] { CreateTypeWithEvent("Program", "{|#0:Evt|}"), "Evt", "Program.Evt" },
new object[] { CreateTypeWithProperty("Program", "{|#0:Naem|}"), "Naem", "Program.Naem" },
new object[] { CreateTypeWithMethod("Program", "{|#0:SomeMathod|}"), "Mathod", "Program.SomeMathod()" },
};
public static IEnumerable<object[]> UnmeaningfulMembers
=> new[]
{
new object[] { CreateTypeWithConstructor("A", constructorName: "{|#0:A|}", isStatic: false), "A" },
new object[] { CreateTypeWithConstructor("B", constructorName: "{|#0:B|}", isStatic: false), "B" },
new object[] { CreateTypeWithField("Program", "{|#0:_c|}"), "c" },
new object[] { CreateTypeWithEvent("Program", "{|#0:D|}"), "D" },
new object[] { CreateTypeWithProperty("Program", "{|#0:E|}"), "E" },
new object[] { CreateTypeWithMethod("Program", "{|#0:F|}"), "F" },
};
public static IEnumerable<object[]> MisspelledMemberParameters
=> new[]
{
new object[] { CreateTypeWithConstructor("Program", parameter: "int {|#0:yourNaem|}", isStatic: false), "Naem", "yourNaem", "Program.Program(int)" },
new object[] { CreateTypeWithMethod("Program", "Method", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.Method(int)" },
new object[] { CreateTypeWithIndexer("Program", "int {|#0:yourNaem|}"), "Naem", "yourNaem", "Program.this[int]" },
};
[Theory]
[InlineData("namespace Bar { }")]
[InlineData("class Program { }")]
[InlineData("class Program { void Member() { } }")]
[InlineData("class Program { int _variable = 1; }")]
[InlineData("class Program { void Member(string name) { } }")]
[InlineData("class Program { delegate int GetNumber(string name); }")]
[InlineData("class Program<TResource> { }")]
public async Task NoMisspellings_Verify_NoDiagnosticsAsync(string source)
{
await VerifyCSharpAsync(source);
}
[Fact]
public async Task MisspellingAllowedByGlobalXmlDictionary_Verify_NoDiagnosticsAsync()
{
var source = "class Clazz { }";
var dictionary = CreateXmlDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingAllowedByGlobalDicDictionary_Verify_NoDiagnosticsAsync()
{
var source = "class Clazz { }";
var dictionary = CreateDicDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingsAllowedByMultipleGlobalDictionaries_Verify_NoDiagnosticsAsync()
{
var source = @"class Clazz { const string Naem = ""foo""; }";
var xmlDictionary = CreateXmlDictionary(new[] { "clazz" });
var dicDictionary = CreateDicDictionary(new[] { "naem" });
await VerifyCSharpAsync(source, new[] { xmlDictionary, dicDictionary });
}
[Fact]
public async Task CorrectWordDisallowedByGlobalXmlDictionary_Verify_EmitsDiagnosticAsync()
{
var source = "class {|#0:Program|} { }";
var dictionary = CreateXmlDictionary(null, new[] { "program" });
await VerifyCSharpAsync(
source,
dictionary,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule)
.WithLocation(0)
.WithArguments("Program", "Program"));
}
[Fact]
public async Task MisspellingAllowedByProjectDictionary_Verify_NoDiagnosticsAsync()
{
var source = "class Clazz {}";
var dictionary = CreateDicDictionary(new[] { "clazz" });
await VerifyCSharpAsync(source, dictionary);
}
[Fact]
public async Task MisspellingAllowedByDifferentProjectDictionary_Verify_EmitsDiagnosticAsync()
{
var source = "class {|#0:Clazz|} {}";
var dictionary = CreateDicDictionary(new[] { "clazz" });
var test = new VerifyCS.Test
{
TestState =
{
Sources = { source },
AdditionalProjects =
{
["OtherProject"] =
{
AdditionalFiles = { dictionary }
},
},
AdditionalProjectReferences = { "OtherProject" }
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule)
.WithLocation(0)
.WithArguments("Clazz", "Clazz")
}
};
await test.RunAsync();
}
[Fact]
public async Task AssemblyMisspelled_Verify_EmitsDiagnosticAsync()
{
var source = "{|#0:class Program {}|}";
var test = new VerifyCS.Test
{
TestState =
{
Sources = { source },
},
SolutionTransforms =
{
(solution, projectId) => RenameProjectAssembly(solution, projectId),
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.AssemblyRule)
.WithLocation(0)
.WithArguments("Assambly", "MyAssambly")
}
};
await test.RunAsync();
static Solution RenameProjectAssembly(Solution solution, ProjectId projectId)
{
return solution.WithProjectAssemblyName(projectId, "MyAssambly");
}
}
[Fact]
public async Task AssemblyUnmeaningful_Verify_EmitsDiagnosticAsync()
{
var source = "{|#0:class Program {}|}";
var test = new VerifyCS.Test
{
TestState =
{
Sources = { source },
},
SolutionTransforms =
{
(solution, projectId) => RenameProjectAssembly(solution, projectId),
},
ExpectedDiagnostics =
{
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.AssemblyMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("A")
}
};
await test.RunAsync();
static Solution RenameProjectAssembly(Solution solution, ProjectId projectId)
{
return solution.WithProjectAssemblyName(projectId, "A");
}
}
[Fact]
public async Task NamespaceMisspelled_Verify_EmitsDiagnosticAsync()
{
var source = "namespace Tests.{|#0:MyNarmspace|} {}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.NamespaceRule)
.WithLocation(0)
.WithArguments("Narmspace", "Tests.MyNarmspace"));
}
[Fact]
public async Task NamespaceUnmeaningful_Verify_EmitsDiagnosticAsync()
{
var source = "namespace Tests.{|#0:A|} {}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.NamespaceMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("A"));
}
[Theory]
[InlineData("namespace MyNamespace { class {|#0:MyClazz|} {} }", "Clazz", "MyNamespace.MyClazz")]
[InlineData("namespace MyNamespace { struct {|#0:MyStroct|} {} }", "Stroct", "MyNamespace.MyStroct")]
[InlineData("namespace MyNamespace { enum {|#0:MyEnim|} {} }", "Enim", "MyNamespace.MyEnim")]
[InlineData("namespace MyNamespace { interface {|#0:IMyFase|} {} }", "Fase", "MyNamespace.IMyFase")]
[InlineData("namespace MyNamespace { delegate int {|#0:MyDelegete|}(); }", "Delegete", "MyNamespace.MyDelegete")]
public async Task TypeMisspelled_Verify_EmitsDiagnosticAsync(string source, string misspelling, string typeName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeRule)
.WithLocation(0)
.WithArguments(misspelling, typeName));
}
[Theory]
[InlineData("class {|#0:A|} {}", "A")]
[InlineData("struct {|#0:B|} {}", "B")]
[InlineData("enum {|#0:C|} {}", "C")]
[InlineData("interface {|#0:ID|} {}", "D")]
[InlineData("delegate int {|#0:E|}();", "E")]
public async Task TypeUnmeaningful_Verify_EmitsDiagnosticAsync(string source, string typeName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments(typeName));
}
[Theory]
[MemberData(nameof(MisspelledMembers))]
public async Task MemberMisspelled_Verify_EmitsDiagnosticAsync(string source, string misspelling, string memberName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberRule)
.WithLocation(0)
.WithArguments(misspelling, memberName));
}
[Fact]
public async Task MemberOverrideMisspelled_Verify_EmitsDiagnosticOnlyAtDefinitionAsync()
{
var source = @"
abstract class Parent
{
protected abstract string {|#0:Naem|} { get; }
public abstract int {|#1:Mathod|}();
}
class Child : Parent
{
protected override string Naem => ""child"";
public override int Mathod() => 0;
}
class Grandchild : Child
{
protected override string Naem => ""grandchild"";
public override int Mathod() => 1;
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberRule)
.WithLocation(0)
.WithArguments("Naem", "Parent.Naem"),
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberRule)
.WithLocation(1)
.WithArguments("Mathod", "Parent.Mathod()"));
}
[Theory]
[MemberData(nameof(UnmeaningfulMembers))]
public async Task MemberUnmeaningful_Verify_EmitsDiagnosticAsync(string source, string memberName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments(memberName));
}
[Fact]
public async Task VariableMisspelled_Verify_EmitsDiagnosticAsync()
{
var source = @"
class Program
{
public Program()
{
var {|#0:myVoriable|} = 5;
}
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.VariableRule)
.WithLocation(0)
.WithArguments("Voriable", "myVoriable"));
}
[Theory]
[MemberData(nameof(MisspelledMemberParameters))]
public async Task MemberParameterMisspelled_Verify_EmitsDiagnosticAsync(string source, string misspelling, string parameterName, string memberName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterRule)
.WithLocation(0)
.WithArguments(memberName, misspelling, parameterName));
}
[Fact]
public async Task MemberParameterUnmeaningful_Verify_EmitsDiagnosticAsync()
{
var source = @"
class Program
{
public void Method(string {|#0:a|})
{
}
public string this[int {|#1:i|}] => null;
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("Program.Method(string)", "a"),
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MemberParameterMoreMeaningfulNameRule)
.WithLocation(1)
.WithArguments("Program.this[int]", "i"));
}
[Fact]
public async Task DelegateParameterMisspelled_Verify_EmitsDiagnosticAsync()
{
var source = "delegate void MyDelegate(string {|#0:firstNaem|});";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.DelegateParameterRule)
.WithLocation(0)
.WithArguments("MyDelegate", "Naem", "firstNaem"));
}
[Fact]
public async Task DelegateParameterUnmeaningful_Verify_EmitsDiagnosticAsync()
{
var source = "delegate void MyDelegate(string {|#0:a|});";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.DelegateParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("MyDelegate", "a"));
}
[Theory]
[InlineData("class MyClass<TCorrect, {|#0:TWroong|}> { }", "MyClass<TCorrect, TWroong>", "Wroong", "TWroong")]
[InlineData("struct MyStructure<{|#0:TWroong|}> { }", "MyStructure<TWroong>", "Wroong", "TWroong")]
[InlineData("interface IInterface<{|#0:TWroong|}> { }", "IInterface<TWroong>", "Wroong", "TWroong")]
[InlineData("delegate int MyDelegate<{|#0:TWroong|}>();", "MyDelegate<TWroong>", "Wroong", "TWroong")]
public async Task TypeTypeParameterMisspelled_Verify_EmitsDiagnosticAsync(string source, string typeName, string misspelling, string typeParameterName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeTypeParameterRule)
.WithLocation(0)
.WithArguments(typeName, misspelling, typeParameterName));
}
[Theory]
[InlineData("class MyClass<{|#0:A|}> { }", "MyClass<A>", "A")]
[InlineData("struct MyStructure<{|#0:B|}> { }", "MyStructure<B>", "B")]
[InlineData("interface IInterface<{|#0:C|}> { }", "IInterface<C>", "C")]
[InlineData("delegate int MyDelegate<{|#0:D|}>();", "MyDelegate<D>", "D")]
public async Task TypeTypeParameterUnmeaningful_Verify_EmitsDiagnosticAsync(string source, string typeName, string typeParameterName)
{
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.TypeTypeParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments(typeName, typeParameterName));
}
[Fact]
public async Task MethodTypeParameterMisspelled_Verify_EmitsDiagnosticAsync()
{
var source = @"
class Program
{
void Method<{|#0:TTipe|}>(TTipe item)
{
}
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MethodTypeParameterRule)
.WithLocation(0)
.WithArguments("Program.Method<TTipe>(TTipe)", "Tipe", "TTipe"));
}
[Fact]
public async Task MethodTypeParameterUnmeaningful_Verify_EmitsDiagnosticAsync()
{
var source = @"
class Program
{
void Method<{|#0:TA|}>(TA parameter)
{
}
}";
await VerifyCSharpAsync(
source,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.MethodTypeParameterMoreMeaningfulNameRule)
.WithLocation(0)
.WithArguments("Program.Method<TA>(TA)", "TA"));
}
[Fact]
public async Task MisspellingContainsOnlyCapitalizedLetters_Verify_NoDiagnosticsAsync()
{
var source = "class FCCA { }";
await VerifyCSharpAsync(source);
}
[Theory]
[InlineData("0x0")]
[InlineData("0xDEADBEEF")]
public async Task MisspellingStartsWithADigit_Verify_NoDiagnosticsAsync(string misspelling)
{
var source = $"enum Name {{ My{misspelling} }}";
await VerifyCSharpAsync(source);
}
[Fact]
public async Task MalformedXmlDictionary_Verify_EmitsDiagnosticAsync()
{
var contents = @"<?xml version=""1.0"" encoding=""utf-8""?>
<Dictionary>
<Words>
<Recognized>
<Word>okay</Word>
<word>bad</Word> <!-- xml tags are case-sensitive -->
</Recognized>
</Words>
</Dictionary>";
var dictionary = ("CodeAnalysisDictionary.xml", contents);
await VerifyCSharpAsync(
"class Program {}",
dictionary,
VerifyCS.Diagnostic(IdentifiersShouldBeSpelledCorrectlyAnalyzer.FileParseRule)
// Ignore diagnostic message comparison because the actual message
// includes localized content from an exception's message
.WithMessage(null));
}
private Task VerifyCSharpAsync(string source, params DiagnosticResult[] expected)
=> VerifyCSharpAsync(source, Array.Empty<(string Path, string Text)>(), expected);
private Task VerifyCSharpAsync(string source, (string Path, string Text) additionalText, params DiagnosticResult[] expected)
=> VerifyCSharpAsync(source, new[] { additionalText }, expected);
private async Task VerifyCSharpAsync(string source, (string Path, string Text)[] additionalTexts, params DiagnosticResult[] expected)
{
var csharpTest = new VerifyCS.Test
{
TestCode = source,
TestState =
{
AdditionalFilesFactories = { () => additionalTexts.Select(x => (x.Path, SourceText.From(x.Text))) }
},
TestBehaviors = TestBehaviors.SkipSuppressionCheck,
};
csharpTest.ExpectedDiagnostics.AddRange(expected);
await csharpTest.RunAsync();
}
private static (string Path, string Text) CreateXmlDictionary(IEnumerable<string> recognizedWords, IEnumerable<string> unrecognizedWords = null)
=> CreateXmlDictionary("CodeAnalysisDictionary.xml", recognizedWords, unrecognizedWords);
private static (string Path, string Text) CreateXmlDictionary(string filename, IEnumerable<string> recognizedWords, IEnumerable<string> unrecognizedWords = null)
{
var contents = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<Dictionary>
<Words>
<Recognized>{CreateXml(recognizedWords)}</Recognized>
<Unrecognized>{CreateXml(unrecognizedWords)}</Unrecognized>
</Words>
</Dictionary>";
return (filename, contents);
static string CreateXml(IEnumerable<string> words) =>
string.Join(Environment.NewLine, words?.Select(x => $"<Word>{x}</Word>") ?? Enumerable.Empty<string>());
}
private static (string Path, string Text) CreateDicDictionary(IEnumerable<string> recognizedWords)
{
var contents = string.Join(Environment.NewLine, recognizedWords);
return ("CustomDictionary.dic", contents);
}
private static string CreateTypeWithConstructor(string typeName, string constructorName = "", string parameter = "", bool isStatic = false)
{
if (string.IsNullOrEmpty(constructorName))
{
constructorName = typeName;
}
return $@"
#pragma warning disable {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}
class {typeName}
#pragma warning restore {IdentifiersShouldBeSpelledCorrectlyAnalyzer.RuleId}
{{
{(isStatic ? "static " : string.Empty)}{constructorName}({parameter}) {{ }}
}}";
}
private static string CreateTypeWithMethod(string typeName, string methodName, string parameter = "")
=> $"class {typeName} {{ void {methodName}({parameter}) {{ }} }}";
private static string CreateTypeWithIndexer(string typeName, string parameter)
=> $"class {typeName} {{ int this[{parameter}] => 0; }}";
private static string CreateTypeWithProperty(string typeName, string propertyName)
=> $"class {typeName} {{ string {propertyName} {{ get; }} }}";
private static string CreateTypeWithField(string typeName, string fieldName)
=> $"class {typeName} {{ private string {fieldName}; }}";
private static string CreateTypeWithEvent(string typeName, string eventName)
=> $@"using System;
class {typeName} {{ event EventHandler<string> {eventName}; }}";
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.FirebaseRealtimeDatabase.v1beta
{
/// <summary>The FirebaseRealtimeDatabase Service.</summary>
public class FirebaseRealtimeDatabaseService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1beta";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public FirebaseRealtimeDatabaseService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public FirebaseRealtimeDatabaseService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Projects = new ProjectsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "firebasedatabase";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://firebasedatabase.googleapis.com/";
#else
"https://firebasedatabase.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://firebasedatabase.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Firebase Realtime Database Management API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>
/// View your data across Google Cloud services and see the email address of your Google Account
/// </summary>
public static string CloudPlatformReadOnly = "https://www.googleapis.com/auth/cloud-platform.read-only";
/// <summary>View and administer all your Firebase data and settings</summary>
public static string Firebase = "https://www.googleapis.com/auth/firebase";
/// <summary>View all your Firebase data and settings</summary>
public static string FirebaseReadonly = "https://www.googleapis.com/auth/firebase.readonly";
}
/// <summary>
/// Available OAuth 2.0 scope constants for use with the Firebase Realtime Database Management API.
/// </summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>
/// View your data across Google Cloud services and see the email address of your Google Account
/// </summary>
public const string CloudPlatformReadOnly = "https://www.googleapis.com/auth/cloud-platform.read-only";
/// <summary>View and administer all your Firebase data and settings</summary>
public const string Firebase = "https://www.googleapis.com/auth/firebase";
/// <summary>View all your Firebase data and settings</summary>
public const string FirebaseReadonly = "https://www.googleapis.com/auth/firebase.readonly";
}
/// <summary>Gets the Projects resource.</summary>
public virtual ProjectsResource Projects { get; }
}
/// <summary>A base abstract class for FirebaseRealtimeDatabase requests.</summary>
public abstract class FirebaseRealtimeDatabaseBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new FirebaseRealtimeDatabaseBaseServiceRequest instance.</summary>
protected FirebaseRealtimeDatabaseBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes FirebaseRealtimeDatabase parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "projects" collection of methods.</summary>
public class ProjectsResource
{
private const string Resource = "projects";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ProjectsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Locations = new LocationsResource(service);
}
/// <summary>Gets the Locations resource.</summary>
public virtual LocationsResource Locations { get; }
/// <summary>The "locations" collection of methods.</summary>
public class LocationsResource
{
private const string Resource = "locations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public LocationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
Instances = new InstancesResource(service);
}
/// <summary>Gets the Instances resource.</summary>
public virtual InstancesResource Instances { get; }
/// <summary>The "instances" collection of methods.</summary>
public class InstancesResource
{
private const string Resource = "instances";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public InstancesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Requests that a new DatabaseInstance be created. The state of a successfully created
/// DatabaseInstance is ACTIVE. Only available for projects on the Blaze plan. Projects can be upgraded
/// using the Cloud Billing API
/// https://cloud.google.com/billing/reference/rest/v1/projects/updateBillingInfo. Note that it might
/// take a few minutes for billing enablement state to propagate to Firebase systems.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="parent">
/// The parent project for which to create a database instance, in the form:
/// `projects/{project-number}/locations/{location-id}`.
/// </param>
public virtual CreateRequest Create(Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance body, string parent)
{
return new CreateRequest(service, body, parent);
}
/// <summary>
/// Requests that a new DatabaseInstance be created. The state of a successfully created
/// DatabaseInstance is ACTIVE. Only available for projects on the Blaze plan. Projects can be upgraded
/// using the Cloud Billing API
/// https://cloud.google.com/billing/reference/rest/v1/projects/updateBillingInfo. Note that it might
/// take a few minutes for billing enablement state to propagate to Firebase systems.
/// </summary>
public class CreateRequest : FirebaseRealtimeDatabaseBaseServiceRequest<Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance>
{
/// <summary>Constructs a new Create request.</summary>
public CreateRequest(Google.Apis.Services.IClientService service, Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance body, string parent) : base(service)
{
Parent = parent;
Body = body;
InitParameters();
}
/// <summary>
/// The parent project for which to create a database instance, in the form:
/// `projects/{project-number}/locations/{location-id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>The globally unique identifier of the database instance.</summary>
[Google.Apis.Util.RequestParameterAttribute("databaseId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string DatabaseId { get; set; }
/// <summary>When set to true, the request will be validated but not submitted.</summary>
[Google.Apis.Util.RequestParameterAttribute("validateOnly", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> ValidateOnly { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "create";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta/{+parent}/instances";
/// <summary>Initializes Create parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("databaseId", new Google.Apis.Discovery.Parameter
{
Name = "databaseId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("validateOnly", new Google.Apis.Discovery.Parameter
{
Name = "validateOnly",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Marks a DatabaseInstance to be deleted. The DatabaseInstance will be purged within 30 days. The
/// default database cannot be deleted. IDs for deleted database instances may never be recovered or
/// re-used. The Database may only be deleted if it is already in a DISABLED state.
/// </summary>
/// <param name="name">
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`
/// </param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Marks a DatabaseInstance to be deleted. The DatabaseInstance will be purged within 30 days. The
/// default database cannot be deleted. IDs for deleted database instances may never be recovered or
/// re-used. The Database may only be deleted if it is already in a DISABLED state.
/// </summary>
public class DeleteRequest : FirebaseRealtimeDatabaseBaseServiceRequest<Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
});
}
}
/// <summary>
/// Disables a DatabaseInstance. The database can be re-enabled later using ReenableDatabaseInstance.
/// When a database is disabled, all reads and writes are denied, including view access in the Firebase
/// console.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`
/// </param>
public virtual DisableRequest Disable(Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DisableDatabaseInstanceRequest body, string name)
{
return new DisableRequest(service, body, name);
}
/// <summary>
/// Disables a DatabaseInstance. The database can be re-enabled later using ReenableDatabaseInstance.
/// When a database is disabled, all reads and writes are denied, including view access in the Firebase
/// console.
/// </summary>
public class DisableRequest : FirebaseRealtimeDatabaseBaseServiceRequest<Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance>
{
/// <summary>Constructs a new Disable request.</summary>
public DisableRequest(Google.Apis.Services.IClientService service, Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DisableDatabaseInstanceRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DisableDatabaseInstanceRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "disable";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta/{+name}:disable";
/// <summary>Initializes Disable parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
});
}
}
/// <summary>Gets the DatabaseInstance identified by the specified resource name.</summary>
/// <param name="name">
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`. `database-id` is a
/// globally unique identifier across all parent collections. For convenience, this method allows you to
/// supply `-` as a wildcard character in place of specific collections under `projects` and
/// `locations`. The resulting wildcarding form of the method is:
/// `projects/-/locations/-/instances/{database-id}`.
/// </param>
public virtual GetRequest Get(string name)
{
return new GetRequest(service, name);
}
/// <summary>Gets the DatabaseInstance identified by the specified resource name.</summary>
public class GetRequest : FirebaseRealtimeDatabaseBaseServiceRequest<Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`. `database-id` is a
/// globally unique identifier across all parent collections. For convenience, this method allows
/// you to supply `-` as a wildcard character in place of specific collections under `projects` and
/// `locations`. The resulting wildcarding form of the method is:
/// `projects/-/locations/-/instances/{database-id}`.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta/{+name}";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
});
}
}
/// <summary>
/// Lists each DatabaseInstance associated with the specified parent project. The list items are
/// returned in no particular order, but will be a consistent view of the database instances when
/// additional requests are made with a `pageToken`. The resulting list contains instances in any STATE.
/// The list results may be stale by a few seconds. Use GetDatabaseInstance for consistent reads.
/// </summary>
/// <param name="parent">
/// The parent project for which to list database instances, in the form:
/// `projects/{project-number}/locations/{location-id}` To list across all locations, use a parent in
/// the form: `projects/{project-number}/locations/-`
/// </param>
public virtual ListRequest List(string parent)
{
return new ListRequest(service, parent);
}
/// <summary>
/// Lists each DatabaseInstance associated with the specified parent project. The list items are
/// returned in no particular order, but will be a consistent view of the database instances when
/// additional requests are made with a `pageToken`. The resulting list contains instances in any STATE.
/// The list results may be stale by a few seconds. Use GetDatabaseInstance for consistent reads.
/// </summary>
public class ListRequest : FirebaseRealtimeDatabaseBaseServiceRequest<Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.ListDatabaseInstancesResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string parent) : base(service)
{
Parent = parent;
InitParameters();
}
/// <summary>
/// The parent project for which to list database instances, in the form:
/// `projects/{project-number}/locations/{location-id}` To list across all locations, use a parent
/// in the form: `projects/{project-number}/locations/-`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("parent", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Parent { get; private set; }
/// <summary>
/// The maximum number of database instances to return in the response. The server may return fewer
/// than this at its discretion. If no value is specified (or too large a value is specified), then
/// the server will impose its own limit.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>
/// Token returned from a previous call to `ListDatabaseInstances` indicating where in the set of
/// database instances to resume listing.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta/{+parent}/instances";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("parent", new Google.Apis.Discovery.Parameter
{
Name = "parent",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+$",
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>
/// Enables a DatabaseInstance. The database must have been disabled previously using
/// DisableDatabaseInstance. The state of a successfully reenabled DatabaseInstance is ACTIVE.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`
/// </param>
public virtual ReenableRequest Reenable(Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.ReenableDatabaseInstanceRequest body, string name)
{
return new ReenableRequest(service, body, name);
}
/// <summary>
/// Enables a DatabaseInstance. The database must have been disabled previously using
/// DisableDatabaseInstance. The state of a successfully reenabled DatabaseInstance is ACTIVE.
/// </summary>
public class ReenableRequest : FirebaseRealtimeDatabaseBaseServiceRequest<Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.DatabaseInstance>
{
/// <summary>Constructs a new Reenable request.</summary>
public ReenableRequest(Google.Apis.Services.IClientService service, Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.ReenableDatabaseInstanceRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.FirebaseRealtimeDatabase.v1beta.Data.ReenableDatabaseInstanceRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "reenable";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1beta/{+name}:reenable";
/// <summary>Initializes Reenable parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^projects/[^/]+/locations/[^/]+/instances/[^/]+$",
});
}
}
}
}
}
}
namespace Google.Apis.FirebaseRealtimeDatabase.v1beta.Data
{
/// <summary>
/// Representation of a Realtime Database instance. Details on interacting with contents of a DatabaseInstance can
/// be found at: https://firebase.google.com/docs/database/rest/start.
/// </summary>
public class DatabaseInstance : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Immutable. The globally unique hostname of the database.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("databaseUrl")]
public virtual string DatabaseUrl { get; set; }
/// <summary>
/// The fully qualified resource name of the database instance, in the form:
/// `projects/{project-number}/locations/{location-id}/instances/{database-id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The resource name of the project this instance belongs to. For example: `projects/{project-number}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("project")]
public virtual string Project { get; set; }
/// <summary>The database's lifecycle state. Read-only.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("state")]
public virtual string State { get; set; }
/// <summary>
/// The database instance type. On creation only USER_DATABASE is allowed, which is also the default when
/// omitted.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request sent to the DisableDatabaseInstance method.</summary>
public class DisableDatabaseInstanceRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response from the ListDatabaseInstances method.</summary>
public class ListDatabaseInstancesResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>List of each DatabaseInstance that is in the parent Firebase project.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("instances")]
public virtual System.Collections.Generic.IList<DatabaseInstance> Instances { get; set; }
/// <summary>
/// If the result list is too large to fit in a single response, then a token is returned. If the string is
/// empty, then this response is the last page of results. This token can be used in a subsequent call to
/// `ListDatabaseInstances` to find the next group of database instances. Page tokens are short-lived and should
/// not be persisted.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The request sent to the ReenableDatabaseInstance method.</summary>
public class ReenableDatabaseInstanceRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using NuGet.Commands;
using NuGet.Common;
namespace NuGet
{
public class Program
{
private const string NuGetExtensionsKey = "NUGET_EXTENSIONS_PATH";
private static readonly string ExtensionsDirectoryRoot = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "NuGet", "Commands");
[Import]
public HelpCommand HelpCommand { get; set; }
[ImportMany]
public IEnumerable<ICommand> Commands { get; set; }
[Import]
public ICommandManager Manager { get; set; }
/// <summary>
/// Flag meant for unit tests that prevents command line extensions from being loaded.
/// </summary>
public static bool IgnoreExtensions { get; set; }
public static int Main(string[] args)
{
DebugHelper.WaitForAttach(ref args);
// This is to avoid applying weak event pattern usage, which breaks under Mono or restricted environments, e.g. Windows Azure Web Sites.
EnvironmentUtility.SetRunningFromCommandLine();
// Set output encoding to UTF8 if running on Unices. This is not needed on Windows.
if (Environment.OSVersion.Platform == PlatformID.Unix || Environment.OSVersion.Platform == PlatformID.MacOSX)
{
System.Console.OutputEncoding = System.Text.Encoding.UTF8;
}
var console = new Common.Console();
var fileSystem = new PhysicalFileSystem(Directory.GetCurrentDirectory());
Func<Exception, string> getErrorMessage = e => e.Message;
try
{
// Remove NuGet.exe.old
RemoveOldFile(fileSystem);
// Import Dependencies
var p = new Program();
p.Initialize(fileSystem, console);
// Add commands to the manager
foreach (ICommand cmd in p.Commands)
{
p.Manager.RegisterCommand(cmd);
}
CommandLineParser parser = new CommandLineParser(p.Manager);
// Parse the command
ICommand command = parser.ParseCommandLine(args) ?? p.HelpCommand;
// Fallback on the help command if we failed to parse a valid command
if (!ArgumentCountValid(command))
{
// Get the command name and add it to the argument list of the help command
string commandName = command.CommandAttribute.CommandName;
// Print invalid command then show help
console.WriteLine(LocalizedResourceManager.GetString("InvalidArguments"), commandName);
p.HelpCommand.ViewHelpForCommand(commandName);
}
else
{
SetConsoleInteractivity(console, command as Command);
// When we're detailed, get the whole exception including the stack
// This is useful for debugging errors.
if (console.Verbosity == Verbosity.Detailed)
{
getErrorMessage = e => e.ToString();
}
command.Execute();
}
}
catch (AggregateException exception)
{
string message;
Exception unwrappedEx = ExceptionUtility.Unwrap(exception);
if (unwrappedEx == exception)
{
// If the AggregateException contains more than one InnerException, it cannot be unwrapped. In which case, simply print out individual error messages
message = String.Join(Environment.NewLine, exception.InnerExceptions.Select(getErrorMessage).Distinct(StringComparer.CurrentCulture));
}
else
{
message = getErrorMessage(ExceptionUtility.Unwrap(exception));
}
console.WriteError(message);
return 1;
}
catch (Exception e)
{
console.WriteError(getErrorMessage(ExceptionUtility.Unwrap(e)));
return 1;
}
finally
{
OptimizedZipPackage.PurgeCache();
}
return 0;
}
private void Initialize(IFileSystem fileSystem, IConsole console)
{
using (var catalog = new AggregateCatalog(new AssemblyCatalog(GetType().Assembly)))
{
if (!IgnoreExtensions)
{
AddExtensionsToCatalog(catalog, console);
}
using (var container = new CompositionContainer(catalog))
{
container.ComposeExportedValue<IConsole>(console);
container.ComposeExportedValue<IPackageRepositoryFactory>(new NuGet.Common.CommandLineRepositoryFactory(console));
container.ComposeExportedValue<IFileSystem>(fileSystem);
container.ComposeParts(this);
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We don't want to block the exe from usage if anything failed")]
internal static void RemoveOldFile(IFileSystem fileSystem)
{
string oldFile = typeof(Program).Assembly.Location + ".old";
try
{
if (fileSystem.FileExists(oldFile))
{
fileSystem.DeleteFile(oldFile);
}
}
catch
{
// We don't want to block the exe from usage if anything failed
}
}
public static bool ArgumentCountValid(ICommand command)
{
CommandAttribute attribute = command.CommandAttribute;
return command.Arguments.Count >= attribute.MinArgs &&
command.Arguments.Count <= attribute.MaxArgs;
}
private static void AddExtensionsToCatalog(AggregateCatalog catalog, IConsole console)
{
IEnumerable<string> directories = new[] { ExtensionsDirectoryRoot };
var customExtensions = Environment.GetEnvironmentVariable(NuGetExtensionsKey);
if (!String.IsNullOrEmpty(customExtensions))
{
// Add all directories from the environment variable if available.
directories = directories.Concat(customExtensions.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries));
}
IEnumerable<string> files;
foreach (var directory in directories)
{
if (Directory.Exists(directory))
{
files = Directory.EnumerateFiles(directory, "*.dll", SearchOption.AllDirectories);
RegisterExtensions(catalog, files, console);
}
}
// Ideally we want to look for all files. However, using MEF to identify imports results in assemblies being loaded and locked by our App Domain
// which could be slow, might affect people's build systems and among other things breaks our build.
// Consequently, we'll use a convention - only binaries ending in the name Extensions would be loaded.
var nugetDirectory = Path.GetDirectoryName(typeof(Program).Assembly.Location);
files = Directory.EnumerateFiles(nugetDirectory, "*Extensions.dll");
RegisterExtensions(catalog, files, console);
}
private static void RegisterExtensions(AggregateCatalog catalog, IEnumerable<string> enumerateFiles, IConsole console)
{
foreach (var item in enumerateFiles)
{
try
{
catalog.Catalogs.Add(new AssemblyCatalog(item));
}
catch (BadImageFormatException ex)
{
// Ignore if the dll wasn't a valid assembly
console.WriteWarning(ex.Message);
}
catch (FileLoadException ex)
{
// Ignore if we couldn't load the assembly.
console.WriteWarning(ex.Message);
}
}
}
private static void SetConsoleInteractivity(IConsole console, Command command)
{
// Global environment variable to prevent the exe for prompting for credentials
string globalSwitch = Environment.GetEnvironmentVariable("NUGET_EXE_NO_PROMPT");
// When running from inside VS, no input is available to our executable locking up VS.
// VS sets up a couple of environment variables one of which is named VisualStudioVersion.
// Every time this is setup, we will just fail.
// TODO: Remove this in next iteration. This is meant for short-term backwards compat.
string vsSwitch = Environment.GetEnvironmentVariable("VisualStudioVersion");
console.IsNonInteractive = !String.IsNullOrEmpty(globalSwitch) ||
!String.IsNullOrEmpty(vsSwitch) ||
(command != null && command.NonInteractive);
if (command != null)
{
console.Verbosity = command.Verbosity;
}
}
}
}
| |
using System;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using NuGet.Test.Mocks;
using NuGet.VisualStudio;
using NuGet.VisualStudio.Test;
using EnvDTE;
namespace NuGet.Test.VisualStudio {
[TestClass]
public class VsPackageManagerTest {
[TestMethod]
public void InstallPackageInstallsIntoProjectAndPackageManager() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>().Object;
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
var pathResolver = new DefaultPackagePathResolver(projectSystem);
var projectManager = new ProjectManager(localRepository, pathResolver, new MockProjectSystem(), new MockPackageRepository());
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, projectSystem, localRepository, new Mock<IRecentPackageRepository>().Object);
var package = PackageUtility.CreatePackage("foo", "1.0", new[] { "hello" });
sourceRepository.AddPackage(package);
// Act
packageManager.InstallPackage(projectManager, "foo", new Version("1.0"), ignoreDependencies: false, logger: NullLogger.Instance);
// Assert
Assert.IsTrue(packageManager.LocalRepository.Exists(package));
Assert.IsTrue(projectManager.LocalRepository.Exists(package));
}
[TestMethod]
public void InstallPackageWithOperationsExecuteAllOperations() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>().Object;
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
var pathResolver = new DefaultPackagePathResolver(projectSystem);
var projectManager = new ProjectManager(localRepository, pathResolver, new MockProjectSystem(), new MockPackageRepository());
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, projectSystem, localRepository, new Mock<IRecentPackageRepository>().Object);
var package = PackageUtility.CreatePackage("foo", "1.0", new[] { "hello" }, dependencies: new PackageDependency[] { new PackageDependency("bar") });
sourceRepository.AddPackage(package);
var package2 = PackageUtility.CreatePackage("bar", "2.0", new[] { "world" });
sourceRepository.AddPackage(package2);
var package3 = PackageUtility.CreatePackage("awesome", "1.0", new[] { "candy" });
localRepository.AddPackage(package3);
var operations = new PackageOperation[] {
new PackageOperation(package, PackageAction.Install),
new PackageOperation(package2, PackageAction.Install),
new PackageOperation(package3, PackageAction.Uninstall)
};
// Act
packageManager.InstallPackage(projectManager, package, operations, ignoreDependencies: false, logger: NullLogger.Instance);
// Assert
Assert.IsTrue(packageManager.LocalRepository.Exists(package));
Assert.IsTrue(packageManager.LocalRepository.Exists(package2));
Assert.IsTrue(!packageManager.LocalRepository.Exists(package3));
Assert.IsTrue(projectManager.LocalRepository.Exists(package));
Assert.IsTrue(projectManager.LocalRepository.Exists(package2));
}
[TestMethod]
public void InstallPackgeWithNullProjectManagerOnlyInstallsIntoPackageManager() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>().Object;
var sourceRepository = new MockPackageRepository();
var projectSystem = new MockProjectSystem();
var pathResolver = new DefaultPackagePathResolver(projectSystem);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, projectSystem, localRepository, new Mock<IRecentPackageRepository>().Object);
var package = PackageUtility.CreatePackage("foo", "1.0", new[] { "hello" });
sourceRepository.AddPackage(package);
// Act
packageManager.InstallPackage((IProjectManager)null, "foo", new Version("1.0"), ignoreDependencies: false, logger: NullLogger.Instance);
// Assert
Assert.IsTrue(packageManager.LocalRepository.Exists(package));
}
[TestMethod]
public void UninstallProjectLevelPackageThrowsIfPackageIsReferenced() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
localRepository.Setup(m => m.IsReferenced("foo", It.IsAny<Version>())).Returns(true);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
var package = PackageUtility.CreatePackage("foo", "1.0", new[] { "hello" });
localRepository.Object.AddPackage(package);
sourceRepository.AddPackage(package);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
var projectManager = new ProjectManager(localRepository.Object, pathResolver, new MockProjectSystem(), new MockPackageRepository());
// Act
ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UninstallPackage(projectManager, "foo", version: null, forceRemove: false, removeDependencies: false, logger: NullLogger.Instance), @"Unable to find package 'foo 1.0' in 'C:\MockFileSystem\'.");
}
[TestMethod]
public void UninstallProjectLevelPackageWithNoProjectManagerThrows() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
localRepository.Setup(m => m.IsReferenced("foo", It.IsAny<Version>())).Returns(true);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
var package = PackageUtility.CreatePackage("foo", "1.0", new[] { "hello" });
localRepository.Object.AddPackage(package);
sourceRepository.AddPackage(package);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
// Act
ExceptionAssert.Throws<InvalidOperationException>(() => packageManager.UninstallPackage(null, "foo", version: null, forceRemove: false, removeDependencies: false, logger: NullLogger.Instance), "No project was specified.");
}
[TestMethod]
public void UninstallPackageRemovesPackageIfPackageIsNotReferenced() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
localRepository.Setup(m => m.IsReferenced("foo", It.IsAny<Version>())).Returns(false);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
var package = PackageUtility.CreatePackage("foo", "1.0", new[] { "hello" });
localRepository.Object.AddPackage(package);
sourceRepository.AddPackage(package);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
// Act
packageManager.UninstallPackage(null, "foo", version: null, forceRemove: false, removeDependencies: false, logger: NullLogger.Instance);
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(package));
}
[TestMethod]
public void UpdatePackageRemovesPackageIfPackageIsNotReferenced() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
localRepository.Setup(m => m.IsReferenced("A", new Version("1.0"))).Returns(false);
var projectRepository = new MockProjectPackageRepository(localRepository.Object);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
var A10 = PackageUtility.CreatePackage("A", "1.0", new[] { "hello" });
var A20 = PackageUtility.CreatePackage("A", "2.0", new[] { "hello" });
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
localRepository.Object.AddPackage(A10);
localRepository.Object.AddPackage(A20);
projectRepository.Add(A10);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
var projectManager = new ProjectManager(localRepository.Object, pathResolver, new MockProjectSystem(), projectRepository);
// Act
packageManager.UpdatePackage(projectManager, "A", version: null, updateDependencies: true, logger: NullLogger.Instance);
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(A10));
}
[TestMethod]
public void UpdatePackageDoesNotRemovesPackageIfPackageIsReferenced() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
localRepository.Setup(m => m.IsReferenced("A", new Version("1.0"))).Returns(true);
var projectRepository = new MockProjectPackageRepository(localRepository.Object);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
var A10 = PackageUtility.CreatePackage("A", "1.0", new[] { "hello" });
var A20 = PackageUtility.CreatePackage("A", "2.0", new[] { "hello" });
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
localRepository.Object.AddPackage(A10);
localRepository.Object.AddPackage(A20);
projectRepository.Add(A10);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
var projectManager = new ProjectManager(localRepository.Object, pathResolver, new MockProjectSystem(), projectRepository);
// Act
packageManager.UpdatePackage(projectManager, "A", version: null, updateDependencies: true, logger: NullLogger.Instance);
// Assert
Assert.IsTrue(packageManager.LocalRepository.Exists(A10));
}
[TestMethod]
public void UpdatePackageWithSharedDependency() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
var projectRepository = new MockProjectPackageRepository(localRepository.Object);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
// A1 -> B1
// A2 -> B2
// F1 -> G1
// G1 -> B1
var A10 = PackageUtility.CreatePackage("A", "1.0", new[] { "hello" }, dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("1.0")) });
var A20 = PackageUtility.CreatePackage("A", "2.0", new[] { "hello" }, dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("2.0")) });
var B10 = PackageUtility.CreatePackage("B", "1.0", new[] { "hello" });
var B20 = PackageUtility.CreatePackage("B", "2.0", new[] { "hello" });
var F10 = PackageUtility.CreatePackage("F", "1.0", new[] { "hello" }, dependencies: new[] { new PackageDependency("G", VersionUtility.ParseVersionSpec("1.0")) });
var G10 = PackageUtility.CreatePackage("G", "1.0", new[] { "hello" }, dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("1.0")) });
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B10);
sourceRepository.AddPackage(B20);
sourceRepository.AddPackage(F10);
sourceRepository.AddPackage(G10);
localRepository.Object.AddPackage(A10);
localRepository.Object.AddPackage(A20);
localRepository.Object.AddPackage(B10);
localRepository.Object.AddPackage(B20);
localRepository.Object.AddPackage(F10);
localRepository.Object.AddPackage(G10);
projectRepository.Add(A10);
projectRepository.Add(B10);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
var projectManager = new ProjectManager(localRepository.Object, pathResolver, new MockProjectSystem(), projectRepository);
// Act
packageManager.UpdatePackage(projectManager, "A", version: null, updateDependencies: true, logger: NullLogger.Instance);
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(A10));
Assert.IsFalse(packageManager.LocalRepository.Exists(B10));
Assert.IsTrue(packageManager.LocalRepository.Exists(A20));
Assert.IsTrue(packageManager.LocalRepository.Exists(B20));
Assert.IsTrue(packageManager.LocalRepository.Exists(F10));
Assert.IsTrue(packageManager.LocalRepository.Exists(G10));
}
[TestMethod]
public void UpdatePackageWithSameDependency() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
var projectRepository = new MockProjectPackageRepository(localRepository.Object);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var projectSystem = new MockProjectSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
// A1 -> B1
// A2 -> B1
var A10 = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { "A1.dll" }, dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("1.0")) });
var A20 = PackageUtility.CreatePackage("A", "2.0", assemblyReferences: new[] { "A2.dll" }, dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("1.0")) });
var B10 = PackageUtility.CreatePackage("B", "1.0", assemblyReferences: new[] { "B1.dll" });
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B10);
localRepository.Object.AddPackage(A10);
localRepository.Object.AddPackage(A20);
localRepository.Object.AddPackage(B10);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
var projectManager = new ProjectManager(localRepository.Object, pathResolver, projectSystem, projectRepository);
projectManager.AddPackageReference("A", new Version("1.0"));
// Act
packageManager.UpdatePackage(projectManager, "A", version: null, updateDependencies: true, logger: NullLogger.Instance);
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(A10));
Assert.IsFalse(projectSystem.ReferenceExists("A1.dll"));
Assert.IsTrue(packageManager.LocalRepository.Exists(B10));
Assert.IsTrue(projectSystem.ReferenceExists("B1.dll"));
Assert.IsTrue(packageManager.LocalRepository.Exists(A20));
Assert.IsTrue(projectSystem.ReferenceExists("A2.dll"));
}
[TestMethod]
public void UpdatePackageNewVersionOfPackageHasLessDependencies() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
var projectRepository = new MockProjectPackageRepository(localRepository.Object);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var projectSystem = new MockProjectSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
// A1 -> B1
// A2
var A10 = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { "A1.dll" }, dependencies: new[] { new PackageDependency("B", VersionUtility.ParseVersionSpec("1.0")) });
var A20 = PackageUtility.CreatePackage("A", "2.0", assemblyReferences: new[] { "A2.dll" });
var B10 = PackageUtility.CreatePackage("B", "1.0", assemblyReferences: new[] { "B1.dll" });
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B10);
localRepository.Object.AddPackage(A10);
localRepository.Object.AddPackage(A20);
localRepository.Object.AddPackage(B10);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
var projectManager = new ProjectManager(localRepository.Object, pathResolver, projectSystem, projectRepository);
projectManager.AddPackageReference("A", new Version("1.0"));
// Act
packageManager.UpdatePackage(projectManager, "A", version: null, updateDependencies: true, logger: NullLogger.Instance);
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(A10));
Assert.IsFalse(projectSystem.ReferenceExists("A1.dll"));
Assert.IsFalse(packageManager.LocalRepository.Exists(B10));
Assert.IsFalse(projectSystem.ReferenceExists("B1.dll"));
Assert.IsTrue(packageManager.LocalRepository.Exists(A20));
Assert.IsTrue(projectSystem.ReferenceExists("A2.dll"));
}
[TestMethod]
public void UpdatePackageWithMultipleSharedDependencies() {
// Arrange
var localRepository = new Mock<MockPackageRepository>() { CallBase = true }.As<ISharedPackageRepository>();
var projectRepository = new MockProjectPackageRepository(localRepository.Object);
var sourceRepository = new MockPackageRepository();
var fileSystem = new MockFileSystem();
var projectSystem = new MockProjectSystem();
var pathResolver = new DefaultPackagePathResolver(fileSystem);
// A1 -> B1, C1
// A2 -> B1
var A10 = PackageUtility.CreatePackage("A", "1.0", assemblyReferences: new[] { "A1.dll" }, dependencies: new[] {
new PackageDependency("B", VersionUtility.ParseVersionSpec("1.0")),
new PackageDependency("C", VersionUtility.ParseVersionSpec("1.0")),
});
var A20 = PackageUtility.CreatePackage("A", "2.0", assemblyReferences: new[] { "A2.dll" }, dependencies: new[] {
new PackageDependency("B", VersionUtility.ParseVersionSpec("1.0"))
});
var B10 = PackageUtility.CreatePackage("B", "1.0", assemblyReferences: new[] { "B1.dll" });
var C10 = PackageUtility.CreatePackage("C", "1.0", assemblyReferences: new[] { "C1.dll" });
sourceRepository.AddPackage(A10);
sourceRepository.AddPackage(A20);
sourceRepository.AddPackage(B10);
sourceRepository.AddPackage(C10);
localRepository.Object.AddPackage(A10);
localRepository.Object.AddPackage(A20);
localRepository.Object.AddPackage(B10);
localRepository.Object.AddPackage(C10);
var packageManager = new VsPackageManager(TestUtils.GetSolutionManager(), sourceRepository, fileSystem, localRepository.Object, new Mock<IRecentPackageRepository>().Object);
var projectManager = new ProjectManager(localRepository.Object, pathResolver, projectSystem, projectRepository);
projectManager.AddPackageReference("A", new Version("1.0"));
// Act
packageManager.UpdatePackage(projectManager, "A", version: null, updateDependencies: true, logger: NullLogger.Instance);
// Assert
Assert.IsFalse(packageManager.LocalRepository.Exists(A10));
Assert.IsFalse(projectSystem.ReferenceExists("A1.dll"));
Assert.IsFalse(packageManager.LocalRepository.Exists(C10));
Assert.IsFalse(projectSystem.ReferenceExists("C1.dll"));
Assert.IsTrue(packageManager.LocalRepository.Exists(B10));
Assert.IsTrue(projectSystem.ReferenceExists("B1.dll"));
Assert.IsTrue(packageManager.LocalRepository.Exists(A20));
Assert.IsTrue(projectSystem.ReferenceExists("A2.dll"));
}
// This repository better simulates what happens when we're running the package manager in vs
private class MockProjectPackageRepository : MockPackageRepository {
private readonly IPackageRepository _parent;
public MockProjectPackageRepository(IPackageRepository parent) {
_parent = parent;
}
public override IQueryable<IPackage> GetPackages() {
return base.GetPackages().Where(p => _parent.Exists(p));
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Payroll.WebApi.Areas.HelpPage.ModelDescriptions;
using Payroll.WebApi.Areas.HelpPage.Models;
namespace Payroll.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// dnlib: See LICENSE.txt for more info
using System;
using System.Collections.Generic;
using dnlib.DotNet.Pdb.Symbols;
using dnlib.IO;
namespace dnlib.DotNet.Pdb.Managed {
sealed class DbiModule {
public DbiModule() {
Functions = new List<DbiFunction>();
Documents = new List<DbiDocument>();
}
public ushort StreamId { get; private set; }
uint cbSyms;
uint cbOldLines;
uint cbLines;
public string ModuleName { get; private set; }
public string ObjectName { get; private set; }
public List<DbiFunction> Functions { get; private set; }
public List<DbiDocument> Documents { get; private set; }
public void Read(ref DataReader reader) {
reader.Position += 34;
StreamId = reader.ReadUInt16();
cbSyms = reader.ReadUInt32();
cbOldLines = reader.ReadUInt32();
cbLines = reader.ReadUInt32();
reader.Position += 16;
if ((int)cbSyms < 0)
cbSyms = 0;
if ((int)cbOldLines < 0)
cbOldLines = 0;
if ((int)cbLines < 0)
cbLines = 0;
ModuleName = PdbReader.ReadCString(ref reader);
ObjectName = PdbReader.ReadCString(ref reader);
reader.Position = (reader.Position + 3) & (~3U);
}
public void LoadFunctions(PdbReader pdbReader, ref DataReader reader) {
reader.Position = 0;
ReadFunctions(reader.Slice(reader.Position, cbSyms));
if (Functions.Count > 0) {
reader.Position += cbSyms + cbOldLines;
ReadLines(pdbReader, reader.Slice(reader.Position, cbLines));
}
}
void ReadFunctions(DataReader reader) {
if (reader.ReadUInt32() != 4)
throw new PdbException("Invalid signature");
while (reader.Position < reader.Length) {
var size = reader.ReadUInt16();
var begin = reader.Position;
var end = begin + size;
var type = (SymbolType)reader.ReadUInt16();
switch (type) {
case SymbolType.S_GMANPROC:
case SymbolType.S_LMANPROC:
var func = new DbiFunction();
func.Read(ref reader, end);
Functions.Add(func);
break;
default:
reader.Position = end;
break;
}
}
}
void ReadLines(PdbReader pdbReader, DataReader reader) {
var docs = new Dictionary<uint, DbiDocument>();
reader.Position = 0;
while (reader.Position < reader.Length) {
var sig = (ModuleStreamType)reader.ReadUInt32();
var size = reader.ReadUInt32();
var begin = reader.Position;
var end = (begin + size + 3) & ~3U;
if (sig == ModuleStreamType.FileInfo)
ReadFiles(pdbReader, docs, ref reader, end);
reader.Position = end;
}
var sortedFuncs = new DbiFunction[Functions.Count];
Functions.CopyTo(sortedFuncs, 0);
Array.Sort(sortedFuncs, (a, b) => a.Address.CompareTo(b.Address));
reader.Position = 0;
while (reader.Position < reader.Length) {
var sig = (ModuleStreamType)reader.ReadUInt32();
var size = reader.ReadUInt32();
var begin = reader.Position;
var end = begin + size;
if (sig == ModuleStreamType.Lines)
ReadLines(sortedFuncs, docs, ref reader, end);
reader.Position = end;
}
}
void ReadFiles(PdbReader pdbReader, Dictionary<uint, DbiDocument> documents, ref DataReader reader, uint end) {
var begin = reader.Position;
while (reader.Position < end) {
var id = reader.Position - begin;
var nameId = reader.ReadUInt32();
var len = reader.ReadByte();
/*var type = */reader.ReadByte();
var doc = pdbReader.GetDocument(nameId);
documents.Add(id, doc);
reader.Position += len;
reader.Position = (reader.Position + 3) & (~3U);
}
}
void ReadLines(DbiFunction[] funcs, Dictionary<uint, DbiDocument> documents, ref DataReader reader, uint end) {
var address = PdbAddress.ReadAddress(ref reader);
int first = 0;
int last = funcs.Length - 1;
int found = -1;
while (first <= last) {
var index = first + ((last - first) >> 1);
var addr = funcs[index].Address;
if (addr < address) {
first = index + 1;
}
else if (addr > address) {
last = index - 1;
}
else {
found = index;
break;
}
}
if (found == -1)
return;
var flags = reader.ReadUInt16();
reader.Position += 4;
if (funcs[found].Lines is null) {
while (found > 0) {
var prevFunc = funcs[found - 1];
if (prevFunc is not null || prevFunc.Address != address)
break;
found--;
}
}
else {
while (found < funcs.Length - 1 && funcs[found] is not null) {
var nextFunc = funcs[found + 1];
if (nextFunc.Address != address)
break;
found++;
}
}
var func = funcs[found];
if (func.Lines is not null)
return;
func.Lines = new List<SymbolSequencePoint>();
while (reader.Position < end) {
var document = documents[reader.ReadUInt32()];
var count = reader.ReadUInt32();
reader.Position += 4;
const int LINE_ENTRY_SIZE = 8;
const int COL_ENTRY_SIZE = 4;
var lineTablePos = reader.Position;
var colTablePos = reader.Position + count * LINE_ENTRY_SIZE;
for (uint i = 0; i < count; i++) {
reader.Position = lineTablePos + i * LINE_ENTRY_SIZE;
var line = new SymbolSequencePoint {
Document = document
};
line.Offset = reader.ReadInt32();
var lineFlags = reader.ReadUInt32();
line.Line = (int)(lineFlags & 0x00ffffff);
line.EndLine = line.Line + (int)((lineFlags >> 24) & 0x7F);
if ((flags & 1) != 0) {
reader.Position = colTablePos + i * COL_ENTRY_SIZE;
line.Column = reader.ReadUInt16();
line.EndColumn = reader.ReadUInt16();
}
func.Lines.Add(line);
}
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. 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.Globalization;
using System.Linq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class CommonCommandLineParserTests : TestBase
{
private const int EN_US = 1033;
private void VerifyCommandLineSplitter(string commandLine, string[] expected)
{
string[] actual = CommandLineSplitter.SplitCommandLine(commandLine);
Assert.Equal(expected.Length, actual.Length);
for (int i = 0; i < actual.Length; ++i)
{
Assert.Equal(expected[i], actual[i]);
}
}
private RuleSet ParseRuleSet(string source, params string[] otherSources)
{
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(source);
for (int i = 1; i <= otherSources.Length; i++)
{
var newFile = dir.CreateFile("file" + i + ".ruleset");
newFile.WriteAllText(otherSources[i - 1]);
}
if (otherSources.Length != 0)
{
return RuleSet.LoadEffectiveRuleSetFromFile(file.Path);
}
return RuleSetProcessor.LoadFromFile(file.Path);
}
private void VerifyRuleSetError(string source, string message, bool locSpecific = true, string locMessage = "", params string[] otherSources)
{
try
{
ParseRuleSet(source, otherSources);
}
catch (Exception e)
{
if (CultureInfo.CurrentCulture.LCID == EN_US || CultureInfo.CurrentUICulture.LCID == EN_US || CultureInfo.CurrentCulture == CultureInfo.InvariantCulture || CultureInfo.CurrentUICulture == CultureInfo.InvariantCulture)
{
Assert.Equal(message, e.Message);
}
else if (locSpecific)
{
if (locMessage != "")
Assert.Contains(locMessage, e.Message);
else
Assert.Equal(message, e.Message);
}
return;
}
Assert.True(false, "Didn't return an error");
}
[Fact]
public void TestCommandLineSplitter()
{
VerifyCommandLineSplitter("", new string[0]);
VerifyCommandLineSplitter(" \t ", new string[0]);
VerifyCommandLineSplitter(" abc\tdef baz quuz ", new string[] {"abc", "def", "baz", "quuz"});
VerifyCommandLineSplitter(@" ""abc def"" fi""ddle dee de""e ""hi there ""dude he""llo there"" ",
new string[] { @"abc def", @"fi""ddle dee de""e", @"""hi there ""dude", @"he""llo there""" });
VerifyCommandLineSplitter(@" ""abc def \"" baz quuz"" ""\""straw berry"" fi\""zz \""buzz fizzbuzz",
new string[] { @"abc def "" baz quuz", @"""straw berry", @"fi""zz", @"""buzz", @"fizzbuzz"});
VerifyCommandLineSplitter(@" \\""abc def"" \\\""abc def"" ",
new string[] { @"\""abc def""", @"\""abc", @"def""" });
VerifyCommandLineSplitter(@" \\\\""abc def"" \\\\\""abc def"" ",
new string[] { @"\\""abc def""", @"\\""abc", @"def""" });
}
[Fact]
public void TestRuleSetParsingDuplicateRule()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1012"" Action=""Warning"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
</RuleSet>";
VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "There is a duplicate key sequence 'CA1012' for the 'UniqueRuleName' key or unique identity constraint."));
VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "There is a duplicate key sequence 'CA1012' for the 'UniqueRuleName' key or unique identity constraint."));
}
[Fact]
public void TestRuleSetParsingDuplicateRule2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
<Rule Id=""CA1013"" Action=""None"" />
</Rules>
</RuleSet>";
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetHasDuplicateRules, "CA1012", "Error", "Warn"), locSpecific: false);
}
[Fact]
public void TestRuleSetParsingDuplicateRule3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1013"" Action=""None"" />
</Rules>
</RuleSet>";
var ruleSet = ParseRuleSet(source);
Assert.Equal(expected: ReportDiagnostic.Error, actual: ruleSet.SpecificDiagnosticOptions["CA1012"]);
}
[Fact]
public void TestRuleSetParsingDuplicateRuleSet()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
<RuleSet Name=""Ruleset2"" Description=""Test"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
VerifyRuleSetError(source, "There are multiple root elements. Line 8, position 2.", false);
}
[Fact]
public void TestRuleSetParsingIncludeAll1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetParsingIncludeAll2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetParsingWithIncludeOfSameFile()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""a.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, new string[] { "" });
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Equal(1, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count());
}
[Fact]
public void TestRuleSetParsingWithMutualIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""a.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Equal(2, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count());
}
[Fact]
public void TestRuleSetParsingWithSiblingIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Equal(3, RuleSet.GetEffectiveIncludesFromFile(ruleSet.FilePath).Count());
}
[Fact]
public void TestRuleSetParsingIncludeAll3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
VerifyRuleSetError(source, () => string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The 'Action' attribute is invalid - The value 'Default' is invalid according to its datatype 'TIncludeAllAction' - The Enumeration constraint failed."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Id' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Action' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'AnalyzerId' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute4()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"">
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'RuleNamespace' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute5()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'ToolsVersion' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRulesMissingAttribute6()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The required attribute 'Name' is missing."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetParsingRules()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
<Rule Id=""CA1015"" Action=""Info"" />
<Rule Id=""CA1016"" Action=""Hidden"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1012"], ReportDiagnostic.Error);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1013"], ReportDiagnostic.Warn);
Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1014"], ReportDiagnostic.Suppress);
Assert.Contains("CA1015", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1015"], ReportDiagnostic.Info);
Assert.Contains("CA1016", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ruleSet.SpecificDiagnosticOptions["CA1016"], ReportDiagnostic.Hidden);
}
[Fact]
public void TestRuleSetParsingRules2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Default"" />
<Rule Id=""CA1013"" Action=""Warning"" />
<Rule Id=""CA1014"" Action=""None"" />
</Rules>
</RuleSet>
";
string locMessage = string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "");
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "The 'Action' attribute is invalid - The value 'Default' is invalid according to its datatype 'TRuleAction' - The Enumeration constraint failed."), locMessage: locMessage);
}
[Fact]
public void TestRuleSetInclude()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""foo.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source);
Assert.True(ruleSet.Includes.Count() == 1);
Assert.Equal(ruleSet.Includes.First().Action, ReportDiagnostic.Default);
Assert.Equal(ruleSet.Includes.First().IncludePath, "foo.ruleset");
}
[WorkItem(156)]
[Fact(Skip = "156")]
public void TestRuleSetInclude1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""foo.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
VerifyRuleSetError(source, string.Format(CodeAnalysisResources.InvalidRuleSetInclude, "foo.ruleset", string.Format(CodeAnalysisResources.FailedToResolveRuleSetName, "foo.ruleset")), otherSources: new string[] {""});
}
[Fact]
public void TestRuleSetInclude2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Hidden"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Hidden, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Info"" />
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Info, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeGlobalStrict3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Include Path=""file1.ruleset"" Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeRecursiveIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1014"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1013"]);
Assert.Contains("CA1014", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1014"]);
}
[Fact]
public void TestRuleSetIncludeSpecificStrict1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
// CA1012's value in source wins.
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
}
[Fact]
public void TestRuleSetIncludeSpecificStrict2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Error"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
// CA1012's value in source still wins.
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
}
[Fact]
public void TestRuleSetIncludeSpecificStrict3()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Default"" />
<Include Path=""file2.ruleset"" Action=""Default"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Error"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
// CA1013's value in source2 wins.
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeEffectiveAction()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""None"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.DoesNotContain("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
}
[Fact]
public void TestRuleSetIncludeEffectiveAction1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
Assert.Equal(ReportDiagnostic.Default, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionGlobal1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Error, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionGlobal2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<IncludeAll Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.GeneralDiagnosticOption);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionSpecific1()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""None"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestRuleSetIncludeEffectiveActionSpecific2()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var ruleSet = ParseRuleSet(source, source1);
Assert.Contains("CA1012", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1012"]);
Assert.Contains("CA1013", ruleSet.SpecificDiagnosticOptions.Keys);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA1013"]);
}
[Fact]
public void TestAllCombinations()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Error"" />
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1000"" Action=""Warning"" />
<Rule Id=""CA1001"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""None"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
<Rule Id=""CA2119"" Action=""None"" />
<Rule Id=""CA2104"" Action=""Error"" />
<Rule Id=""CA2105"" Action=""Warning"" />
</Rules>
</RuleSet>";
var ruleSet = ParseRuleSet(source, source1, source2);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1000"]);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA1001"]);
Assert.Equal(ReportDiagnostic.Error, ruleSet.SpecificDiagnosticOptions["CA2100"]);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2104"]);
Assert.Equal(ReportDiagnostic.Warn, ruleSet.SpecificDiagnosticOptions["CA2105"]);
Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2111"]);
Assert.Equal(ReportDiagnostic.Suppress, ruleSet.SpecificDiagnosticOptions["CA2119"]);
}
[Fact]
public void TestRuleSetIncludeError()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string source1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset2"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1013"" Action=""Default"" />
</Rules>
</RuleSet>
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(source);
var newFile = dir.CreateFile("file1.ruleset");
newFile.WriteAllText(source1);
try
{
RuleSet.LoadEffectiveRuleSetFromFile(file.Path);
Assert.True(false, "Didn't throw an exception");
}
catch (InvalidRuleSetException e)
{
Assert.Contains(string.Format(CodeAnalysisResources.InvalidRuleSetInclude, newFile.Path, string.Format(CodeAnalysisResources.RuleSetSchemaViolation, "")), e.Message);
}
}
[Fact]
public void GetEffectiveIncludes_NoIncludes()
{
string source = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""Ruleset1"" Description=""Test"" ToolsVersion=""12.0"" >
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1012"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(source);
var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path);
Assert.Equal(expected: 1, actual: includePaths.Length);
Assert.Equal(expected: file.Path, actual: includePaths[0]);
}
[Fact]
public void GetEffectiveIncludes_OneLevel()
{
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1000"" Action=""Warning"" />
<Rule Id=""CA1001"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""None"" />
</Rules>
</RuleSet>
";
string includeSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
</Rules>
</RuleSet>
";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(ruleSetSource);
var include = dir.CreateFile("file1.ruleset");
include.WriteAllText(includeSource);
var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path);
Assert.Equal(expected: 2, actual: includePaths.Length);
Assert.Equal(expected: file.Path, actual: includePaths[0]);
Assert.Equal(expected: include.Path, actual: includePaths[1]);
}
[Fact]
public void GetEffectiveIncludes_TwoLevels()
{
string ruleSetSource = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set1"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file1.ruleset"" Action=""Error"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA1000"" Action=""Warning"" />
<Rule Id=""CA1001"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""None"" />
</Rules>
</RuleSet>
";
string includeSource1 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set2"" Description=""Test"" ToolsVersion=""12.0"">
<Include Path=""file2.ruleset"" Action=""Warning"" />
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
</Rules>
</RuleSet>
";
string includeSource2 = @"<?xml version=""1.0"" encoding=""utf-8""?>
<RuleSet Name=""New Rule Set3"" Description=""Test"" ToolsVersion=""12.0"">
<Rules AnalyzerId=""Microsoft.Analyzers.ManagedCodeAnalysis"" RuleNamespace=""Microsoft.Rules.Managed"">
<Rule Id=""CA2100"" Action=""Warning"" />
<Rule Id=""CA2111"" Action=""Warning"" />
<Rule Id=""CA2119"" Action=""None"" />
<Rule Id=""CA2104"" Action=""Error"" />
<Rule Id=""CA2105"" Action=""Warning"" />
</Rules>
</RuleSet>";
var dir = Temp.CreateDirectory();
var file = dir.CreateFile("a.ruleset");
file.WriteAllText(ruleSetSource);
var include1 = dir.CreateFile("file1.ruleset");
include1.WriteAllText(includeSource1);
var include2 = dir.CreateFile("file2.ruleset");
include2.WriteAllText(includeSource2);
var includePaths = RuleSet.GetEffectiveIncludesFromFile(file.Path);
Assert.Equal(expected: 3, actual: includePaths.Length);
Assert.Equal(expected: file.Path, actual: includePaths[0]);
Assert.Equal(expected: include1.Path, actual: includePaths[1]);
Assert.Equal(expected: include2.Path, actual: includePaths[2]);
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
namespace WebsitePanel.Providers.FTP.IIs70.Config
{
using Microsoft.Web.Administration;
using System;
using System.Runtime.InteropServices;
using System.Threading;
internal class FtpSite : ConfigurationElement
{
private ConnectionsElement _connections;
private DataChannelSecurityElement _dataChannelSecurity;
private DirectoryBrowseElement _directoryBrowse;
private FileHandlingElement _fileHandling;
private FirewallElement _firewall;
private ConfigurationMethod _flushLogMethod;
private LogFileElement _logFile;
private MessagesElement _messages;
private SecurityElement _security;
private SessionCollection _sessions;
private ConfigurationMethod _startMethod;
private ConfigurationMethod _stopMethod;
private UserIsolationElement _userIsolation;
public const int E_NOT_FOUND = -2147023728;
public const int E_OBJECT_NOT_EXIST = -2147020584;
private const uint ERROR_ALREADY_EXISTS = 2147942583;
private string siteServiceId;
public string SiteServiceId
{
get { return siteServiceId; }
set { siteServiceId = value; }
}
public void FlushLog()
{
if (this._flushLogMethod == null)
{
this._flushLogMethod = base.Methods["FlushLog"];
}
this._flushLogMethod.CreateInstance().Execute();
}
public void Start()
{
if (this._startMethod == null)
{
this._startMethod = base.Methods["Start"];
}
this._startMethod.CreateInstance().Execute();
}
public void Stop()
{
if (this._stopMethod == null)
{
this._stopMethod = base.Methods["Stop"];
}
this._stopMethod.CreateInstance().Execute();
}
public bool AllowUTF8
{
get
{
return (bool) base["allowUTF8"];
}
set
{
base["allowUTF8"] = value;
}
}
public ConnectionsElement Connections
{
get
{
if (this._connections == null)
{
this._connections = (ConnectionsElement) base.GetChildElement("connections", typeof(ConnectionsElement));
}
return this._connections;
}
}
public DataChannelSecurityElement DataChannelSecurity
{
get
{
if (this._dataChannelSecurity == null)
{
this._dataChannelSecurity = (DataChannelSecurityElement) base.GetChildElement("dataChannelSecurity", typeof(DataChannelSecurityElement));
}
return this._dataChannelSecurity;
}
}
public DirectoryBrowseElement DirectoryBrowse
{
get
{
if (this._directoryBrowse == null)
{
this._directoryBrowse = (DirectoryBrowseElement) base.GetChildElement("directoryBrowse", typeof(DirectoryBrowseElement));
}
return this._directoryBrowse;
}
}
public FileHandlingElement FileHandling
{
get
{
if (this._fileHandling == null)
{
this._fileHandling = (FileHandlingElement) base.GetChildElement("fileHandling", typeof(FileHandlingElement));
}
return this._fileHandling;
}
}
public FirewallElement FirewallSupport
{
get
{
if (this._firewall == null)
{
this._firewall = (FirewallElement)base.GetChildElement("firewallSupport", typeof(FirewallElement));
}
return this._firewall;
}
}
public uint LastStartupStatus
{
get
{
return (uint) base["lastStartupStatus"];
}
set
{
base["lastStartupStatus"] = value;
}
}
public LogFileElement LogFile
{
get
{
if (this._logFile == null)
{
this._logFile = (LogFileElement)base.GetChildElement("logFile", typeof(LogFileElement));
}
return this._logFile;
}
}
public MessagesElement Messages
{
get
{
if (this._messages == null)
{
this._messages = (MessagesElement) base.GetChildElement("messages", typeof(MessagesElement));
}
return this._messages;
}
}
public SecurityElement Security
{
get
{
if (this._security == null)
{
this._security = (SecurityElement) base.GetChildElement("security", typeof(SecurityElement));
}
return this._security;
}
}
public bool ServerAutoStart
{
get
{
return (bool) base["serverAutoStart"];
}
set
{
base["serverAutoStart"] = value;
}
}
public SessionCollection Sessions
{
get
{
if (this._sessions == null)
{
this._sessions = (SessionCollection) base.GetCollection("sessions", typeof(SessionCollection));
}
return this._sessions;
}
}
public SiteState State
{
get
{
SiteState unknown = SiteState.Unknown;
int num = 0;
bool flag = false;
while (!flag && (++num < 10))
{
try
{
unknown = (SiteState)base["state"];
flag = true;
continue;
}
catch (COMException exception)
{
if (exception.ErrorCode != -2147020584)
{
return unknown;
}
Thread.Sleep(100);
continue;
}
}
return unknown;
}
set
{
base["state"] = (int) value;
}
}
public UserIsolationElement UserIsolation
{
get
{
if (this._userIsolation == null)
{
this._userIsolation = (UserIsolationElement) base.GetChildElement("userIsolation", typeof(UserIsolationElement));
}
return this._userIsolation;
}
}
}
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 Antlr4.Runtime.Atn;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
namespace Antlr4.Runtime.Atn
{
/// <summary>
/// This enumeration defines the prediction modes available in ANTLR 4 along with
/// utility methods for analyzing configuration sets for conflicts and/or
/// ambiguities.
/// </summary>
/// <remarks>
/// This enumeration defines the prediction modes available in ANTLR 4 along with
/// utility methods for analyzing configuration sets for conflicts and/or
/// ambiguities.
/// </remarks>
[System.Serializable]
public sealed class PredictionMode
{
/// <summary>The SLL(*) prediction mode.</summary>
/// <remarks>
/// The SLL(*) prediction mode. This prediction mode ignores the current
/// parser context when making predictions. This is the fastest prediction
/// mode, and provides correct results for many grammars. This prediction
/// mode is more powerful than the prediction mode provided by ANTLR 3, but
/// may result in syntax errors for grammar and input combinations which are
/// not SLL.
/// <p>
/// When using this prediction mode, the parser will either return a correct
/// parse tree (i.e. the same parse tree that would be returned with the
/// <see cref="Ll"/>
/// prediction mode), or it will report a syntax error. If a
/// syntax error is encountered when using the
/// <see cref="Sll"/>
/// prediction mode,
/// it may be due to either an actual syntax error in the input or indicate
/// that the particular combination of grammar and input requires the more
/// powerful
/// <see cref="Ll"/>
/// prediction abilities to complete successfully.</p>
/// <p>
/// This prediction mode does not provide any guarantees for prediction
/// behavior for syntactically-incorrect inputs.</p>
/// </remarks>
public static readonly PredictionMode Sll = new PredictionMode();
/// <summary>The LL(*) prediction mode.</summary>
/// <remarks>
/// The LL(*) prediction mode. This prediction mode allows the current parser
/// context to be used for resolving SLL conflicts that occur during
/// prediction. This is the fastest prediction mode that guarantees correct
/// parse results for all combinations of grammars with syntactically correct
/// inputs.
/// <p>
/// When using this prediction mode, the parser will make correct decisions
/// for all syntactically-correct grammar and input combinations. However, in
/// cases where the grammar is truly ambiguous this prediction mode might not
/// report a precise answer for <em>exactly which</em> alternatives are
/// ambiguous.</p>
/// <p>
/// This prediction mode does not provide any guarantees for prediction
/// behavior for syntactically-incorrect inputs.</p>
/// </remarks>
public static readonly PredictionMode Ll = new PredictionMode();
/// <summary>The LL(*) prediction mode with exact ambiguity detection.</summary>
/// <remarks>
/// The LL(*) prediction mode with exact ambiguity detection. In addition to
/// the correctness guarantees provided by the
/// <see cref="Ll"/>
/// prediction mode,
/// this prediction mode instructs the prediction algorithm to determine the
/// complete and exact set of ambiguous alternatives for every ambiguous
/// decision encountered while parsing.
/// <p>
/// This prediction mode may be used for diagnosing ambiguities during
/// grammar development. Due to the performance overhead of calculating sets
/// of ambiguous alternatives, this prediction mode should be avoided when
/// the exact results are not necessary.</p>
/// <p>
/// This prediction mode does not provide any guarantees for prediction
/// behavior for syntactically-incorrect inputs.</p>
/// </remarks>
public static readonly PredictionMode LlExactAmbigDetection = new PredictionMode();
/// <summary>A Map that uses just the state and the stack context as the key.</summary>
/// <remarks>A Map that uses just the state and the stack context as the key.</remarks>
internal class AltAndContextMap : Dictionary<ATNConfig, BitSet>
{
public AltAndContextMap()
: base(PredictionMode.AltAndContextConfigEqualityComparator.Instance)
{
}
}
private sealed class AltAndContextConfigEqualityComparator : EqualityComparer<ATNConfig>
{
public static readonly PredictionMode.AltAndContextConfigEqualityComparator Instance = new PredictionMode.AltAndContextConfigEqualityComparator();
private AltAndContextConfigEqualityComparator()
{
}
/// <summary>
/// The hash code is only a function of the
/// <see cref="ATNState.stateNumber"/>
/// and
/// <see cref="ATNConfig.Context"/>
/// .
/// </summary>
public override int GetHashCode(ATNConfig o)
{
int hashCode = MurmurHash.Initialize(7);
hashCode = MurmurHash.Update(hashCode, o.State.stateNumber);
hashCode = MurmurHash.Update(hashCode, o.Context);
hashCode = MurmurHash.Finish(hashCode, 2);
return hashCode;
}
public override bool Equals(ATNConfig a, ATNConfig b)
{
if (a == b)
{
return true;
}
if (a == null || b == null)
{
return false;
}
return a.State.stateNumber == b.State.stateNumber && a.Context.Equals(b.Context);
}
}
/// <summary>Computes the SLL prediction termination condition.</summary>
/// <remarks>
/// Computes the SLL prediction termination condition.
/// <p>
/// This method computes the SLL prediction termination condition for both of
/// the following cases.</p>
/// <ul>
/// <li>The usual SLL+LL fallback upon SLL conflict</li>
/// <li>Pure SLL without LL fallback</li>
/// </ul>
/// <p><strong>COMBINED SLL+LL PARSING</strong></p>
/// <p>When LL-fallback is enabled upon SLL conflict, correct predictions are
/// ensured regardless of how the termination condition is computed by this
/// method. Due to the substantially higher cost of LL prediction, the
/// prediction should only fall back to LL when the additional lookahead
/// cannot lead to a unique SLL prediction.</p>
/// <p>Assuming combined SLL+LL parsing, an SLL configuration set with only
/// conflicting subsets should fall back to full LL, even if the
/// configuration sets don't resolve to the same alternative (e.g.
/// <c/>
///
/// 1,2}} and
/// <c/>
///
/// 3,4}}. If there is at least one non-conflicting
/// configuration, SLL could continue with the hopes that more lookahead will
/// resolve via one of those non-conflicting configurations.</p>
/// <p>Here's the prediction termination rule them: SLL (for SLL+LL parsing)
/// stops when it sees only conflicting configuration subsets. In contrast,
/// full LL keeps going when there is uncertainty.</p>
/// <p><strong>HEURISTIC</strong></p>
/// <p>As a heuristic, we stop prediction when we see any conflicting subset
/// unless we see a state that only has one alternative associated with it.
/// The single-alt-state thing lets prediction continue upon rules like
/// (otherwise, it would admit defeat too soon):</p>
/// <p>
/// <c>[12|1|[], 6|2|[], 12|2|[]]. s : (ID | ID ID?) ';' ;</c>
/// </p>
/// <p>When the ATN simulation reaches the state before
/// <c>';'</c>
/// , it has a
/// DFA state that looks like:
/// <c>[12|1|[], 6|2|[], 12|2|[]]</c>
/// . Naturally
/// <c>12|1|[]</c>
/// and
/// <c>12|2|[]</c>
/// conflict, but we cannot stop
/// processing this node because alternative to has another way to continue,
/// via
/// <c>[6|2|[]]</c>
/// .</p>
/// <p>It also let's us continue for this rule:</p>
/// <p>
/// <c>[1|1|[], 1|2|[], 8|3|[]] a : A | A | A B ;</c>
/// </p>
/// <p>After matching input A, we reach the stop state for rule A, state 1.
/// State 8 is the state right before B. Clearly alternatives 1 and 2
/// conflict and no amount of further lookahead will separate the two.
/// However, alternative 3 will be able to continue and so we do not stop
/// working on this state. In the previous example, we're concerned with
/// states associated with the conflicting alternatives. Here alt 3 is not
/// associated with the conflicting configs, but since we can continue
/// looking for input reasonably, don't declare the state done.</p>
/// <p><strong>PURE SLL PARSING</strong></p>
/// <p>To handle pure SLL parsing, all we have to do is make sure that we
/// combine stack contexts for configurations that differ only by semantic
/// predicate. From there, we can do the usual SLL termination heuristic.</p>
/// <p><strong>PREDICATES IN SLL+LL PARSING</strong></p>
/// <p>SLL decisions don't evaluate predicates until after they reach DFA stop
/// states because they need to create the DFA cache that works in all
/// semantic situations. In contrast, full LL evaluates predicates collected
/// during start state computation so it can ignore predicates thereafter.
/// This means that SLL termination detection can totally ignore semantic
/// predicates.</p>
/// <p>Implementation-wise,
/// <see cref="ATNConfigSet"/>
/// combines stack contexts but not
/// semantic predicate contexts so we might see two configurations like the
/// following.</p>
/// <p>
/// <c/>
/// (s, 1, x,
/// ), (s, 1, x', {p})}</p>
/// <p>Before testing these configurations against others, we have to merge
/// <c>x</c>
/// and
/// <c>x'</c>
/// (without modifying the existing configurations).
/// For example, we test
/// <c>(x+x')==x''</c>
/// when looking for conflicts in
/// the following configurations.</p>
/// <p>
/// <c/>
/// (s, 1, x,
/// ), (s, 1, x', {p}), (s, 2, x'', {})}</p>
/// <p>If the configuration set has predicates (as indicated by
/// <see cref="ATNConfigSet.HasSemanticContext()"/>
/// ), this algorithm makes a copy of
/// the configurations to strip out all of the predicates so that a standard
/// <see cref="ATNConfigSet"/>
/// will merge everything ignoring predicates.</p>
/// </remarks>
public static bool HasSLLConflictTerminatingPrediction(PredictionMode mode, ATNConfigSet configs)
{
if (AllConfigsInRuleStopStates(configs))
{
return true;
}
// pure SLL mode parsing
if (mode == PredictionMode.Sll)
{
// Don't bother with combining configs from different semantic
// contexts if we can fail over to full LL; costs more time
// since we'll often fail over anyway.
if (configs.HasSemanticContext)
{
// dup configs, tossing out semantic predicates
ATNConfigSet dup = new ATNConfigSet();
foreach (ATNConfig c in configs)
{
c.Transform(c.State, SemanticContext.None, false);
dup.Add(c);
}
configs = dup;
}
}
// now we have combined contexts for configs with dissimilar preds
// pure SLL or combined SLL+LL mode parsing
ICollection<BitSet> altsets = GetConflictingAltSubsets(configs);
bool heuristic = HasConflictingAltSet(altsets) && !HasStateAssociatedWithOneAlt(configs);
return heuristic;
}
/// <summary>
/// Checks if any configuration in
/// <paramref name="configs"/>
/// is in a
/// <see cref="RuleStopState"/>
/// . Configurations meeting this condition have reached
/// the end of the decision rule (local context) or end of start rule (full
/// context).
/// </summary>
/// <param name="configs">the configuration set to test</param>
/// <returns>
///
/// <see langword="true"/>
/// if any configuration in
/// <paramref name="configs"/>
/// is in a
/// <see cref="RuleStopState"/>
/// , otherwise
/// <see langword="false"/>
/// </returns>
public static bool HasConfigInRuleStopState(IEnumerable<ATNConfig> configs)
{
foreach (ATNConfig c in configs)
{
if (c.State is RuleStopState)
{
return true;
}
}
return false;
}
/// <summary>
/// Checks if all configurations in
/// <paramref name="configs"/>
/// are in a
/// <see cref="RuleStopState"/>
/// . Configurations meeting this condition have reached
/// the end of the decision rule (local context) or end of start rule (full
/// context).
/// </summary>
/// <param name="configs">the configuration set to test</param>
/// <returns>
///
/// <see langword="true"/>
/// if all configurations in
/// <paramref name="configs"/>
/// are in a
/// <see cref="RuleStopState"/>
/// , otherwise
/// <see langword="false"/>
/// </returns>
public static bool AllConfigsInRuleStopStates(IEnumerable<ATNConfig> configs)
{
foreach (ATNConfig config in configs)
{
if (!(config.State is RuleStopState))
{
return false;
}
}
return true;
}
/// <summary>Full LL prediction termination.</summary>
/// <remarks>
/// Full LL prediction termination.
/// <p>Can we stop looking ahead during ATN simulation or is there some
/// uncertainty as to which alternative we will ultimately pick, after
/// consuming more input? Even if there are partial conflicts, we might know
/// that everything is going to resolve to the same minimum alternative. That
/// means we can stop since no more lookahead will change that fact. On the
/// other hand, there might be multiple conflicts that resolve to different
/// minimums. That means we need more look ahead to decide which of those
/// alternatives we should predict.</p>
/// <p>The basic idea is to split the set of configurations
/// <c>C</c>
/// , into
/// conflicting subsets
/// <c>(s, _, ctx, _)</c>
/// and singleton subsets with
/// non-conflicting configurations. Two configurations conflict if they have
/// identical
/// <see cref="ATNConfig.State"/>
/// and
/// <see cref="ATNConfig.Context"/>
/// values
/// but different
/// <see cref="ATNConfig.Alt"/>
/// value, e.g.
/// <c>(s, i, ctx, _)</c>
/// and
/// <c>(s, j, ctx, _)</c>
/// for
/// <c>i!=j</c>
/// .</p>
/// <p/>
/// Reduce these configuration subsets to the set of possible alternatives.
/// You can compute the alternative subsets in one pass as follows:
/// <p/>
/// <c/>
/// A_s,ctx =
/// i | (s, i, ctx, _)}} for each configuration in
/// <c>C</c>
/// holding
/// <c>s</c>
/// and
/// <c>ctx</c>
/// fixed.
/// <p/>
/// Or in pseudo-code, for each configuration
/// <c>c</c>
/// in
/// <c>C</c>
/// :
/// <pre>
/// map[c] U= c.
/// <see cref="ATNConfig.Alt()">getAlt()</see>
/// # map hash/equals uses s and x, not
/// alt and not pred
/// </pre>
/// <p>The values in
/// <c>map</c>
/// are the set of
/// <c>A_s,ctx</c>
/// sets.</p>
/// <p>If
/// <c>|A_s,ctx|=1</c>
/// then there is no conflict associated with
/// <c>s</c>
/// and
/// <c>ctx</c>
/// .</p>
/// <p>Reduce the subsets to singletons by choosing a minimum of each subset. If
/// the union of these alternative subsets is a singleton, then no amount of
/// more lookahead will help us. We will always pick that alternative. If,
/// however, there is more than one alternative, then we are uncertain which
/// alternative to predict and must continue looking for resolution. We may
/// or may not discover an ambiguity in the future, even if there are no
/// conflicting subsets this round.</p>
/// <p>The biggest sin is to terminate early because it means we've made a
/// decision but were uncertain as to the eventual outcome. We haven't used
/// enough lookahead. On the other hand, announcing a conflict too late is no
/// big deal; you will still have the conflict. It's just inefficient. It
/// might even look until the end of file.</p>
/// <p>No special consideration for semantic predicates is required because
/// predicates are evaluated on-the-fly for full LL prediction, ensuring that
/// no configuration contains a semantic context during the termination
/// check.</p>
/// <p><strong>CONFLICTING CONFIGS</strong></p>
/// <p>Two configurations
/// <c>(s, i, x)</c>
/// and
/// <c>(s, j, x')</c>
/// , conflict
/// when
/// <c>i!=j</c>
/// but
/// <c>x=x'</c>
/// . Because we merge all
/// <c>(s, i, _)</c>
/// configurations together, that means that there are at
/// most
/// <c>n</c>
/// configurations associated with state
/// <c>s</c>
/// for
/// <c>n</c>
/// possible alternatives in the decision. The merged stacks
/// complicate the comparison of configuration contexts
/// <c>x</c>
/// and
/// <c>x'</c>
/// . Sam checks to see if one is a subset of the other by calling
/// merge and checking to see if the merged result is either
/// <c>x</c>
/// or
/// <c>x'</c>
/// . If the
/// <c>x</c>
/// associated with lowest alternative
/// <c>i</c>
/// is the superset, then
/// <c>i</c>
/// is the only possible prediction since the
/// others resolve to
/// <c>min(i)</c>
/// as well. However, if
/// <c>x</c>
/// is
/// associated with
/// <c>j>i</c>
/// then at least one stack configuration for
/// <c>j</c>
/// is not in conflict with alternative
/// <c>i</c>
/// . The algorithm
/// should keep going, looking for more lookahead due to the uncertainty.</p>
/// <p>For simplicity, I'm doing a equality check between
/// <c>x</c>
/// and
/// <c>x'</c>
/// that lets the algorithm continue to consume lookahead longer
/// than necessary. The reason I like the equality is of course the
/// simplicity but also because that is the test you need to detect the
/// alternatives that are actually in conflict.</p>
/// <p><strong>CONTINUE/STOP RULE</strong></p>
/// <p>Continue if union of resolved alternative sets from non-conflicting and
/// conflicting alternative subsets has more than one alternative. We are
/// uncertain about which alternative to predict.</p>
/// <p>The complete set of alternatives,
/// <c>[i for (_,i,_)]</c>
/// , tells us which
/// alternatives are still in the running for the amount of input we've
/// consumed at this point. The conflicting sets let us to strip away
/// configurations that won't lead to more states because we resolve
/// conflicts to the configuration with a minimum alternate for the
/// conflicting set.</p>
/// <p><strong>CASES</strong></p>
/// <ul>
/// <li>no conflicts and more than 1 alternative in set => continue</li>
/// <li>
/// <c>(s, 1, x)</c>
/// ,
/// <c>(s, 2, x)</c>
/// ,
/// <c>(s, 3, z)</c>
/// ,
/// <c>(s', 1, y)</c>
/// ,
/// <c>(s', 2, y)</c>
/// yields non-conflicting set
/// <c/>
///
/// 3}} U conflicting sets
/// <c/>
/// min(
/// 1,2})} U
/// <c/>
/// min(
/// 1,2})} =
/// <c/>
///
/// 1,3}} => continue
/// </li>
/// <li>
/// <c>(s, 1, x)</c>
/// ,
/// <c>(s, 2, x)</c>
/// ,
/// <c>(s', 1, y)</c>
/// ,
/// <c>(s', 2, y)</c>
/// ,
/// <c>(s'', 1, z)</c>
/// yields non-conflicting set
/// <c/>
///
/// 1}} U conflicting sets
/// <c/>
/// min(
/// 1,2})} U
/// <c/>
/// min(
/// 1,2})} =
/// <c/>
///
/// 1}} => stop and predict 1</li>
/// <li>
/// <c>(s, 1, x)</c>
/// ,
/// <c>(s, 2, x)</c>
/// ,
/// <c>(s', 1, y)</c>
/// ,
/// <c>(s', 2, y)</c>
/// yields conflicting, reduced sets
/// <c/>
///
/// 1}} U
/// <c/>
///
/// 1}} =
/// <c/>
///
/// 1}} => stop and predict 1, can announce
/// ambiguity
/// <c/>
///
/// 1,2}}</li>
/// <li>
/// <c>(s, 1, x)</c>
/// ,
/// <c>(s, 2, x)</c>
/// ,
/// <c>(s', 2, y)</c>
/// ,
/// <c>(s', 3, y)</c>
/// yields conflicting, reduced sets
/// <c/>
///
/// 1}} U
/// <c/>
///
/// 2}} =
/// <c/>
///
/// 1,2}} => continue</li>
/// <li>
/// <c>(s, 1, x)</c>
/// ,
/// <c>(s, 2, x)</c>
/// ,
/// <c>(s', 3, y)</c>
/// ,
/// <c>(s', 4, y)</c>
/// yields conflicting, reduced sets
/// <c/>
///
/// 1}} U
/// <c/>
///
/// 3}} =
/// <c/>
///
/// 1,3}} => continue</li>
/// </ul>
/// <p><strong>EXACT AMBIGUITY DETECTION</strong></p>
/// <p>If all states report the same conflicting set of alternatives, then we
/// know we have the exact ambiguity set.</p>
/// <p><code>|A_<em>i</em>|>1</code> and
/// <code>A_<em>i</em> = A_<em>j</em></code> for all <em>i</em>, <em>j</em>.</p>
/// <p>In other words, we continue examining lookahead until all
/// <c>A_i</c>
/// have more than one alternative and all
/// <c>A_i</c>
/// are the same. If
/// <c/>
/// A=
/// {1,2}, {1,3}}}, then regular LL prediction would terminate
/// because the resolved set is
/// <c/>
///
/// 1}}. To determine what the real
/// ambiguity is, we have to know whether the ambiguity is between one and
/// two or one and three so we keep going. We can only stop prediction when
/// we need exact ambiguity detection when the sets look like
/// <c/>
/// A=
/// {1,2}}} or
/// <c/>
///
/// {1,2},{1,2}}}, etc...</p>
/// </remarks>
public static int ResolvesToJustOneViableAlt(IEnumerable<BitSet> altsets)
{
return GetSingleViableAlt(altsets);
}
/// <summary>
/// Determines if every alternative subset in
/// <paramref name="altsets"/>
/// contains more
/// than one alternative.
/// </summary>
/// <param name="altsets">a collection of alternative subsets</param>
/// <returns>
///
/// <see langword="true"/>
/// if every
/// <see cref="Antlr4.Runtime.Sharpen.BitSet"/>
/// in
/// <paramref name="altsets"/>
/// has
/// <see cref="Antlr4.Runtime.Sharpen.BitSet.Cardinality()">cardinality</see>
/// > 1, otherwise
/// <see langword="false"/>
/// </returns>
public static bool AllSubsetsConflict(IEnumerable<BitSet> altsets)
{
return !HasNonConflictingAltSet(altsets);
}
/// <summary>
/// Determines if any single alternative subset in
/// <paramref name="altsets"/>
/// contains
/// exactly one alternative.
/// </summary>
/// <param name="altsets">a collection of alternative subsets</param>
/// <returns>
///
/// <see langword="true"/>
/// if
/// <paramref name="altsets"/>
/// contains a
/// <see cref="Antlr4.Runtime.Sharpen.BitSet"/>
/// with
/// <see cref="Antlr4.Runtime.Sharpen.BitSet.Cardinality()">cardinality</see>
/// 1, otherwise
/// <see langword="false"/>
/// </returns>
public static bool HasNonConflictingAltSet(IEnumerable<BitSet> altsets)
{
foreach (BitSet alts in altsets)
{
if (alts.Cardinality() == 1)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if any single alternative subset in
/// <paramref name="altsets"/>
/// contains
/// more than one alternative.
/// </summary>
/// <param name="altsets">a collection of alternative subsets</param>
/// <returns>
///
/// <see langword="true"/>
/// if
/// <paramref name="altsets"/>
/// contains a
/// <see cref="Antlr4.Runtime.Sharpen.BitSet"/>
/// with
/// <see cref="Antlr4.Runtime.Sharpen.BitSet.Cardinality()">cardinality</see>
/// > 1, otherwise
/// <see langword="false"/>
/// </returns>
public static bool HasConflictingAltSet(IEnumerable<BitSet> altsets)
{
foreach (BitSet alts in altsets)
{
if (alts.Cardinality() > 1)
{
return true;
}
}
return false;
}
/// <summary>
/// Determines if every alternative subset in
/// <paramref name="altsets"/>
/// is equivalent.
/// </summary>
/// <param name="altsets">a collection of alternative subsets</param>
/// <returns>
///
/// <see langword="true"/>
/// if every member of
/// <paramref name="altsets"/>
/// is equal to the
/// others, otherwise
/// <see langword="false"/>
/// </returns>
public static bool AllSubsetsEqual(IEnumerable<BitSet> altsets)
{
IEnumerator<BitSet> it = altsets.GetEnumerator();
it.MoveNext();
BitSet first = it.Current;
while (it.MoveNext())
{
BitSet next = it.Current;
if (!next.Equals(first))
{
return false;
}
}
return true;
}
/// <summary>
/// Returns the unique alternative predicted by all alternative subsets in
/// <paramref name="altsets"/>
/// . If no such alternative exists, this method returns
/// <see cref="ATN.InvalidAltNumber"/>
/// .
/// </summary>
/// <param name="altsets">a collection of alternative subsets</param>
public static int GetUniqueAlt(IEnumerable<BitSet> altsets)
{
BitSet all = GetAlts(altsets);
if (all.Cardinality() == 1)
{
return all.NextSetBit(0);
}
return ATN.InvalidAltNumber;
}
/// <summary>
/// Gets the complete set of represented alternatives for a collection of
/// alternative subsets.
/// </summary>
/// <remarks>
/// Gets the complete set of represented alternatives for a collection of
/// alternative subsets. This method returns the union of each
/// <see cref="Antlr4.Runtime.Sharpen.BitSet"/>
/// in
/// <paramref name="altsets"/>
/// .
/// </remarks>
/// <param name="altsets">a collection of alternative subsets</param>
/// <returns>
/// the set of represented alternatives in
/// <paramref name="altsets"/>
/// </returns>
public static BitSet GetAlts(IEnumerable<BitSet> altsets)
{
BitSet all = new BitSet();
foreach (BitSet alts in altsets)
{
all.Or(alts);
}
return all;
}
/// <summary>This function gets the conflicting alt subsets from a configuration set.</summary>
/// <remarks>
/// This function gets the conflicting alt subsets from a configuration set.
/// For each configuration
/// <c>c</c>
/// in
/// <paramref name="configs"/>
/// :
/// <pre>
/// map[c] U= c.
/// <see cref="ATNConfig.Alt()">getAlt()</see>
/// # map hash/equals uses s and x, not
/// alt and not pred
/// </pre>
/// </remarks>
[return: NotNull]
public static ICollection<BitSet> GetConflictingAltSubsets(IEnumerable<ATNConfig> configs)
{
PredictionMode.AltAndContextMap configToAlts = new PredictionMode.AltAndContextMap();
foreach (ATNConfig c in configs)
{
BitSet alts;
if (!configToAlts.TryGetValue(c, out alts))
{
alts = new BitSet();
configToAlts[c] = alts;
}
alts.Set(c.Alt);
}
return configToAlts.Values;
}
/// <summary>Get a map from state to alt subset from a configuration set.</summary>
/// <remarks>
/// Get a map from state to alt subset from a configuration set. For each
/// configuration
/// <c>c</c>
/// in
/// <paramref name="configs"/>
/// :
/// <pre>
/// map[c.
/// <see cref="ATNConfig.State"/>
/// ] U= c.
/// <see cref="ATNConfig.Alt"/>
/// </pre>
/// </remarks>
[return: NotNull]
public static IDictionary<ATNState, BitSet> GetStateToAltMap(IEnumerable<ATNConfig> configs)
{
IDictionary<ATNState, BitSet> m = new Dictionary<ATNState, BitSet>();
foreach (ATNConfig c in configs)
{
BitSet alts;
if (!m.TryGetValue(c.State, out alts))
{
alts = new BitSet();
m[c.State] = alts;
}
alts.Set(c.Alt);
}
return m;
}
public static bool HasStateAssociatedWithOneAlt(IEnumerable<ATNConfig> configs)
{
IDictionary<ATNState, BitSet> x = GetStateToAltMap(configs);
foreach (BitSet alts in x.Values)
{
if (alts.Cardinality() == 1)
{
return true;
}
}
return false;
}
public static int GetSingleViableAlt(IEnumerable<BitSet> altsets)
{
BitSet viableAlts = new BitSet();
foreach (BitSet alts in altsets)
{
int minAlt = alts.NextSetBit(0);
viableAlts.Set(minAlt);
if (viableAlts.Cardinality() > 1)
{
// more than 1 viable alt
return ATN.InvalidAltNumber;
}
}
return viableAlts.NextSetBit(0);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Kitware.VTK;
namespace SpherePuzzle
{
/// <summary>
/// An example converted from a vtk Tcl example
/// and embeded in a CSharp Dialog
/// </summary>
public partial class Form1 : Form
{
/// <summary>
///
/// </summary>
public Form1()
{
InitializeComponent();
}
vtkSpherePuzzle puzzle = vtkSpherePuzzle.New();
vtkPolyDataMapper mapper = vtkPolyDataMapper.New();
vtkActor actor = vtkActor.New();
vtkSpherePuzzleArrows arrows = vtkSpherePuzzleArrows.New();
vtkPolyDataMapper mapper2 = vtkPolyDataMapper.New();
vtkActor actor2 = vtkActor.New();
Boolean once = true;
bool in_piece_rotation = false;
double LastVal = 0;
bool LastValExists = false;
/// <summary>
/// Clean up globals
/// </summary>
public void disposeAllVTKObjects()
{
puzzle.Dispose();
mapper.Dispose();
actor.Dispose();
arrows.Dispose();
mapper2.Dispose();
actor2.Dispose();
}
/// <summary>
/// Set up the dialog
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void renderWindowControl1_Load(object sender, EventArgs e)
{
//Setup the variables and the background
vtkRenderer ren1 = renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer();
mapper.SetInputConnection(puzzle.GetOutputPort());
mapper2.SetInputConnection(arrows.GetOutputPort());
actor.SetMapper(mapper);
actor2.SetMapper(mapper2);
ren1.AddActor(actor);
ren1.AddActor(actor2);
ren1.SetBackground(0.1, 0.2, 0.4);
//Set up the camera
ren1.ResetCamera();
vtkCamera cam = ren1.GetActiveCamera();
cam.Elevation(-40);
renderWindowControl1.RenderWindow.Render();
//Change the style to a trackball style
//Equivalent of pressing 't'
vtkRenderWindowInteractor iren = renderWindowControl1.RenderWindow.GetInteractor();
vtkInteractorStyleSwitch istyle = vtkInteractorStyleSwitch.New();
iren.SetInteractorStyle(istyle);
(istyle).SetCurrentStyleToTrackballCamera();
//Add events to the iren instead of Observers
iren.MouseMoveEvt += new vtkObject.vtkObjectEventHandler(MotionCallback);
iren.CharEvt += new vtkObject.vtkObjectEventHandler(CharCallback);
}
/// <summary>
/// Highlights pieces
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void MotionCallback(vtkObject sender, vtkObjectEventArgs e)
{
//Make sure the piece isn't in an animation
//durring a click or bad things happen
if (!in_piece_rotation)
{
vtkRenderWindowInteractor iren = renderWindowControl1.RenderWindow.GetInteractor();
vtkInteractorStyleSwitch istyle = (vtkInteractorStyleSwitch)iren.GetInteractorStyle();
//return if the user is performing interaction
if (istyle.GetState()!=0)
{
return;
}
int[] pos = iren.GetEventPosition();
int x = pos[0];
int y = pos[1];
vtkRenderer ren1 = renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer();
ren1.SetDisplayPoint(x, y, ren1.GetZ(x, y));
ren1.DisplayToWorld();
double [] pt = ren1.GetWorldPoint();
double val = puzzle.SetPoint(pt[0], pt[1], pt[2]);
if (!LastValExists || val != LastVal)
{
renderWindowControl1.RenderWindow.Render();
LastVal = val;
LastValExists = true;
}
}
}
/// <summary>
/// Called when a key is pressed
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
void CharCallback(vtkObject sender, vtkObjectEventArgs e)
{
vtkRenderWindowInteractor iren = renderWindowControl1.RenderWindow.GetInteractor();
sbyte keycode = iren.GetKeyCode();
//if the keycode is not M
if (keycode != 109 && keycode != 77)
{
return;
}
int[] pos = iren.GetEventPosition();
ButtonCallback(pos[0], pos[1]);
}
/// <summary>
/// Moves the sphere when the mouse is clicked in
/// position (x,y)
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
void ButtonCallback(double x, double y)
{
if (!in_piece_rotation)
{
in_piece_rotation = true;
vtkRenderer ren1 = renderWindowControl1.RenderWindow.GetRenderers().GetFirstRenderer();
ren1.SetDisplayPoint(x,y,ren1.GetZ((int)x,(int)y));
ren1.DisplayToWorld();
double[] pt = ren1.GetWorldPoint();
x = pt[0];
y = pt[1];
double z = pt[2];
for (int i = 0; i <= 100; i += 10)
{
puzzle.SetPoint(x, y, z);
puzzle.MovePoint(i);
renderWindowControl1.RenderWindow.Render();
this.Update();
}
in_piece_rotation = false;
}
}
/// <summary>
/// Reset
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
puzzle.Reset();
renderWindowControl1.RenderWindow.Render();
}
/// <summary>
/// Quit
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Clean up
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Closed(object sender, FormClosedEventArgs e)
{
disposeAllVTKObjects();
}
/// <summary>
/// Scrambles the puzzle when the form first becomes
/// visible
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Activated(object sender, EventArgs e)
{
if (once)
{
ButtonCallback(218, 195);
ButtonCallback(261, 128);
ButtonCallback(213, 107);
ButtonCallback(203, 162);
ButtonCallback(134, 186);
once = false;
}
}
}
}
| |
using System;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Imaging;
using AForge.Video;
using AForge.Video.DirectShow;
using MatterHackers.Agg.Image;
namespace AForge
{
public interface ICamera
{
void TakeSnapShot();
ImageBuffer CurrentImage { get; }
int Exposure0To511 { get; set; }
int RedBalance0To255 { get; set; }
int GreenBalance0To255 { get; set; }
int BlueBalance0To255 { get; set; }
bool IsNewImageReady();
void CloseCurrentVideoSource();
void OpenSettings();
}
public class AForgeCamera : ICamera
{
public enum DownSample { None, HalfSize };
VideoCaptureDevice videoCaptureDevice;
bool newImageReady = false;
ImageBuffer asyncCopiedVideoImage = new ImageBuffer();
ImageBuffer imageForExternalUse = new ImageBuffer();
DownSample downSampleVideo = DownSample.None;
bool flipY = true;
public AForgeCamera(string preferedCameraName = null, int preferedWidth = 640, int preferedHeight = 480, DownSample downSampleVideo = DownSample.None)
{
this.downSampleVideo = downSampleVideo;
if (preferedCameraName != null)
{
FilterInfoCollection videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
foreach (FilterInfo info in videoDevices)
{
if (info.Name.Contains(preferedCameraName))
{
videoCaptureDevice = new VideoCaptureDevice(info.MonikerString);
videoCaptureDevice.DesiredFrameSize = new Size(preferedWidth, preferedHeight);
break;
}
}
}
if (videoCaptureDevice == null)
{
VideoCaptureDeviceForm form = new VideoCaptureDeviceForm();
if (form.ShowDialog(null) == DialogResult.OK)
{
// create video source
videoCaptureDevice = form.VideoDevice;
}
}
if (videoCaptureDevice != null)
{
//videoCaptureDevice.DesiredFrameRate = 5;
//videoCaptureDevice.ProvideSnapshots = true;
//videoCaptureDevice.DesiredSnapshotSize = new Size(preferedWidth, preferedHeight);
//videoCaptureDevice.SnapshotFrame += new NewFrameEventHandler(videoCaptureDevice_SnapshotFrame);
asyncCopiedVideoImage = new ImageBuffer(videoCaptureDevice.DesiredFrameSize.Width, videoCaptureDevice.DesiredFrameSize.Height, 32, new BlenderBGRA());
if (downSampleVideo == DownSample.HalfSize)
{
imageForExternalUse = new ImageBuffer(videoCaptureDevice.DesiredFrameSize.Width / 2, videoCaptureDevice.DesiredFrameSize.Height / 2, 32, new BlenderBGRA());
}
else
{
imageForExternalUse = new ImageBuffer(videoCaptureDevice.DesiredFrameSize.Width, videoCaptureDevice.DesiredFrameSize.Height, 32, new BlenderBGRA());
}
videoCaptureDevice.Start();
videoCaptureDevice.NewFrame += new NewFrameEventHandler(source_NewFrame);
}
}
public ImageBuffer CurrentImage
{
get
{
return imageForExternalUse;
}
}
public int Exposure0To511 { get; set; }
public int RedBalance0To255 { get; set; }
public int GreenBalance0To255 { get; set; }
public int BlueBalance0To255 { get; set; }
public void OpenSettings()
{
videoCaptureDevice.DisplayPropertyPage(IntPtr.Zero);
}
bool currentlyUsingCameraImage = false;
public bool IsNewImageReady()
{
if (newImageReady)
{
if (!currentlyUsingCameraImage)
{
currentlyUsingCameraImage = true;
lock (asyncCopiedVideoImage)
{
if (downSampleVideo == DownSample.HalfSize)
{
imageForExternalUse.NewGraphics2D().Render(asyncCopiedVideoImage, 0, 0, 0, .5, .5);
}
else
{
imageForExternalUse.NewGraphics2D().Render(asyncCopiedVideoImage, 0, 0);
}
}
imageForExternalUse.MarkImageChanged();
newImageReady = false;
currentlyUsingCameraImage = false;
return true;
}
}
return false;
}
void source_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
if (!currentlyUsingCameraImage)
{
currentlyUsingCameraImage = true;
Bitmap bitmap = eventArgs.Frame;
if (bitmap.Width != asyncCopiedVideoImage.Width || bitmap.Height != asyncCopiedVideoImage.Height)
{
asyncCopiedVideoImage = new ImageBuffer(bitmap.Width, bitmap.Height, 32, new BlenderBGRA());
}
UpdateImageBuffer(asyncCopiedVideoImage, bitmap);
newImageReady = true;
currentlyUsingCameraImage = false;
}
}
public void TakeSnapShot()
{
videoCaptureDevice.Stop();
videoCaptureDevice.ProvideSnapshots = true;
videoCaptureDevice.SimulateTrigger();
videoCaptureDevice.Start();
}
void videoCaptureDevice_SnapshotFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bitmap = eventArgs.Frame;
bitmap.Save("snapshot.png");
}
// Close video source if it is running
public void CloseCurrentVideoSource()
{
if (videoCaptureDevice != null)
{
videoCaptureDevice.SignalToStop();
// wait ~ 3 seconds
for (int i = 0; i < 30; i++)
{
if (!videoCaptureDevice.IsRunning)
{
break;
}
System.Threading.Thread.Sleep(100);
}
if (videoCaptureDevice.IsRunning)
{
videoCaptureDevice.Stop();
}
videoCaptureDevice.Stop();
videoCaptureDevice = null;
}
}
internal void UpdateImageBuffer(ImageBuffer destImageBuffer, Bitmap sourceBitmap)
{
BitmapData bitmapData = null;
bool isLocked = false;
if (destImageBuffer != null)
{
if (!isLocked)
{
bitmapData = sourceBitmap.LockBits(new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height), System.Drawing.Imaging.ImageLockMode.ReadWrite, sourceBitmap.PixelFormat);
}
int destBufferStrideInBytes = destImageBuffer.StrideInBytes();
int destBufferHeight = destImageBuffer.Height;
int destBufferWidth = destImageBuffer.Width;
int destBufferHeightMinusOne = destBufferHeight - 1;
int bitmapDataStride = bitmapData.Stride;
int offset;
byte[] buffer = destImageBuffer.GetBuffer(out offset);
if (flipY)
{
unsafe
{
byte* bitmapDataScan0 = (byte*)bitmapData.Scan0;
fixed (byte* pDestFixed = &buffer[offset])
{
byte* pSource = bitmapDataScan0;
for (int y = 0; y < destBufferHeight; y++)
{
byte* pDest = pDestFixed + destBufferStrideInBytes * (destBufferHeight - 1 - y);
for (int x = 0; x < destBufferWidth; x++)
{
pDest[x * 4 + 0] = pSource[x * 3 + 0];
pDest[x * 4 + 1] = pSource[x * 3 + 1];
pDest[x * 4 + 2] = pSource[x * 3 + 2];
pDest[x * 4 + 3] = 255;
}
pSource += bitmapDataStride;
}
}
}
}
else
{
unsafe
{
byte* bitmapDataScan0 = (byte*)bitmapData.Scan0;
fixed (byte* pDestFixed = &buffer[offset])
{
byte* pSource = bitmapDataScan0;
for (int y = 0; y < destBufferHeight; y++)
{
byte* pDest = pDestFixed + destBufferStrideInBytes * (y);
for (int x = 0; x < destBufferWidth; x++)
{
pDest[x * 4 + 0] = pSource[x * 3 + 0];
pDest[x * 4 + 1] = pSource[x * 3 + 1];
pDest[x * 4 + 2] = pSource[x * 3 + 2];
pDest[x * 4 + 3] = 255;
}
pSource += bitmapDataStride;
}
}
}
}
if (!isLocked)
{
sourceBitmap.UnlockBits(bitmapData);
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using EditorBrowsableAttribute = System.ComponentModel.EditorBrowsableAttribute;
using EditorBrowsableState = System.ComponentModel.EditorBrowsableState;
using Internal.Runtime.CompilerServices;
#if BIT64
using nint = System.Int64;
using nuint = System.UInt64;
#else // BIT64
using nint = System.Int32;
using nuint = System.UInt32;
#endif // BIT64
namespace System
{
/// <summary>
/// Represents a contiguous region of memory, similar to <see cref="ReadOnlySpan{T}"/>.
/// Unlike <see cref="ReadOnlySpan{T}"/>, it is not a byref-like type.
/// </summary>
[DebuggerTypeProxy(typeof(MemoryDebugView<>))]
[DebuggerDisplay("{ToString(),raw}")]
public readonly struct ReadOnlyMemory<T> : IEquatable<ReadOnlyMemory<T>>
{
// NOTE: With the current implementation, Memory<T> and ReadOnlyMemory<T> must have the same layout,
// as code uses Unsafe.As to cast between them.
// The highest order bit of _index is used to discern whether _object is a pre-pinned array.
// (_index < 0) => _object is a pre-pinned array, so Pin() will not allocate a new GCHandle
// (else) => Pin() needs to allocate a new GCHandle to pin the object.
private readonly object? _object;
private readonly int _index;
private readonly int _length;
internal const int RemoveFlagsBitMask = 0x7FFFFFFF;
/// <summary>
/// Creates a new memory over the entirety of the target array.
/// </summary>
/// <param name="array">The target array.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[]? array)
{
if (array == null)
{
this = default;
return; // returns default
}
_object = array;
_index = 0;
_length = array.Length;
}
/// <summary>
/// Creates a new memory over the portion of the target array beginning
/// at 'start' index and ending at 'end' index (exclusive).
/// </summary>
/// <param name="array">The target array.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
/// <remarks>Returns default when <paramref name="array"/> is null.</remarks>
/// <exception cref="System.ArrayTypeMismatchException">Thrown when <paramref name="array"/> is covariant and array's type is not exactly T[].</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in the range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory(T[]? array, int start, int length)
{
if (array == null)
{
if (start != 0 || length != 0)
ThrowHelper.ThrowArgumentOutOfRangeException();
this = default;
return; // returns default
}
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)array.Length)
ThrowHelper.ThrowArgumentOutOfRangeException();
#else
if ((uint)start > (uint)array.Length || (uint)length > (uint)(array.Length - start))
ThrowHelper.ThrowArgumentOutOfRangeException();
#endif
_object = array;
_index = start;
_length = length;
}
/// <summary>Creates a new memory over the existing object, start, and length. No validation is performed.</summary>
/// <param name="obj">The target object.</param>
/// <param name="start">The index at which to begin the memory.</param>
/// <param name="length">The number of items in the memory.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlyMemory(object? obj, int start, int length)
{
// No validation performed in release builds; caller must provide any necessary validation.
// 'obj is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert((obj == null)
|| (typeof(T) == typeof(char) && obj is string)
#if FEATURE_UTF8STRING
|| ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && obj is Utf8String)
#endif // FEATURE_UTF8STRING
|| (obj is T[])
|| (obj is MemoryManager<T>));
_object = obj;
_index = start;
_length = length;
}
/// <summary>
/// Defines an implicit conversion of an array to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(T[]? array) => new ReadOnlyMemory<T>(array);
/// <summary>
/// Defines an implicit conversion of a <see cref="ArraySegment{T}"/> to a <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static implicit operator ReadOnlyMemory<T>(ArraySegment<T> segment) => new ReadOnlyMemory<T>(segment.Array, segment.Offset, segment.Count);
/// <summary>
/// Returns an empty <see cref="ReadOnlyMemory{T}"/>
/// </summary>
public static ReadOnlyMemory<T> Empty => default;
/// <summary>
/// The number of items in the memory.
/// </summary>
public int Length => _length;
/// <summary>
/// Returns true if Length is 0.
/// </summary>
public bool IsEmpty => _length == 0;
/// <summary>
/// For <see cref="ReadOnlyMemory{Char}"/>, returns a new instance of string that represents the characters pointed to by the memory.
/// Otherwise, returns a <see cref="string"/> with the name of the type and the number of elements.
/// </summary>
public override string ToString()
{
if (typeof(T) == typeof(char))
{
return (_object is string str) ? str.Substring(_index, _length) : Span.ToString();
}
#if FEATURE_UTF8STRING
else if (typeof(T) == typeof(Char8))
{
// TODO_UTF8STRING: Call into optimized transcoding routine when it's available.
ReadOnlySpan<T> span = Span;
return Encoding.UTF8.GetString(new ReadOnlySpan<byte>(ref Unsafe.As<T, byte>(ref MemoryMarshal.GetReference(span)), span.Length));
}
#endif // FEATURE_UTF8STRING
return string.Format("System.ReadOnlyMemory<{0}>[{1}]", typeof(T).Name, _length);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start'.
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start)
{
if ((uint)start > (uint)_length)
{
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
}
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, _length - start);
}
/// <summary>
/// Forms a slice out of the given memory, beginning at 'start', of given length
/// </summary>
/// <param name="start">The index at which to begin this slice.</param>
/// <param name="length">The desired length for the slice (exclusive).</param>
/// <exception cref="System.ArgumentOutOfRangeException">
/// Thrown when the specified <paramref name="start"/> or end index is not in range (<0 or >Length).
/// </exception>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlyMemory<T> Slice(int start, int length)
{
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)(uint)start + (ulong)(uint)length > (ulong)(uint)_length)
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#else
if ((uint)start > (uint)_length || (uint)length > (uint)(_length - start))
ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.start);
#endif
// It is expected for _index + start to be negative if the memory is already pre-pinned.
return new ReadOnlyMemory<T>(_object, _index + start, length);
}
/// <summary>
/// Returns a span from the memory.
/// </summary>
public unsafe ReadOnlySpan<T> Span
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
ref T refToReturn = ref Unsafe.AsRef<T>(null);
int lengthOfUnderlyingSpan = 0;
// Copy this field into a local so that it can't change out from under us mid-operation.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject.GetType() == typeof(string))
{
// Special-case string since it's the most common for ROM<char>.
refToReturn = ref Unsafe.As<char, T>(ref Unsafe.As<string>(tmpObject).GetRawStringData());
lengthOfUnderlyingSpan = Unsafe.As<string>(tmpObject).Length;
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject.GetType() == typeof(Utf8String))
{
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<Utf8String>(tmpObject).DangerousGetMutableReference());
lengthOfUnderlyingSpan = Unsafe.As<Utf8String>(tmpObject).Length;
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// We know the object is not null, it's not a string, and it is variable-length. The only
// remaining option is for it to be a T[] (or a U[] which is blittable to T[], like int[]
// and uint[]). Otherwise somebody used private reflection to set this field, and we're not
// too worried about type safety violations at this point.
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
refToReturn = ref Unsafe.As<byte, T>(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData());
lengthOfUnderlyingSpan = Unsafe.As<T[]>(tmpObject).Length;
}
else
{
// We know the object is not null, and it's not variable-length, so it must be a MemoryManager<T>.
// Otherwise somebody used private reflection to set this field, and we're not too worried about
// type safety violations at that point. Note that it can't be a MemoryManager<U>, even if U and
// T are blittable (e.g., MemoryManager<int> to MemoryManager<uint>), since there exists no
// constructor or other public API which would allow such a conversion.
Debug.Assert(tmpObject is MemoryManager<T>);
Span<T> memoryManagerSpan = Unsafe.As<MemoryManager<T>>(tmpObject).GetSpan();
refToReturn = ref MemoryMarshal.GetReference(memoryManagerSpan);
lengthOfUnderlyingSpan = memoryManagerSpan.Length;
}
// If the Memory<T> or ReadOnlyMemory<T> instance is torn, this property getter has undefined behavior.
// We try to detect this condition and throw an exception, but it's possible that a torn struct might
// appear to us to be valid, and we'll return an undesired span. Such a span is always guaranteed at
// least to be in-bounds when compared with the original Memory<T> instance, so using the span won't
// AV the process.
nuint desiredStartIndex = (uint)_index & (uint)RemoveFlagsBitMask;
int desiredLength = _length;
#if BIT64
// See comment in Span<T>.Slice for how this works.
if ((ulong)desiredStartIndex + (ulong)(uint)desiredLength > (ulong)(uint)lengthOfUnderlyingSpan)
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#else
if ((uint)desiredStartIndex > (uint)lengthOfUnderlyingSpan || (uint)desiredLength > (uint)(lengthOfUnderlyingSpan - desiredStartIndex))
{
ThrowHelper.ThrowArgumentOutOfRangeException();
}
#endif
refToReturn = ref Unsafe.Add(ref refToReturn, (IntPtr)(void*)desiredStartIndex);
lengthOfUnderlyingSpan = desiredLength;
}
return new ReadOnlySpan<T>(ref refToReturn, lengthOfUnderlyingSpan);
}
}
/// <summary>
/// Copies the contents of the read-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <param name="destination">The Memory to copy items into.</param>
/// <exception cref="System.ArgumentException">
/// Thrown when the destination is shorter than the source.
/// </exception>
/// </summary>
public void CopyTo(Memory<T> destination) => Span.CopyTo(destination.Span);
/// <summary>
/// Copies the contents of the readonly-only memory into the destination. If the source
/// and destination overlap, this method behaves as if the original values are in
/// a temporary location before the destination is overwritten.
///
/// <returns>If the destination is shorter than the source, this method
/// return false and no data is written to the destination.</returns>
/// </summary>
/// <param name="destination">The span to copy items into.</param>
public bool TryCopyTo(Memory<T> destination) => Span.TryCopyTo(destination.Span);
/// <summary>
/// Creates a handle for the memory.
/// The GC will not move the memory until the returned <see cref="MemoryHandle"/>
/// is disposed, enabling taking and using the memory's address.
/// <exception cref="System.ArgumentException">
/// An instance with nonprimitive (non-blittable) members cannot be pinned.
/// </exception>
/// </summary>
public unsafe MemoryHandle Pin()
{
// It's possible that the below logic could result in an AV if the struct
// is torn. This is ok since the caller is expecting to use raw pointers,
// and we're not required to keep this as safe as the other Span-based APIs.
object? tmpObject = _object;
if (tmpObject != null)
{
if (typeof(T) == typeof(char) && tmpObject is string s)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref char stringData = ref Unsafe.Add(ref s.GetRawStringData(), _index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#if FEATURE_UTF8STRING
else if ((typeof(T) == typeof(byte) || typeof(T) == typeof(Char8)) && tmpObject is Utf8String utf8String)
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
ref byte stringData = ref utf8String.DangerousGetMutableReference(_index);
return new MemoryHandle(Unsafe.AsPointer(ref stringData), handle);
}
#endif // FEATURE_UTF8STRING
else if (RuntimeHelpers.ObjectHasComponentSize(tmpObject))
{
// 'tmpObject is T[]' below also handles things like int[] <-> uint[] being convertible
Debug.Assert(tmpObject is T[]);
// Array is already pre-pinned
if (_index < 0)
{
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index & RemoveFlagsBitMask);
return new MemoryHandle(pointer);
}
else
{
GCHandle handle = GCHandle.Alloc(tmpObject, GCHandleType.Pinned);
void* pointer = Unsafe.Add<T>(Unsafe.AsPointer(ref Unsafe.As<T[]>(tmpObject).GetRawSzArrayData()), _index);
return new MemoryHandle(pointer, handle);
}
}
else
{
Debug.Assert(tmpObject is MemoryManager<T>);
return Unsafe.As<MemoryManager<T>>(tmpObject).Pin(_index);
}
}
return default;
}
/// <summary>
/// Copies the contents from the memory into a new array. This heap
/// allocates, so should generally be avoided, however it is sometimes
/// necessary to bridge the gap with APIs written in terms of arrays.
/// </summary>
public T[] ToArray() => Span.ToArray();
/// <summary>Determines whether the specified object is equal to the current object.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override bool Equals(object? obj)
{
if (obj is ReadOnlyMemory<T> readOnlyMemory)
{
return Equals(readOnlyMemory);
}
else if (obj is Memory<T> memory)
{
return Equals(memory);
}
else
{
return false;
}
}
/// <summary>
/// Returns true if the memory points to the same array and has the same length. Note that
/// this does *not* check to see if the *contents* are equal.
/// </summary>
public bool Equals(ReadOnlyMemory<T> other)
{
return
_object == other._object &&
_index == other._index &&
_length == other._length;
}
/// <summary>Returns the hash code for this <see cref="ReadOnlyMemory{T}"/></summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public override int GetHashCode()
{
// We use RuntimeHelpers.GetHashCode instead of Object.GetHashCode because the hash
// code is based on object identity and referential equality, not deep equality (as common with string).
return (_object != null) ? HashCode.Combine(RuntimeHelpers.GetHashCode(_object), _index, _length) : 0;
}
/// <summary>Gets the state of the memory as individual fields.</summary>
/// <param name="start">The offset.</param>
/// <param name="length">The count.</param>
/// <returns>The object.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal object? GetObjectStartLength(out int start, out int length)
{
start = _index;
length = _length;
return _object;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// Timetable Quilt Headers
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class TH : EduHubEntity
{
#region Navigation Property Cache
private TT Cache_TT01KEY_TT;
private TT Cache_TT02KEY_TT;
private TT Cache_TT03KEY_TT;
private TT Cache_TT04KEY_TT;
private TT Cache_TT05KEY_TT;
private TT Cache_TT06KEY_TT;
private TT Cache_TT07KEY_TT;
private TT Cache_TT08KEY_TT;
private TT Cache_TT09KEY_TT;
private TT Cache_TT10KEY_TT;
private TT Cache_TT11KEY_TT;
private TT Cache_TT12KEY_TT;
private TT Cache_TT13KEY_TT;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<KCC> Cache_THKEY_KCC_CURRENT_QUILT;
private IReadOnlyList<SCI> Cache_THKEY_SCI_CURRENT_QUILT;
private IReadOnlyList<SCL> Cache_THKEY_SCL_QUILT;
private IReadOnlyList<SFAQ> Cache_THKEY_SFAQ_QKEY;
private IReadOnlyList<SMAQ> Cache_THKEY_SMAQ_QKEY;
private IReadOnlyList<TCTD> Cache_THKEY_TCTD_QKEY;
private IReadOnlyList<TCTQ> Cache_THKEY_TCTQ_QKEY;
private IReadOnlyList<THTN> Cache_THKEY_THTN_QKEY;
private IReadOnlyList<THTQ> Cache_THKEY_THTQ_QKEY;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Quilt code
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string THKEY { get; internal set; }
/// <summary>
/// Quilt title
/// [Alphanumeric (30)]
/// </summary>
public string TITLE { get; internal set; }
/// <summary>
/// Can this template be selected by general users
/// [Alphanumeric (1)]
/// </summary>
public string SELECTABLE { get; internal set; }
/// <summary>
/// Number of rows
/// </summary>
public short? THROWS { get; internal set; }
/// <summary>
/// Number of columns
/// </summary>
public short? THCOLS { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL01 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL02 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL03 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL04 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL05 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL06 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL07 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL08 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL09 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL10 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL11 { get; internal set; }
/// <summary>
/// Labels for rows (periods)
/// [Alphanumeric (10)]
/// </summary>
public string TH_RLABEL12 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL01 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL02 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL03 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL04 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL05 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL06 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL07 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL08 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL09 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL10 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL11 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL12 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL13 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL14 { get; internal set; }
/// <summary>
/// Labels for columns (days)
/// [Alphanumeric (10)]
/// </summary>
public string TH_CLABEL15 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD01 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD02 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD03 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD04 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD05 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD06 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD07 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD08 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD09 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD10 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD11 { get; internal set; }
/// <summary>
/// Teaching period for student absence
/// </summary>
public short? TEACHING_PERIOD12 { get; internal set; }
/// <summary>
/// Link to 1st template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT01KEY { get; internal set; }
/// <summary>
/// Link to 2nd template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT02KEY { get; internal set; }
/// <summary>
/// Link to 3rd template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT03KEY { get; internal set; }
/// <summary>
/// Link to 4th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT04KEY { get; internal set; }
/// <summary>
/// Link to 5th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT05KEY { get; internal set; }
/// <summary>
/// Link to 6th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT06KEY { get; internal set; }
/// <summary>
/// Link to 7th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT07KEY { get; internal set; }
/// <summary>
/// Link to 8th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT08KEY { get; internal set; }
/// <summary>
/// Link to 9th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT09KEY { get; internal set; }
/// <summary>
/// Link to 10th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT10KEY { get; internal set; }
/// <summary>
/// Link to 11th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT11KEY { get; internal set; }
/// <summary>
/// Link to 12th template in timetable
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT12KEY { get; internal set; }
/// <summary>
/// Link to 13th template in timetable (maximum)
/// [Uppercase Alphanumeric (8)]
/// </summary>
public string TT13KEY { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT01 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT02 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT03 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT04 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT05 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT06 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT07 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT08 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT09 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT10 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT11 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT12 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Quilts
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_QUILT13 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA01 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA02 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA03 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA04 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA05 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA06 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA07 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA08 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA09 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA10 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA11 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA12 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Extras
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXTRA13 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM01 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM02 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM03 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM04 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM05 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM06 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM07 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM08 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM09 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM10 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM11 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM12 { get; internal set; }
/// <summary>
/// Which templates displayed when editing in Exams
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string THVIEW_EXAM13 { get; internal set; }
/// <summary>
/// First day in the calendar
/// </summary>
public DateTime? CALENDAR_START01 { get; internal set; }
/// <summary>
/// First day in the calendar
/// </summary>
public DateTime? CALENDAR_START02 { get; internal set; }
/// <summary>
/// First day in the calendar
/// </summary>
public DateTime? CALENDAR_START03 { get; internal set; }
/// <summary>
/// First day in the calendar
/// </summary>
public DateTime? CALENDAR_START04 { get; internal set; }
/// <summary>
/// Last Day in calendar
/// </summary>
public DateTime? CALENDAR_END01 { get; internal set; }
/// <summary>
/// Last Day in calendar
/// </summary>
public DateTime? CALENDAR_END02 { get; internal set; }
/// <summary>
/// Last Day in calendar
/// </summary>
public DateTime? CALENDAR_END03 { get; internal set; }
/// <summary>
/// Last Day in calendar
/// </summary>
public DateTime? CALENDAR_END04 { get; internal set; }
/// <summary>
/// Display colour
/// </summary>
public int? CALENDAR_COLOUR { get; internal set; }
/// <summary>
/// Placement method R=rotate M=Day match
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_PLACE_METHOD { get; internal set; }
/// <summary>
/// Days quilt may be on the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_DAYS01 { get; internal set; }
/// <summary>
/// Days quilt may be on the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_DAYS02 { get; internal set; }
/// <summary>
/// Days quilt may be on the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_DAYS03 { get; internal set; }
/// <summary>
/// Days quilt may be on the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_DAYS04 { get; internal set; }
/// <summary>
/// Days quilt may be on the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_DAYS05 { get; internal set; }
/// <summary>
/// Days quilt may be on the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_DAYS06 { get; internal set; }
/// <summary>
/// Days quilt may be on the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_DAYS07 { get; internal set; }
/// <summary>
/// Row to place the quilt on
/// </summary>
public short? CALENDAR_ROW { get; internal set; }
/// <summary>
/// View this quilt in the calendar
/// [Uppercase Alphanumeric (1)]
/// </summary>
public string CALENDAR_VIEW { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last write operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT01KEY]->[TT.TTKEY]
/// Link to 1st template in timetable
/// </summary>
public TT TT01KEY_TT
{
get
{
if (TT01KEY == null)
{
return null;
}
if (Cache_TT01KEY_TT == null)
{
Cache_TT01KEY_TT = Context.TT.FindByTTKEY(TT01KEY);
}
return Cache_TT01KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT02KEY]->[TT.TTKEY]
/// Link to 2nd template in timetable
/// </summary>
public TT TT02KEY_TT
{
get
{
if (TT02KEY == null)
{
return null;
}
if (Cache_TT02KEY_TT == null)
{
Cache_TT02KEY_TT = Context.TT.FindByTTKEY(TT02KEY);
}
return Cache_TT02KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT03KEY]->[TT.TTKEY]
/// Link to 3rd template in timetable
/// </summary>
public TT TT03KEY_TT
{
get
{
if (TT03KEY == null)
{
return null;
}
if (Cache_TT03KEY_TT == null)
{
Cache_TT03KEY_TT = Context.TT.FindByTTKEY(TT03KEY);
}
return Cache_TT03KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT04KEY]->[TT.TTKEY]
/// Link to 4th template in timetable
/// </summary>
public TT TT04KEY_TT
{
get
{
if (TT04KEY == null)
{
return null;
}
if (Cache_TT04KEY_TT == null)
{
Cache_TT04KEY_TT = Context.TT.FindByTTKEY(TT04KEY);
}
return Cache_TT04KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT05KEY]->[TT.TTKEY]
/// Link to 5th template in timetable
/// </summary>
public TT TT05KEY_TT
{
get
{
if (TT05KEY == null)
{
return null;
}
if (Cache_TT05KEY_TT == null)
{
Cache_TT05KEY_TT = Context.TT.FindByTTKEY(TT05KEY);
}
return Cache_TT05KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT06KEY]->[TT.TTKEY]
/// Link to 6th template in timetable
/// </summary>
public TT TT06KEY_TT
{
get
{
if (TT06KEY == null)
{
return null;
}
if (Cache_TT06KEY_TT == null)
{
Cache_TT06KEY_TT = Context.TT.FindByTTKEY(TT06KEY);
}
return Cache_TT06KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT07KEY]->[TT.TTKEY]
/// Link to 7th template in timetable
/// </summary>
public TT TT07KEY_TT
{
get
{
if (TT07KEY == null)
{
return null;
}
if (Cache_TT07KEY_TT == null)
{
Cache_TT07KEY_TT = Context.TT.FindByTTKEY(TT07KEY);
}
return Cache_TT07KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT08KEY]->[TT.TTKEY]
/// Link to 8th template in timetable
/// </summary>
public TT TT08KEY_TT
{
get
{
if (TT08KEY == null)
{
return null;
}
if (Cache_TT08KEY_TT == null)
{
Cache_TT08KEY_TT = Context.TT.FindByTTKEY(TT08KEY);
}
return Cache_TT08KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT09KEY]->[TT.TTKEY]
/// Link to 9th template in timetable
/// </summary>
public TT TT09KEY_TT
{
get
{
if (TT09KEY == null)
{
return null;
}
if (Cache_TT09KEY_TT == null)
{
Cache_TT09KEY_TT = Context.TT.FindByTTKEY(TT09KEY);
}
return Cache_TT09KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT10KEY]->[TT.TTKEY]
/// Link to 10th template in timetable
/// </summary>
public TT TT10KEY_TT
{
get
{
if (TT10KEY == null)
{
return null;
}
if (Cache_TT10KEY_TT == null)
{
Cache_TT10KEY_TT = Context.TT.FindByTTKEY(TT10KEY);
}
return Cache_TT10KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT11KEY]->[TT.TTKEY]
/// Link to 11th template in timetable
/// </summary>
public TT TT11KEY_TT
{
get
{
if (TT11KEY == null)
{
return null;
}
if (Cache_TT11KEY_TT == null)
{
Cache_TT11KEY_TT = Context.TT.FindByTTKEY(TT11KEY);
}
return Cache_TT11KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT12KEY]->[TT.TTKEY]
/// Link to 12th template in timetable
/// </summary>
public TT TT12KEY_TT
{
get
{
if (TT12KEY == null)
{
return null;
}
if (Cache_TT12KEY_TT == null)
{
Cache_TT12KEY_TT = Context.TT.FindByTTKEY(TT12KEY);
}
return Cache_TT12KEY_TT;
}
}
/// <summary>
/// TT (Timetable Grid Templates) related entity by [TH.TT13KEY]->[TT.TTKEY]
/// Link to 13th template in timetable (maximum)
/// </summary>
public TT TT13KEY_TT
{
get
{
if (TT13KEY == null)
{
return null;
}
if (Cache_TT13KEY_TT == null)
{
Cache_TT13KEY_TT = Context.TT.FindByTTKEY(TT13KEY);
}
return Cache_TT13KEY_TT;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// KCC (Calendar Dates for Absences) related entities by [TH.THKEY]->[KCC.CURRENT_QUILT]
/// Quilt code
/// </summary>
public IReadOnlyList<KCC> THKEY_KCC_CURRENT_QUILT
{
get
{
if (Cache_THKEY_KCC_CURRENT_QUILT == null &&
!Context.KCC.TryFindByCURRENT_QUILT(THKEY, out Cache_THKEY_KCC_CURRENT_QUILT))
{
Cache_THKEY_KCC_CURRENT_QUILT = new List<KCC>().AsReadOnly();
}
return Cache_THKEY_KCC_CURRENT_QUILT;
}
}
/// <summary>
/// SCI (School Information) related entities by [TH.THKEY]->[SCI.CURRENT_QUILT]
/// Quilt code
/// </summary>
public IReadOnlyList<SCI> THKEY_SCI_CURRENT_QUILT
{
get
{
if (Cache_THKEY_SCI_CURRENT_QUILT == null &&
!Context.SCI.TryFindByCURRENT_QUILT(THKEY, out Cache_THKEY_SCI_CURRENT_QUILT))
{
Cache_THKEY_SCI_CURRENT_QUILT = new List<SCI>().AsReadOnly();
}
return Cache_THKEY_SCI_CURRENT_QUILT;
}
}
/// <summary>
/// SCL (Subject Classes) related entities by [TH.THKEY]->[SCL.QUILT]
/// Quilt code
/// </summary>
public IReadOnlyList<SCL> THKEY_SCL_QUILT
{
get
{
if (Cache_THKEY_SCL_QUILT == null &&
!Context.SCL.TryFindByQUILT(THKEY, out Cache_THKEY_SCL_QUILT))
{
Cache_THKEY_SCL_QUILT = new List<SCL>().AsReadOnly();
}
return Cache_THKEY_SCL_QUILT;
}
}
/// <summary>
/// SFAQ (Staff Availability in Quilt) related entities by [TH.THKEY]->[SFAQ.QKEY]
/// Quilt code
/// </summary>
public IReadOnlyList<SFAQ> THKEY_SFAQ_QKEY
{
get
{
if (Cache_THKEY_SFAQ_QKEY == null &&
!Context.SFAQ.TryFindByQKEY(THKEY, out Cache_THKEY_SFAQ_QKEY))
{
Cache_THKEY_SFAQ_QKEY = new List<SFAQ>().AsReadOnly();
}
return Cache_THKEY_SFAQ_QKEY;
}
}
/// <summary>
/// SMAQ (Room Availability in Quilt) related entities by [TH.THKEY]->[SMAQ.QKEY]
/// Quilt code
/// </summary>
public IReadOnlyList<SMAQ> THKEY_SMAQ_QKEY
{
get
{
if (Cache_THKEY_SMAQ_QKEY == null &&
!Context.SMAQ.TryFindByQKEY(THKEY, out Cache_THKEY_SMAQ_QKEY))
{
Cache_THKEY_SMAQ_QKEY = new List<SMAQ>().AsReadOnly();
}
return Cache_THKEY_SMAQ_QKEY;
}
}
/// <summary>
/// TCTD (Calendar Period Information) related entities by [TH.THKEY]->[TCTD.QKEY]
/// Quilt code
/// </summary>
public IReadOnlyList<TCTD> THKEY_TCTD_QKEY
{
get
{
if (Cache_THKEY_TCTD_QKEY == null &&
!Context.TCTD.TryFindByQKEY(THKEY, out Cache_THKEY_TCTD_QKEY))
{
Cache_THKEY_TCTD_QKEY = new List<TCTD>().AsReadOnly();
}
return Cache_THKEY_TCTD_QKEY;
}
}
/// <summary>
/// TCTQ (Calendar Class Information) related entities by [TH.THKEY]->[TCTQ.QKEY]
/// Quilt code
/// </summary>
public IReadOnlyList<TCTQ> THKEY_TCTQ_QKEY
{
get
{
if (Cache_THKEY_TCTQ_QKEY == null &&
!Context.TCTQ.TryFindByQKEY(THKEY, out Cache_THKEY_TCTQ_QKEY))
{
Cache_THKEY_TCTQ_QKEY = new List<TCTQ>().AsReadOnly();
}
return Cache_THKEY_TCTQ_QKEY;
}
}
/// <summary>
/// THTN (Timetable Labels) related entities by [TH.THKEY]->[THTN.QKEY]
/// Quilt code
/// </summary>
public IReadOnlyList<THTN> THKEY_THTN_QKEY
{
get
{
if (Cache_THKEY_THTN_QKEY == null &&
!Context.THTN.TryFindByQKEY(THKEY, out Cache_THKEY_THTN_QKEY))
{
Cache_THKEY_THTN_QKEY = new List<THTN>().AsReadOnly();
}
return Cache_THKEY_THTN_QKEY;
}
}
/// <summary>
/// THTQ (Timetable Quilt Entries) related entities by [TH.THKEY]->[THTQ.QKEY]
/// Quilt code
/// </summary>
public IReadOnlyList<THTQ> THKEY_THTQ_QKEY
{
get
{
if (Cache_THKEY_THTQ_QKEY == null &&
!Context.THTQ.TryFindByQKEY(THKEY, out Cache_THKEY_THTQ_QKEY))
{
Cache_THKEY_THTQ_QKEY = new List<THTQ>().AsReadOnly();
}
return Cache_THKEY_THTQ_QKEY;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
namespace System.Net.Sockets
{
public partial class SocketAsyncEventArgs : EventArgs, IDisposable
{
// AcceptSocket property variables.
internal Socket _acceptSocket;
private Socket _connectSocket;
// Buffer,Offset,Count property variables.
internal byte[] _buffer;
internal int _count;
internal int _offset;
// BufferList property variables.
internal IList<ArraySegment<byte>> _bufferList;
// BytesTransferred property variables.
private int _bytesTransferred;
// Completed event property variables.
private event EventHandler<SocketAsyncEventArgs> _completed;
private bool _completedChanged;
// DisconnectReuseSocket propery variables.
private bool _disconnectReuseSocket;
// LastOperation property variables.
private SocketAsyncOperation _completedOperation;
// ReceiveMessageFromPacketInfo property variables.
private IPPacketInformation _receiveMessageFromPacketInfo;
// RemoteEndPoint property variables.
private EndPoint _remoteEndPoint;
// SendPacketsFlags property variable.
internal TransmitFileOptions _sendPacketsFlags;
// SendPacketsSendSize property variable.
internal int _sendPacketsSendSize;
// SendPacketsElements property variables.
internal SendPacketsElement[] _sendPacketsElements;
// SocketError property variables.
private SocketError _socketError;
private Exception _connectByNameError;
// SocketFlags property variables.
internal SocketFlags _socketFlags;
// UserToken property variables.
private object _userToken;
// Internal buffer for AcceptEx when Buffer not supplied.
internal byte[] _acceptBuffer;
internal int _acceptAddressBufferCount;
// Internal SocketAddress buffer.
internal Internals.SocketAddress _socketAddress;
// Misc state variables.
private ExecutionContext _context;
private ExecutionContext _contextCopy;
private ContextCallback _executionCallback;
private Socket _currentSocket;
private bool _disposeCalled;
// Controls thread safety via Interlocked.
private const int Configuring = -1;
private const int Free = 0;
private const int InProgress = 1;
private const int Disposed = 2;
private int _operating;
private MultipleConnectAsync _multipleConnect;
private static bool s_loggingEnabled = Logging.On;
public SocketAsyncEventArgs()
{
_executionCallback = new ContextCallback(ExecutionCallback);
InitializeInternals();
}
public Socket AcceptSocket
{
get { return _acceptSocket; }
set { _acceptSocket = value; }
}
public Socket ConnectSocket
{
get { return _connectSocket; }
}
public byte[] Buffer
{
get { return _buffer; }
}
public int Offset
{
get { return _offset; }
}
public int Count
{
get { return _count; }
}
// NOTE: this property is mutually exclusive with Buffer.
// Setting this property with an existing non-null Buffer will throw.
public IList<ArraySegment<byte>> BufferList
{
get { return _bufferList; }
set
{
StartConfiguring();
try
{
if (value != null && _buffer != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "Buffer"));
}
_bufferList = value;
SetupMultipleBuffers();
}
finally
{
Complete();
}
}
}
public int BytesTransferred
{
get { return _bytesTransferred; }
}
public event EventHandler<SocketAsyncEventArgs> Completed
{
add
{
_completed += value;
_completedChanged = true;
}
remove
{
_completed -= value;
_completedChanged = true;
}
}
protected virtual void OnCompleted(SocketAsyncEventArgs e)
{
EventHandler<SocketAsyncEventArgs> handler = _completed;
if (handler != null)
{
handler(e._currentSocket, e);
}
}
public bool DisconnectReuseSocket
{
get { return _disconnectReuseSocket; }
set { _disconnectReuseSocket = value; }
}
public SocketAsyncOperation LastOperation
{
get { return _completedOperation; }
}
public IPPacketInformation ReceiveMessageFromPacketInfo
{
get { return _receiveMessageFromPacketInfo; }
}
public EndPoint RemoteEndPoint
{
get { return _remoteEndPoint; }
set { _remoteEndPoint = value; }
}
public SendPacketsElement[] SendPacketsElements
{
get { return _sendPacketsElements; }
set
{
StartConfiguring();
try
{
_sendPacketsElements = value;
SetupSendPacketsElements();
}
finally
{
Complete();
}
}
}
public TransmitFileOptions SendPacketsFlags
{
get { return _sendPacketsFlags; }
set { _sendPacketsFlags = value; }
}
public int SendPacketsSendSize
{
get { return _sendPacketsSendSize; }
set { _sendPacketsSendSize = value; }
}
public SocketError SocketError
{
get { return _socketError; }
set { _socketError = value; }
}
public Exception ConnectByNameError
{
get { return _connectByNameError; }
}
public SocketFlags SocketFlags
{
get { return _socketFlags; }
set { _socketFlags = value; }
}
public object UserToken
{
get { return _userToken; }
set { _userToken = value; }
}
public void SetBuffer(byte[] buffer, int offset, int count)
{
SetBufferInternal(buffer, offset, count);
}
public void SetBuffer(int offset, int count)
{
SetBufferInternal(_buffer, offset, count);
}
private void SetBufferInternal(byte[] buffer, int offset, int count)
{
StartConfiguring();
try
{
if (buffer == null)
{
// Clear out existing buffer.
_buffer = null;
_offset = 0;
_count = 0;
}
else
{
// Can't have both Buffer and BufferList.
if (_bufferList != null)
{
throw new ArgumentException(SR.Format(SR.net_ambiguousbuffers, "BufferList"));
}
// Offset and count can't be negative and the
// combination must be in bounds of the array.
if (offset < 0 || offset > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset");
}
if (count < 0 || count > (buffer.Length - offset))
{
throw new ArgumentOutOfRangeException("count");
}
_buffer = buffer;
_offset = offset;
_count = count;
}
// Pin new or unpin old buffer if necessary.
SetupSingleBuffer();
}
finally
{
Complete();
}
}
internal void SetResults(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
_socketError = socketError;
_connectByNameError = null;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
}
internal void SetResults(Exception exception, int bytesTransferred, SocketFlags flags)
{
_connectByNameError = exception;
_bytesTransferred = bytesTransferred;
_socketFlags = flags;
if (exception == null)
{
_socketError = SocketError.Success;
}
else
{
SocketException socketException = exception as SocketException;
if (socketException != null)
{
_socketError = socketException.SocketErrorCode;
}
else
{
_socketError = SocketError.SocketError;
}
}
}
private void ExecutionCallback(object ignored)
{
OnCompleted(this);
}
// Marks this object as no longer "in-use". Will also execute a Dispose deferred
// because I/O was in progress.
internal void Complete()
{
// Mark as not in-use.
_operating = Free;
InnerComplete();
// Check for deferred Dispose().
// The deferred Dispose is not guaranteed if Dispose is called while an operation is in progress.
// The _disposeCalled variable is not managed in a thread-safe manner on purpose for performance.
if (_disposeCalled)
{
Dispose();
}
}
// Dispose call to implement IDisposable.
public void Dispose()
{
// Remember that Dispose was called.
_disposeCalled = true;
// Check if this object is in-use for an async socket operation.
if (Interlocked.CompareExchange(ref _operating, Disposed, Free) != Free)
{
// Either already disposed or will be disposed when current operation completes.
return;
}
// OK to dispose now.
FreeInternals(false);
// Don't bother finalizing later.
GC.SuppressFinalize(this);
}
~SocketAsyncEventArgs()
{
FreeInternals(true);
}
// NOTE: Use a try/finally to make sure Complete is called when you're done
private void StartConfiguring()
{
int status = Interlocked.CompareExchange(ref _operating, Configuring, Free);
if (status == InProgress || status == Configuring)
{
throw new InvalidOperationException(SR.net_socketopinprogress);
}
else if (status == Disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
// Prepares for a native async socket call.
// This method performs the tasks common to all socket operations.
internal void StartOperationCommon(Socket socket)
{
// Change status to "in-use".
if (Interlocked.CompareExchange(ref _operating, InProgress, Free) != Free)
{
// If it was already "in-use" check if Dispose was called.
if (_disposeCalled)
{
// Dispose was called - throw ObjectDisposed.
throw new ObjectDisposedException(GetType().FullName);
}
// Only one at a time.
throw new InvalidOperationException(SR.net_socketopinprogress);
}
// Prepare execution context for callback.
if (ExecutionContext.IsFlowSuppressed())
{
// Fast path for when flow is suppressed.
_context = null;
_contextCopy = null;
}
else
{
// Flow is not suppressed.
// If event delegates have changed or socket has changed
// then discard any existing context.
if (_completedChanged || socket != _currentSocket)
{
_completedChanged = false;
_context = null;
_contextCopy = null;
}
// Capture execution context if none already.
if (_context == null)
{
_context = ExecutionContext.Capture();
}
// If there is an execution context we need a fresh copy for each completion.
if (_context != null)
{
_contextCopy = _context.CreateCopy();
}
}
// Remember current socket.
_currentSocket = socket;
}
internal void StartOperationAccept()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Accept;
// AcceptEx needs a single buffer with room for two special sockaddr data structures.
// It can also take additional buffer space in front of those special sockaddr
// structures that can be filled in with initial data coming in on a connection.
// First calculate the special AcceptEx address buffer size.
// It is the size of two native sockaddr buffers with 16 extra bytes each.
// The native sockaddr buffers vary by address family so must reference the current socket.
_acceptAddressBufferCount = 2 * (_currentSocket._rightEndPoint.Serialize().Size + 16);
// If our caller specified a buffer (willing to get received data with the Accept) then
// it needs to be large enough for the two special sockaddr buffers that AcceptEx requires.
// Throw if that buffer is not large enough.
bool userSuppliedBuffer = _buffer != null;
if (userSuppliedBuffer)
{
// Caller specified a buffer - see if it is large enough
if (_count < _acceptAddressBufferCount)
{
throw new ArgumentException(SR.Format(SR.net_buffercounttoosmall, "Count"));
}
// Buffer is already pinned if necessary.
}
else
{
// Caller didn't specify a buffer so use an internal one.
// See if current internal one is big enough, otherwise create a new one.
if (_acceptBuffer == null || _acceptBuffer.Length < _acceptAddressBufferCount)
{
_acceptBuffer = new byte[_acceptAddressBufferCount];
}
}
InnerStartOperationAccept(userSuppliedBuffer);
}
internal void StartOperationConnect()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = null;
_connectSocket = null;
InnerStartOperationConnect();
}
internal void StartOperationWrapperConnect(MultipleConnectAsync args)
{
_completedOperation = SocketAsyncOperation.Connect;
_multipleConnect = args;
_connectSocket = null;
}
internal void CancelConnectAsync()
{
if (_operating == InProgress && _completedOperation == SocketAsyncOperation.Connect)
{
if (_multipleConnect != null)
{
// If a multiple connect is in progress, abort it.
_multipleConnect.Cancel();
}
else
{
// Otherwise we're doing a normal ConnectAsync - cancel it by closing the socket.
// _currentSocket will only be null if _multipleConnect was set, so we don't have to check.
GlobalLog.Assert(_currentSocket != null, "SocketAsyncEventArgs::CancelConnectAsync - CurrentSocket and MultipleConnect both null!");
_currentSocket.Dispose();
}
}
}
internal void StartOperationDisconnect()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Disconnect;
InnerStartOperationDisconnect();
}
internal void StartOperationReceive()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Receive;
InnerStartOperationReceive();
}
internal void StartOperationReceiveFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveFrom;
InnerStartOperationReceiveFrom();
}
internal void StartOperationReceiveMessageFrom()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.ReceiveMessageFrom;
InnerStartOperationReceiveMessageFrom();
}
internal void StartOperationSend()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.Send;
InnerStartOperationSend();
}
internal void StartOperationSendPackets()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendPackets;
InnerStartOperationSendPackets();
}
internal void StartOperationSendTo()
{
// Remember the operation type.
_completedOperation = SocketAsyncOperation.SendTo;
InnerStartOperationSendTo();
}
internal void UpdatePerfCounters(int size, bool sendOp)
{
if (sendOp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesSent, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsSent);
}
}
else
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketBytesReceived, size);
if (_currentSocket.Transport == TransportType.Udp)
{
SocketPerfCounter.Instance.Increment(SocketPerfCounterName.SocketDatagramsReceived);
}
}
}
internal void FinishOperationSyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
Complete();
}
internal void FinishConnectByNameSyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(_socketError);
}
Complete();
}
internal void FinishOperationAsyncFailure(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
// This will be null if we're doing a static ConnectAsync to a DnsEndPoint with AddressFamily.Unspecified;
// the attempt socket will be closed anyways, so not updating the state is OK.
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_contextCopy, _executionCallback, null);
}
}
internal void FinishOperationAsyncFailure(Exception exception, int bytesTransferred, SocketFlags flags)
{
SetResults(exception, bytesTransferred, flags);
if (_currentSocket != null)
{
_currentSocket.UpdateStatusAfterSocketError(_socketError);
}
Complete();
if (_context == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_contextCopy, _executionCallback, null);
}
}
internal void FinishWrapperConnectSuccess(Socket connectSocket, int bytesTransferred, SocketFlags flags)
{
SetResults(SocketError.Success, bytesTransferred, flags);
_currentSocket = connectSocket;
_connectSocket = connectSocket;
// Complete the operation and raise the event.
Complete();
if (_contextCopy == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_contextCopy, _executionCallback, null);
}
}
internal void FinishOperationSuccess(SocketError socketError, int bytesTransferred, SocketFlags flags)
{
SetResults(socketError, bytesTransferred, flags);
switch (_completedOperation)
{
case SocketAsyncOperation.Accept:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Get the endpoint.
Internals.SocketAddress remoteSocketAddress = IPEndPointExtensions.Serialize(_currentSocket._rightEndPoint);
socketError = FinishOperationAccept(remoteSocketAddress);
if (socketError == SocketError.Success)
{
_acceptSocket = _currentSocket.UpdateAcceptSocket(_acceptSocket, _currentSocket._rightEndPoint.Create(remoteSocketAddress));
if (s_loggingEnabled)
Logging.PrintInfo(Logging.Sockets, _acceptSocket, SR.Format(SR.net_log_socket_accepted, _acceptSocket.RemoteEndPoint, _acceptSocket.LocalEndPoint));
}
else
{
SetResults(socketError, bytesTransferred, SocketFlags.None);
_acceptSocket = null;
}
break;
case SocketAsyncOperation.Connect:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
socketError = FinishOperationConnect();
// Mark socket connected.
if (socketError == SocketError.Success)
{
if (s_loggingEnabled)
Logging.PrintInfo(Logging.Sockets, _currentSocket, SR.Format(SR.net_log_socket_connected, _currentSocket.LocalEndPoint, _currentSocket.RemoteEndPoint));
_currentSocket.SetToConnected();
_connectSocket = _currentSocket;
}
break;
case SocketAsyncOperation.Disconnect:
_currentSocket.SetToDisconnected();
_currentSocket._remoteEndPoint = null;
break;
case SocketAsyncOperation.Receive:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
break;
case SocketAsyncOperation.ReceiveFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
Internals.SocketAddress socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
break;
case SocketAsyncOperation.ReceiveMessageFrom:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, false);
}
}
// Deal with incoming address.
_socketAddress.InternalSize = GetSocketAddressSize();
socketAddressOriginal = IPEndPointExtensions.Serialize(_remoteEndPoint);
if (!socketAddressOriginal.Equals(_socketAddress))
{
try
{
_remoteEndPoint = _remoteEndPoint.Create(_socketAddress);
}
catch
{
}
}
FinishOperationReceiveMessageFrom();
break;
case SocketAsyncOperation.Send:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
case SocketAsyncOperation.SendPackets:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogSendPacketsBuffers(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
FinishOperationSendPackets();
break;
case SocketAsyncOperation.SendTo:
if (bytesTransferred > 0)
{
// Log and Perf counters.
if (s_loggingEnabled)
{
LogBuffer(bytesTransferred);
}
if (Socket.s_perfCountersEnabled)
{
UpdatePerfCounters(bytesTransferred, true);
}
}
break;
}
if (socketError != SocketError.Success)
{
// Asynchronous failure or something went wrong after async success.
SetResults(socketError, bytesTransferred, flags);
_currentSocket.UpdateStatusAfterSocketError(socketError);
}
// Complete the operation and raise completion event.
Complete();
if (_contextCopy == null)
{
OnCompleted(this);
}
else
{
ExecutionContext.Run(_contextCopy, _executionCallback, null);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace RESTServiceTest.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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.Windows;
using System.Windows.Input;
using System.Windows.Ink;
using System.Windows.Media;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using MS.Internal.Ink;
using MS.Utility;
using MS.Internal;
using System.Diagnostics;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Ink
{
#region IncrementalHitTester Abstract Base Class
/// <summary>
/// This class serves as both the base class and public interface for
/// incremental hit-testing implementaions.
/// </summary>
public abstract class IncrementalHitTester
{
#region Public API
/// <summary>
/// Adds a point representing an incremental move of the hit-testing tool
/// </summary>
/// <param name="point">a point that represents an incremental move of the hitting tool</param>
public void AddPoint(Point point)
{
AddPoints(new Point[1] { point });
}
/// <summary>
/// Adds an array of points representing an incremental move of the hit-testing tool
/// </summary>
/// <param name="points">points representing an incremental move of the hitting tool</param>
public void AddPoints(IEnumerable<Point> points)
{
if (points == null)
{
throw new System.ArgumentNullException("points");
}
if (IEnumerablePointHelper.GetCount(points) == 0)
{
throw new System.ArgumentException(SR.Get(SRID.EmptyArrayNotAllowedAsArgument), "points");
}
if (false == _fValid)
{
throw new System.InvalidOperationException(SR.Get(SRID.EndHitTestingCalled));
}
System.Diagnostics.Debug.Assert(_strokes != null);
AddPointsCore(points);
}
/// <summary>
/// Adds a StylusPacket representing an incremental move of the hit-testing tool
/// </summary>
/// <param name="stylusPoints">stylusPoints</param>
public void AddPoints(StylusPointCollection stylusPoints)
{
if (stylusPoints == null)
{
throw new System.ArgumentNullException("stylusPoints");
}
if (stylusPoints.Count == 0)
{
throw new System.ArgumentException(SR.Get(SRID.EmptyArrayNotAllowedAsArgument), "stylusPoints");
}
if (false == _fValid)
{
throw new System.InvalidOperationException(SR.Get(SRID.EndHitTestingCalled));
}
System.Diagnostics.Debug.Assert(_strokes != null);
Point[] points = new Point[stylusPoints.Count];
for (int x = 0; x < stylusPoints.Count; x++)
{
points[x] = (Point)stylusPoints[x];
}
AddPointsCore(points);
}
/// <summary>
/// Release as many resources as possible for this enumerator
/// </summary>
public void EndHitTesting()
{
if (_strokes != null)
{
// Detach the event handler
_strokes.StrokesChangedInternal -= new StrokeCollectionChangedEventHandler(OnStrokesChanged);
_strokes = null;
int count = _strokeInfos.Count;
for ( int i = 0; i < count; i++)
{
_strokeInfos[i].Detach();
}
_strokeInfos = null;
}
_fValid = false;
}
/// <summary>
/// Accessor to see if the Hit Tester is still valid
/// </summary>
public bool IsValid { get { return _fValid; } }
#endregion
#region Internal
/// <summary>
/// C-tor.
/// </summary>
/// <param name="strokes">strokes to hit-test</param>
internal IncrementalHitTester(StrokeCollection strokes)
{
System.Diagnostics.Debug.Assert(strokes != null);
// Create a StrokeInfo object for each stroke.
_strokeInfos = new List<StrokeInfo>(strokes.Count);
for (int x = 0; x < strokes.Count; x++)
{
Stroke stroke = strokes[x];
_strokeInfos.Add(new StrokeInfo(stroke));
}
_strokes = strokes;
// Attach an event handler to the strokes' changed event
_strokes.StrokesChangedInternal += new StrokeCollectionChangedEventHandler(OnStrokesChanged);
}
/// <summary>
/// The implementation behind AddPoint/AddPoints.
/// Derived classes are supposed to override this method.
/// </summary>
protected abstract void AddPointsCore(IEnumerable<Point> points);
/// <summary>
/// Accessor to the internal collection of StrokeInfo objects
/// </summary>
internal List<StrokeInfo> StrokeInfos { get { return _strokeInfos; } }
#endregion
#region Private
/// <summary>
/// Event handler associated with the stroke collection.
/// </summary>
/// <param name="sender">Stroke collection that was modified</param>
/// <param name="args">Modification that occurred</param>
/// <remarks>
/// Update our _strokeInfos cache. We get notified on StrokeCollection.StrokesChangedInternal which
/// is raised first so we can assume we're the first delegate in the call chain
/// </remarks>
private void OnStrokesChanged(object sender, StrokeCollectionChangedEventArgs args)
{
System.Diagnostics.Debug.Assert((_strokes != null) && (_strokeInfos != null) && (_strokes == sender));
StrokeCollection added = args.Added;
StrokeCollection removed = args.Removed;
if (added.Count > 0)
{
int firstIndex = _strokes.IndexOf(added[0]);
for (int i = 0; i < added.Count; i++)
{
_strokeInfos.Insert(firstIndex, new StrokeInfo(added[i]));
firstIndex++;
}
}
if (removed.Count > 0)
{
StrokeCollection localRemoved = new StrokeCollection(removed);
//we have to assume that removed strokes can be in any order in _strokes
for (int i = 0; i < _strokeInfos.Count && localRemoved.Count > 0; )
{
bool found = false;
for (int j = 0; j < localRemoved.Count; j++)
{
if (localRemoved[j] == _strokeInfos[i].Stroke)
{
_strokeInfos.RemoveAt(i);
localRemoved.RemoveAt(j);
found = true;
}
}
//we didn't find a removed stroke at index i in _strokeInfos, so advance i
if (!found)
{
i++;
}
}
}
//validate our cache
if (_strokes.Count != _strokeInfos.Count)
{
Debug.Assert(false, "Benign assert. IncrementalHitTester's _strokeInfos cache is out of sync, rebuilding.");
RebuildStrokeInfoCache();
return;
}
for (int i = 0; i < _strokeInfos.Count; i++)
{
if (_strokeInfos[i].Stroke != _strokes[i])
{
Debug.Assert(false, "Benign assert. IncrementalHitTester's _strokeInfos cache is out of sync, rebuilding.");
RebuildStrokeInfoCache();
return;
}
}
}
/// <summary>
/// IHT's can get into a state where their StrokeInfo cache is too
/// out of sync with the StrokeCollection to incrementally update it.
/// When we detect this has happened, we just rebuild the entire cache.
/// </summary>
private void RebuildStrokeInfoCache()
{
List<StrokeInfo> newStrokeInfos = new List<StrokeInfo>(_strokes.Count);
foreach (Stroke stroke in _strokes)
{
bool found = false;
for (int x = 0; x < _strokeInfos.Count; x++)
{
StrokeInfo strokeInfo = _strokeInfos[x];
if (strokeInfo != null && stroke == strokeInfo.Stroke)
{
newStrokeInfos.Add(strokeInfo);
//just set to null instead of removing and shifting
//we're about to GC _strokeInfos
_strokeInfos[x] = null;
found = true;
break;
}
}
if (!found)
{
//we didn't find an existing strokeInfo
newStrokeInfos.Add(new StrokeInfo(stroke));
}
}
//detach the remaining strokeInfo's from their strokes
for (int x = 0; x < _strokeInfos.Count; x++)
{
StrokeInfo strokeInfo = _strokeInfos[x];
if (strokeInfo != null)
{
strokeInfo.Detach();
}
}
_strokeInfos = newStrokeInfos;
#if DEBUG
Debug.Assert(_strokeInfos.Count == _strokes.Count);
for (int x = 0; x < _strokeInfos.Count; x++)
{
Debug.Assert(_strokeInfos[x].Stroke == _strokes[x]);
}
#endif
}
#endregion
#region Fields
/// <summary> Reference to the stroke collection under test </summary>
private StrokeCollection _strokes;
/// <summary> A collection of helper objects mapped to the stroke colection</summary>
private List<StrokeInfo> _strokeInfos;
private bool _fValid = true;
#endregion
}
#endregion
#region IncrementalLassoHitTester
/// <summary>
/// IncrementalHitTester implementation for hit-testing with lasso
/// </summary>
public class IncrementalLassoHitTester : IncrementalHitTester
{
#region public APIs
/// <summary>
/// Event
/// </summary>
public event LassoSelectionChangedEventHandler SelectionChanged;
#endregion
#region C-tor and the overrides
/// <summary>
/// C-tor.
/// </summary>
/// <param name="strokes">strokes to hit-test</param>
/// <param name="percentageWithinLasso">a hit-testing parameter that defines the minimal
/// percent of nodes of a stroke to be inside the lasso to consider the stroke hit</param>
internal IncrementalLassoHitTester(StrokeCollection strokes, int percentageWithinLasso)
: base(strokes)
{
System.Diagnostics.Debug.Assert((percentageWithinLasso >= 0) && (percentageWithinLasso <= 100));
_lasso = new SingleLoopLasso();
_percentIntersect = percentageWithinLasso;
}
/// <summary>
/// The implementation behind the public methods AddPoint/AddPoints
/// </summary>
/// <param name="points">new points to add to the lasso</param>
protected override void AddPointsCore(IEnumerable<Point> points)
{
System.Diagnostics.Debug.Assert((points != null) && (IEnumerablePointHelper.GetCount(points)!= 0));
// Add the new points to the lasso
int lastPointIndex = (0 != _lasso.PointCount) ? (_lasso.PointCount - 1) : 0;
_lasso.AddPoints(points);
// Do nothing if there's not enough points, or there's nobody listening
// The points may be filtered out, so if all the points are filtered out, (lastPointIndex == (_lasso.PointCount - 1).
// For this case, check if the incremental lasso is disabled (i.e., points modified).
if ((_lasso.IsEmpty) || (lastPointIndex == (_lasso.PointCount - 1) && false == _lasso.IsIncrementalLassoDirty)
|| (SelectionChanged == null))
{
return;
}
// Variables for possible HitChanged events to fire
StrokeCollection strokesHit = null;
StrokeCollection strokesUnhit = null;
// Create a lasso that represents the current increment
Lasso lassoUpdate = new Lasso();
if (false == _lasso.IsIncrementalLassoDirty)
{
if (0 < lastPointIndex)
{
lassoUpdate.AddPoint(_lasso[0]);
}
// Only the points the have been successfully added to _lasso will be added to
// lassoUpdate.
for (; lastPointIndex < _lasso.PointCount; lastPointIndex++)
{
lassoUpdate.AddPoint(_lasso[lastPointIndex]);
}
}
// Enumerate through the strokes and update their hit-test results
foreach (StrokeInfo strokeInfo in this.StrokeInfos)
{
Lasso lasso;
if (true == strokeInfo.IsDirty || true == _lasso.IsIncrementalLassoDirty)
{
// If this is the first time this stroke gets hit-tested with this lasso,
// or if the stroke (or its DAs) has changed since the last hit-testing,
// or if the lasso points have been modified,
// then (re)hit-test this stroke against the entire lasso.
lasso = _lasso;
strokeInfo.IsDirty = false;
}
else
{
// Otherwise, hit-test it against the lasso increment first and then only
// those ink points that are in that small lasso need to be hit-tested
// against the big (entire) lasso.
// This is supposed to be a significant piece of optimization, since
// lasso increments are usually very small, they are defined by just
// a few points and they don't capture and/or release too many ink nodes.
lasso = lassoUpdate;
}
// Skip those stroke which bounding box doesn't even intersects with the lasso bounds
double hitWeightChange = 0f;
if (lasso.Bounds.IntersectsWith(strokeInfo.StrokeBounds))
{
// Get the stroke node points for the hit-testing.
StylusPointCollection stylusPoints = strokeInfo.StylusPoints;
// Find out if the lasso update has changed the hit count of the stroke.
for (int i = 0; i < stylusPoints.Count; i++)
{
// Consider only the points that become captured/released with this particular update
if (true == lasso.Contains((Point)stylusPoints[i]))
{
double weight = strokeInfo.GetPointWeight(i);
if (lasso == _lasso || _lasso.Contains((Point)stylusPoints[i]))
{
hitWeightChange += weight;
}
else
{
hitWeightChange -= weight;
}
}
}
}
// Update the stroke hit weight and check whether it has crossed the margin
// in either direction since the last update.
if ((hitWeightChange != 0) || (lasso == _lasso))
{
strokeInfo.HitWeight = (lasso == _lasso) ? hitWeightChange : (strokeInfo.HitWeight + hitWeightChange);
bool isHit = DoubleUtil.GreaterThanOrClose(strokeInfo.HitWeight, strokeInfo.TotalWeight * _percentIntersect / 100f - Stroke.PercentageTolerance);
if (strokeInfo.IsHit != isHit)
{
strokeInfo.IsHit = isHit;
if (isHit)
{
// The hit count became greater than the margin percentage, the stroke
// needs to be reported for selection
if (null == strokesHit)
{
strokesHit = new StrokeCollection();
}
strokesHit.Add(strokeInfo.Stroke);
}
else
{
// The hit count just became less than the margin percentage,
// the stroke needs to be reported for de-selection
if (null == strokesUnhit)
{
strokesUnhit = new StrokeCollection();
}
strokesUnhit.Add(strokeInfo.Stroke);
}
}
}
}
_lasso.IsIncrementalLassoDirty = false;
// Raise StrokesHitChanged event if any strokes has changed thier
// hit status and there're the event subscribers.
if ((null != strokesHit) || (null != strokesUnhit))
{
OnSelectionChanged(new LassoSelectionChangedEventArgs (strokesHit, strokesUnhit));
}
}
/// <summary>
/// SelectionChanged event raiser
/// </summary>
/// <param name="eventArgs"></param>
protected void OnSelectionChanged(LassoSelectionChangedEventArgs eventArgs)
{
System.Diagnostics.Debug.Assert(eventArgs != null);
if (SelectionChanged != null)
{
SelectionChanged(this, eventArgs);
}
}
#endregion
#region Fields
private Lasso _lasso;
private int _percentIntersect;
#endregion
}
#endregion
#region IncrementalStrokeHitTester
/// <summary>
/// IncrementalHitTester implementation for hit-testing with a shape, PointErasing .
/// </summary>
public class IncrementalStrokeHitTester : IncrementalHitTester
{
/// <summary>
///
/// </summary>
public event StrokeHitEventHandler StrokeHit;
#region C-tor and the overrides
/// <summary>
/// C-tor
/// </summary>
/// <param name="strokes">strokes to hit-test for erasing</param>
/// <param name="eraserShape">erasing shape</param>
internal IncrementalStrokeHitTester(StrokeCollection strokes, StylusShape eraserShape)
: base(strokes)
{
System.Diagnostics.Debug.Assert(eraserShape != null);
// Create an ErasingStroke objects that implements the actual hit-testing
_erasingStroke = new ErasingStroke(eraserShape);
}
/// <summary>
/// The implementation behind the public methods AddPoint/AddPoints
/// </summary>
/// <param name="points">a set of points representing the last increment
/// in the moving of the erasing shape</param>
protected override void AddPointsCore(IEnumerable<Point> points)
{
System.Diagnostics.Debug.Assert((points != null) && (IEnumerablePointHelper.GetCount(points) != 0));
System.Diagnostics.Debug.Assert(_erasingStroke != null);
// Move the shape through the new points and build the contour of the move.
_erasingStroke.MoveTo(points);
Rect erasingBounds = _erasingStroke.Bounds;
if (erasingBounds.IsEmpty)
{
return;
}
List<StrokeHitEventArgs> strokeHitEventArgCollection = null;
// Do nothing if there's nobody listening to the events
if (StrokeHit != null)
{
List<StrokeIntersection> eraseAt = new List<StrokeIntersection>();
// Test stroke by stroke and collect the results.
for (int x = 0; x < this.StrokeInfos.Count; x++)
{
StrokeInfo strokeInfo = this.StrokeInfos[x];
// Skip the stroke if its bounding box doesn't intersect with the one of the hitting shape.
if ((erasingBounds.IntersectsWith(strokeInfo.StrokeBounds) == false) ||
(_erasingStroke.EraseTest(StrokeNodeIterator.GetIterator(strokeInfo.Stroke, strokeInfo.Stroke.DrawingAttributes), eraseAt) == false))
{
continue;
}
// Create an event args to raise after done with hit-testing
// We don't fire these events right away because user is expected to
// modify the stroke collection in her event handler, and that would
// invalidate this foreach loop.
if (strokeHitEventArgCollection == null)
{
strokeHitEventArgCollection = new List<StrokeHitEventArgs>();
}
strokeHitEventArgCollection.Add(new StrokeHitEventArgs(strokeInfo.Stroke, eraseAt.ToArray()));
// We must clear eraseAt or it will contain invalid results for the next strokes
eraseAt.Clear();
}
}
// Raise StrokeHit event if needed.
if (strokeHitEventArgCollection != null)
{
System.Diagnostics.Debug.Assert(strokeHitEventArgCollection.Count != 0);
for (int x = 0; x < strokeHitEventArgCollection.Count; x++)
{
StrokeHitEventArgs eventArgs = strokeHitEventArgCollection[x];
System.Diagnostics.Debug.Assert(eventArgs.HitStroke != null);
OnStrokeHit(eventArgs);
}
}
}
/// <summary>
/// Event raiser for StrokeHit
/// </summary>
protected void OnStrokeHit(StrokeHitEventArgs eventArgs)
{
System.Diagnostics.Debug.Assert(eventArgs != null);
if (StrokeHit != null)
{
StrokeHit(this, eventArgs);
}
}
#endregion
#region Fields
private ErasingStroke _erasingStroke;
#endregion
}
#endregion
#region EventArgs and delegates
/// <summary>
/// Declaration for LassoSelectionChanged event handler. Used in lasso-selection
/// </summary>
public delegate void LassoSelectionChangedEventHandler(object sender, LassoSelectionChangedEventArgs e);
/// <summary>
/// Declaration for StrokeHit event handler. Used in point-erasing
/// </summary>
public delegate void StrokeHitEventHandler(object sender, StrokeHitEventArgs e);
/// <summary>
/// Event arguments for LassoSelectionChanged event
/// </summary>
public class LassoSelectionChangedEventArgs : EventArgs
{
internal LassoSelectionChangedEventArgs(StrokeCollection selectedStrokes, StrokeCollection deselectedStrokes)
{
_selectedStrokes = selectedStrokes;
_deselectedStrokes = deselectedStrokes;
}
/// <summary>
/// Collection of strokes which were hit with the last increment
/// </summary>
public StrokeCollection SelectedStrokes
{
get
{
if (_selectedStrokes != null)
{
StrokeCollection sc = new StrokeCollection();
sc.Add(_selectedStrokes);
return sc;
}
else
{
return new StrokeCollection();
}
}
}
/// <summary>
/// Collection of strokes which were unhit with the last increment
/// </summary>
public StrokeCollection DeselectedStrokes
{
get
{
if (_deselectedStrokes != null)
{
StrokeCollection sc = new StrokeCollection();
sc.Add(_deselectedStrokes);
return sc;
}
else
{
return new StrokeCollection();
}
}
}
private StrokeCollection _selectedStrokes;
private StrokeCollection _deselectedStrokes;
}
/// <summary>
/// Event arguments for StrokeHit event
/// </summary>
public class StrokeHitEventArgs : EventArgs
{
/// <summary>
/// C-tor
/// </summary>
internal StrokeHitEventArgs(Stroke stroke, StrokeIntersection[] hitFragments)
{
System.Diagnostics.Debug.Assert(stroke != null && hitFragments != null && hitFragments.Length > 0);
_stroke = stroke;
_hitFragments = hitFragments;
}
/// <summary>Stroke that was hit</summary>
public Stroke HitStroke { get { return _stroke; } }
/// <summary>
///
/// </summary>
/// <returns></returns>
public StrokeCollection GetPointEraseResults()
{
return _stroke.Erase(_hitFragments);
}
private Stroke _stroke;
private StrokeIntersection[] _hitFragments;
}
#endregion
}
namespace MS.Internal.Ink
{
#region StrokeInfo
/// <summary>
/// A helper class associated with a stroke. Used for caching the stroke's
/// bounding box, hit-testing results, and for keeping an eye on the stroke changes
/// </summary>
internal class StrokeInfo
{
#region API (used by incremental hit-testers)
/// <summary>
/// StrokeInfo
/// </summary>
internal StrokeInfo(Stroke stroke)
{
System.Diagnostics.Debug.Assert(stroke != null);
_stroke = stroke;
_bounds = stroke.GetBounds();
// Start listening to the stroke events
_stroke.DrawingAttributesChanged += new PropertyDataChangedEventHandler(OnStrokeDrawingAttributesChanged);
_stroke.StylusPointsReplaced += new StylusPointsReplacedEventHandler(OnStylusPointsReplaced);
_stroke.StylusPoints.Changed += new EventHandler(OnStylusPointsChanged);
_stroke.DrawingAttributesReplaced += new DrawingAttributesReplacedEventHandler(OnDrawingAttributesReplaced);
}
/// <summary>The stroke object associated with this helper structure</summary>
internal Stroke Stroke { get { return _stroke; } }
/// <summary>Pre-calculated bounds of the stroke </summary>
internal Rect StrokeBounds { get { return _bounds; } }
/// <summary>Tells whether the stroke or its drawing attributes have been modified
/// since the last use (hit-testing)</summary>
internal bool IsDirty
{
get { return _isDirty; }
set { _isDirty = value; }
}
/// <summary>Tells whether the stroke was found (and reported) as hit </summary>
internal bool IsHit
{
get { return _isHit; }
set { _isHit = value; }
}
/// <summary>
/// Cache teh stroke points
/// </summary>
internal StylusPointCollection StylusPoints
{
get
{
if (_stylusPoints == null)
{
if (_stroke.DrawingAttributes.FitToCurve)
{
_stylusPoints = _stroke.GetBezierStylusPoints();
}
else
{
_stylusPoints = _stroke.StylusPoints;
}
}
return _stylusPoints;
}
}
/// <summary>
/// Holds the current hit-testing result for the stroke. Represents the length of
/// the stroke "inside" and "hit" by the lasso
/// </summary>
internal double HitWeight
{
get { return _hitWeight; }
set
{
// it is ok to clamp this off, rounding error sends it over or under by a minimal amount.
if (DoubleUtil.GreaterThan(value, TotalWeight))
{
_hitWeight = TotalWeight;
}
else if (DoubleUtil.LessThan(value, 0f))
{
_hitWeight = 0f;
}
else
{
_hitWeight = value;
}
}
}
/// <summary>
/// Get the total weight of the stroke. For this implementation, it is the total length of the stroke.
/// </summary>
/// <returns></returns>
internal double TotalWeight
{
get
{
if (!_totalWeightCached)
{
_totalWeight= 0;
for (int i = 0; i < StylusPoints.Count; i++)
{
_totalWeight += this.GetPointWeight(i);
}
_totalWeightCached = true;
}
return _totalWeight;
}
}
/// <summary>
/// Calculate the weight of a point.
/// </summary>
internal double GetPointWeight(int index)
{
StylusPointCollection stylusPoints = this.StylusPoints;
DrawingAttributes da = this.Stroke.DrawingAttributes;
System.Diagnostics.Debug.Assert(stylusPoints != null && index >= 0 && index < stylusPoints.Count);
double weight = 0f;
if (index == 0)
{
weight += Math.Sqrt(da.Width*da.Width + da.Height*da.Height) / 2.0f;
}
else
{
Vector spine = (Point)stylusPoints[index] - (Point)stylusPoints[index - 1];
weight += Math.Sqrt(spine.LengthSquared) / 2.0f;
}
if (index == stylusPoints.Count - 1)
{
weight += Math.Sqrt(da.Width*da.Width + da.Height*da.Height) / 2.0f;
}
else
{
Vector spine = (Point)stylusPoints[index + 1] - (Point)stylusPoints[index];
weight += Math.Sqrt(spine.LengthSquared) / 2.0f;
}
return weight;
}
/// <summary>
/// A kind of disposing method
/// </summary>
internal void Detach()
{
if (_stroke != null)
{
// Detach the event handlers
_stroke.DrawingAttributesChanged -= new PropertyDataChangedEventHandler(OnStrokeDrawingAttributesChanged);
_stroke.StylusPointsReplaced -= new StylusPointsReplacedEventHandler(OnStylusPointsReplaced);
_stroke.StylusPoints.Changed -= new EventHandler(OnStylusPointsChanged);
_stroke.DrawingAttributesReplaced -= new DrawingAttributesReplacedEventHandler(OnDrawingAttributesReplaced);
_stroke = null;
}
}
#endregion
#region Stroke event handlers (Private)
/// <summary>Event handler for stroke data changed events</summary>
private void OnStylusPointsChanged(object sender, EventArgs args)
{
Invalidate();
}
/// <summary>Event handler for stroke data changed events</summary>
private void OnStylusPointsReplaced(object sender, StylusPointsReplacedEventArgs args)
{
Invalidate();
}
/// <summary>
/// Event handler for stroke's drawing attributes changes.
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
private void OnStrokeDrawingAttributesChanged(object sender, PropertyDataChangedEventArgs args)
{
// Only enforce rehittesting of the whole stroke when the DrawingAttribute change may affect hittesting
if(DrawingAttributes.IsGeometricalDaGuid(args.PropertyGuid))
{
Invalidate();
}
}
private void OnDrawingAttributesReplaced(Object sender, DrawingAttributesReplacedEventArgs args)
{
// If the drawing attributes change involves Width, Height, StylusTipTransform, IgnorePressure, or FitToCurve,
// we need to invalidate
if (false == DrawingAttributes.GeometricallyEqual(args.NewDrawingAttributes, args.PreviousDrawingAttributes))
{
Invalidate();
}
}
/// <summary>Implementation for the event handlers above</summary>
private void Invalidate()
{
_totalWeightCached = false;
_stylusPoints = null;
_hitWeight = 0;
// Let the hit-tester know that it should not use incremental hit-testing
_isDirty = true;
// The Stroke.GetBounds may be overriden in the 3rd party code.
// The out-side code could throw exception. If an exception is thrown, _bounds will keep the original value.
// Re-compute the stroke bounds
_bounds = _stroke.GetBounds();
}
#endregion
#region Fields
private Stroke _stroke;
private Rect _bounds;
private double _hitWeight = 0f;
private bool _isHit = false;
private bool _isDirty = true;
private StylusPointCollection _stylusPoints; // Cache the stroke rendering points
private double _totalWeight = 0f;
private bool _totalWeightCached = false;
#endregion
}
#endregion // StrokeInfo
}
// The following code is for Stroke-Erasing scenario. Currently the IncrementalStrokeHitTester
// can be used for Stroke-erasing but the following class is faster. If in the future there's a
// perf issue with Stroke-Erasing, consider adding the following code.
//#region Commented Code for IncrementalStrokeHitTester
//#region IncrementalStrokeHitTester
///// <summary>
///// IncrementalHitTester implementation for hit-testing with a shape, StrokeErasing .
///// </summary>
//public class IncrementalStrokeHitTester : IncrementalHitTester
//{
// /// <summary>
// /// event
// /// </summary>
// public event StrokesHitEventHandler StrokesHit;
// #region C-tor and the overrides
// /// <summary>
// /// C-tor
// /// </summary>
// /// <param name="strokes">strokes to hit-test for erasing</param>
// /// <param name="eraserShape">erasing shape</param>
// internal IncrementalStrokeHitTester(StrokeCollection strokes, StylusShape eraserShape)
// : base(strokes)
// {
// System.Diagnostics.Debug.Assert(eraserShape != null);
// // Create an ErasingStroke objects that implements the actual hit-testing
// _erasingStroke = new ErasingStroke(eraserShape);
// }
// /// <summary>
// ///
// /// </summary>
// /// <param name="eventArgs"></param>
// internal protected void OnStrokesHit(StrokesHitEventArgs eventArgs)
// {
// if (StrokesHit != null)
// {
// StrokesHit(this, eventArgs);
// }
// }
// /// <summary>
// /// The implementation behind the public methods AddPoint/AddPoints
// /// </summary>
// /// <param name="points">a set of points representing the last increment
// /// in the moving of the erasing shape</param>
// internal protected override void AddPointsCore(Point[] points)
// {
// System.Diagnostics.Debug.Assert((points != null) && (points.Length != 0));
// System.Diagnostics.Debug.Assert(_erasingStroke != null);
// // Move the shape through the new points and build the contour of the move.
// _erasingStroke.MoveTo(points);
// Rect erasingBounds = _erasingStroke.Bounds;
// if (erasingBounds.IsEmpty)
// {
// return;
// }
// StrokeCollection strokesHit = null;
// if (StrokesHit != null)
// {
// // Test stroke by stroke and collect hits.
// foreach (StrokeInfo strokeInfo in StrokeInfos)
// {
// // Skip strokes that have already been reported hit or which bounds
// // don't intersect with the bounds of the erasing stroke.
// if ((strokeInfo.IsHit == false) && erasingBounds.IntersectsWith(strokeInfo.StrokeBounds)
// && _erasingStroke.HitTest(StrokeNodeIterator.GetIterator(strokeInfo.Stroke, strokeInfo.Overrides)))
// {
// if (strokesHit == null)
// {
// strokesHit = new StrokeCollection();
// }
// strokesHit.Add(strokeInfo.Stroke);
// strokeInfo.IsHit = true;
// }
// }
// }
// // Raise StrokesHitChanged event if any strokes have been hit and there're listeners to the event.
// if (strokesHit != null)
// {
// System.Diagnostics.Debug.Assert(strokesHit.Count != 0);
// OnStrokesHit(new StrokesHitEventArgs(strokesHit));
// }
// }
// #endregion
// #region Fields
// private ErasingStroke _erasingStroke;
// #endregion
//}
//#endregion
///// <summary>
///// Declaration for StrokesHit event handler. Used in stroke-erasing
///// </summary>
//public delegate void StrokesHitEventHandler(object sender, StrokesHitEventArgs e);
///// <summary>
///// Event arguments for StrokesHit event
///// </summary>
//public class StrokesHitEventArgs : EventArgs
//{
// internal StrokesHitEventArgs(StrokeCollection hitStrokes)
// {
// System.Diagnostics.Debug.Assert(hitStrokes != null && hitStrokes.Count > 0);
// _hitStrokes = hitStrokes;
// }
// /// <summary>
// ///
// /// </summary>
// public StrokeCollection HitStrokes
// {
// get { return _hitStrokes; }
// }
// private StrokeCollection _hitStrokes;
//}
//#endregion
| |
using System;
using System.Collections.Generic;
using System.Linq;
namespace Orleans.Runtime.ConsistentRing
{
/// <summary>
/// We use the 'backward/clockwise' definition to assign responsibilities on the ring.
/// E.g. in a ring of nodes {5, 10, 15} the responsible for key 7 is 10 (the node is responsible for its predecessing range).
/// The backwards/clockwise approach is consistent with many overlays, e.g., Chord, Cassandra, etc.
/// Note: MembershipOracle uses 'forward/counter-clockwise' definition to assign responsibilities.
/// E.g. in a ring of nodes {5, 10, 15}, the responsible of key 7 is node 5 (the node is responsible for its sucessing range)..
/// </summary>
internal class VirtualBucketsRingProvider :
#if !NETSTANDARD
MarshalByRefObject,
#endif
IConsistentRingProvider, ISiloStatusListener
{
private readonly List<IRingRangeListener> statusListeners;
private readonly SortedDictionary<uint, SiloAddress> bucketsMap;
private List<Tuple<uint, SiloAddress>> sortedBucketsList; // flattened sorted bucket list for fast lock-free calculation of CalculateTargetSilo
private readonly Logger logger;
private readonly SiloAddress myAddress;
private readonly int numBucketsPerSilo;
private readonly object lockable;
private bool running;
private IRingRange myRange;
internal VirtualBucketsRingProvider(SiloAddress siloAddress, int numVirtualBuckets)
{
numBucketsPerSilo = numVirtualBuckets;
if (numBucketsPerSilo <= 0 )
throw new IndexOutOfRangeException("numBucketsPerSilo is out of the range. numBucketsPerSilo = " + numBucketsPerSilo);
logger = LogManager.GetLogger(typeof(VirtualBucketsRingProvider).Name);
statusListeners = new List<IRingRangeListener>();
bucketsMap = new SortedDictionary<uint, SiloAddress>();
sortedBucketsList = new List<Tuple<uint, SiloAddress>>();
myAddress = siloAddress;
lockable = new object();
running = true;
myRange = RangeFactory.CreateFullRange();
logger.Info("Starting {0} on silo {1}.", typeof(VirtualBucketsRingProvider).Name, siloAddress.ToStringWithHashCode());
StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RING, ToString);
IntValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_RINGSIZE, () => GetRingSize());
StringValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGDISTANCE, () => String.Format("x{0,8:X8}", ((IRingRangeInternal)myRange).RangeSize()));
FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_MYRANGE_RINGPERCENTAGE, () => (float)((IRingRangeInternal)myRange).RangePercentage());
FloatValueStatistic.FindOrCreate(StatisticNames.CONSISTENTRING_AVERAGERINGPERCENTAGE, () =>
{
int size = GetRingSize();
return size == 0 ? 0 : ((float)100.0/(float) size);
});
// add myself to the list of members
AddServer(myAddress);
}
private void Stop()
{
running = false;
}
public IRingRange GetMyRange()
{
return myRange;
}
private int GetRingSize()
{
lock (lockable)
{
return bucketsMap.Values.Distinct().Count();
}
}
public bool SubscribeToRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
if (statusListeners.Contains(observer)) return false;
statusListeners.Add(observer);
return true;
}
}
public bool UnSubscribeFromRangeChangeEvents(IRingRangeListener observer)
{
lock (statusListeners)
{
return statusListeners.Contains(observer) && statusListeners.Remove(observer);
}
}
private void NotifyLocalRangeSubscribers(IRingRange old, IRingRange now, bool increased)
{
logger.Info(ErrorCode.CRP_Notify, "-NotifyLocalRangeSubscribers about old {0} new {1} increased? {2}", old.ToString(), now.ToString(), increased);
List<IRingRangeListener> copy;
lock (statusListeners)
{
copy = statusListeners.ToList();
}
foreach (IRingRangeListener listener in copy)
{
try
{
listener.RangeChangeNotification(old, now, increased);
}
catch (Exception exc)
{
logger.Error(ErrorCode.CRP_Local_Subscriber_Exception,
String.Format("Local IRangeChangeListener {0} has thrown an exception when was notified about RangeChangeNotification about old {1} new {2} increased? {3}",
listener.GetType().FullName, old, now, increased), exc);
}
}
}
private void AddServer(SiloAddress silo)
{
lock (lockable)
{
List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo);
foreach (var hash in hashes)
{
if (bucketsMap.ContainsKey(hash))
{
var other = bucketsMap[hash];
// If two silos conflict, take the lesser of the two (usually the older one; that is, the lower epoch)
if (silo.CompareTo(other) > 0) continue;
}
bucketsMap[hash] = silo;
}
var myOldRange = myRange;
var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList();
var myNewRange = CalculateRange(bucketsList, myAddress);
// capture my range and sortedBucketsList for later lock-free access.
myRange = myNewRange;
sortedBucketsList = bucketsList;
logger.Info(ErrorCode.CRP_Added_Silo, "Added Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString());
NotifyLocalRangeSubscribers(myOldRange, myNewRange, true);
}
}
internal void RemoveServer(SiloAddress silo)
{
lock (lockable)
{
if (!bucketsMap.ContainsValue(silo)) return; // we have already removed this silo
List<uint> hashes = silo.GetUniformHashCodes(numBucketsPerSilo);
foreach (var hash in hashes)
{
bucketsMap.Remove(hash);
}
var myOldRange = this.myRange;
var bucketsList = bucketsMap.Select(pair => new Tuple<uint, SiloAddress>(pair.Key, pair.Value)).ToList();
var myNewRange = CalculateRange(bucketsList, myAddress);
// capture my range and sortedBucketsList for later lock-free access.
myRange = myNewRange;
sortedBucketsList = bucketsList;
logger.Info(ErrorCode.CRP_Removed_Silo, "Removed Server {0}. Current view: {1}", silo.ToStringWithHashCode(), this.ToString());
NotifyLocalRangeSubscribers(myOldRange, myNewRange, true);
}
}
private static IRingRange CalculateRange(List<Tuple<uint, SiloAddress>> list, SiloAddress silo)
{
var ranges = new List<IRingRange>();
for (int i = 0; i < list.Count; i++)
{
var curr = list[i];
var next = list[(i + 1) % list.Count];
// 'backward/clockwise' definition to assign responsibilities on the ring.
if (next.Item2.Equals(silo))
{
IRingRange range = RangeFactory.CreateRange(curr.Item1, next.Item1);
ranges.Add(range);
}
}
return RangeFactory.CreateRange(ranges);
}
// just for debugging
public override string ToString()
{
Dictionary<SiloAddress, IRingRangeInternal> ranges = GetRanges();
List<KeyValuePair<SiloAddress, IRingRangeInternal>> sortedList = ranges.AsEnumerable().ToList();
sortedList.Sort((t1, t2) => t1.Value.RangePercentage().CompareTo(t2.Value.RangePercentage()));
return Utils.EnumerableToString(sortedList, kv => String.Format("{0} -> {1}", kv.Key, kv.Value.ToString()));
}
// Internal: for testing only!
internal Dictionary<SiloAddress, IRingRangeInternal> GetRanges()
{
List<SiloAddress> silos;
List<Tuple<uint, SiloAddress>> snapshotBucketsList;
lock (lockable)
{
silos = bucketsMap.Values.Distinct().ToList();
snapshotBucketsList = sortedBucketsList;
}
var ranges = new Dictionary<SiloAddress, IRingRangeInternal>();
foreach (var silo in silos)
{
var range = (IRingRangeInternal)CalculateRange(snapshotBucketsList, silo);
ranges.Add(silo, range);
}
return ranges;
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (updatedSilo.Equals(myAddress))
{
if (status.IsTerminating())
{
Stop();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
RemoveServer(updatedSilo);
}
else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Created or SiloStatus.Joining -- wait until it actually becomes active
{
AddServer(updatedSilo);
}
}
}
public SiloAddress GetPrimaryTargetSilo(uint key)
{
return CalculateTargetSilo(key);
}
/// <summary>
/// Finds the silo that owns the given hash value.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="hash"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
private SiloAddress CalculateTargetSilo(uint hash, bool excludeThisSiloIfStopping = true)
{
// put a private reference to point to sortedBucketsList,
// so if someone is changing the sortedBucketsList reference, we won't get it changed in the middle of our operation.
// The tricks of writing lock-free code!
var snapshotBucketsList = sortedBucketsList;
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = excludeThisSiloIfStopping && !running;
if (snapshotBucketsList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeMySelf ? null : myAddress;
}
// use clockwise ... current code in membershipOracle.CalculateTargetSilo() does counter-clockwise ...
// if you want to stick to counter-clockwise, change the responsibility definition in 'In()' method & responsibility defs in OrleansReminderMemory
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
Tuple<uint, SiloAddress> s = snapshotBucketsList.Find(tuple => (tuple.Item1 >= hash) && // <= hash for counter-clockwise responsibilities
(!tuple.Item2.Equals(myAddress) || !excludeMySelf));
if (s == null)
{
// if not found in traversal, then first silo should be returned (we are on a ring)
// if you go back to their counter-clockwise policy, then change the 'In()' method in OrleansReminderMemory
s = snapshotBucketsList[0]; // vs [membershipRingList.Count - 1]; for counter-clockwise policy
// Make sure it's not us...
if (s.Item2.Equals(myAddress) && excludeMySelf)
{
// vs [membershipRingList.Count - 2]; for counter-clockwise policy
s = snapshotBucketsList.Count > 1 ? snapshotBucketsList[1] : null;
}
}
if (logger.IsVerbose2) logger.Verbose2("Calculated ring partition owner silo {0} for key {1}: {2} --> {3}", s.Item2, hash, hash, s.Item1);
return s.Item2;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using Xunit;
namespace System.Linq.Expressions.Tests
{
public class ParameterBlockTests : SharedBlockTests
{
private static IEnumerable<ParameterExpression> SingleParameter
{
get { return Enumerable.Repeat(Expression.Variable(typeof(int)), 1); }
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void SingleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[PerCompilationType(nameof(ConstantValueData))]
public void DoubleElementBlock(object value, bool useInterpreter)
{
Type type = value.GetType();
ConstantExpression constant = Expression.Constant(value, type);
BlockExpression block = Expression.Block(
SingleParameter,
Expression.Empty(),
constant
);
Assert.Equal(type, block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Fact]
public void NullExpicitType()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Expression.Constant(0)));
AssertExtensions.Throws<ArgumentNullException>("type", () => Expression.Block(null, SingleParameter, Enumerable.Repeat(Expression.Constant(0), 1)));
}
[Fact]
public void NullExpressionList()
{
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(SingleParameter, default(IEnumerable<Expression>)));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(Expression[])));
AssertExtensions.Throws<ArgumentNullException>("expressions", () => Expression.Block(typeof(int), SingleParameter, default(IEnumerable<Expression>)));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i < expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = null;
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0)));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions));
Assert.Throws<ArgumentNullException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void UnreadableExpressionInExpressionList(int size)
{
List<Expression> expressionList = Enumerable.Range(0, size).Select(i => (Expression)Expression.Constant(1)).ToList();
for (int i = 0; i != expressionList.Count; ++i)
{
Expression[] expressions = expressionList.ToArray();
expressions[i] = UnreadableExpression;
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(SingleParameter, expressions.Skip(0)));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions));
Assert.Throws<ArgumentException>($"expressions[{i}]", () => Expression.Block(typeof(int), SingleParameter, expressions.Skip(0)));
}
}
[Theory]
[PerCompilationType(nameof(ObjectAssignableConstantValuesAndSizes))]
public void BlockExplicitType(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
BlockExpression block = Expression.Block(typeof(object), SingleParameter, PadBlock(blockSize - 1, constant));
Assert.Equal(typeof(object), block.Type);
Expression equal = Expression.Equal(constant, block);
Assert.True(Expression.Lambda<Func<bool>>(equal).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void BlockInvalidExplicitType(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(string), SingleParameter, expressions.ToArray()));
}
[Theory]
[PerCompilationType(nameof(ConstantValuesAndSizes))]
public void BlockFromEmptyParametersSameAsFromParams(object value, int blockSize, bool useInterpreter)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression fromParamsBlock = Expression.Block(SingleParameter, expressions.ToArray());
BlockExpression fromEnumBlock = Expression.Block(SingleParameter, expressions);
Assert.Equal(fromParamsBlock.GetType(), fromEnumBlock.GetType());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromParamsBlock)).Compile(useInterpreter)());
Assert.True(Expression.Lambda<Func<bool>>(Expression.Equal(constant, fromEnumBlock)).Compile(useInterpreter)());
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void InvalidExpressionIndex(object value, int blockSize)
{
BlockExpression block = Expression.Block(SingleParameter, PadBlock(blockSize - 1, Expression.Constant(value, value.GetType())));
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[-1]);
AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => block.Expressions[blockSize]);
}
[Fact]
public void EmptyBlockWithParametersAndNonVoidTypeNotAllowed()
{
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter));
Assert.Throws<ArgumentException>(null, () => Expression.Block(typeof(int), SingleParameter, Enumerable.Empty<Expression>()));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromParams(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions.ToArray());
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ResultPropertyFromEnumerable(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(constant, block.Result);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void VariableCountCorrect(object value, int blockSize)
{
IEnumerable<ParameterExpression> vars = Enumerable.Range(0, blockSize).Select(i => Expression.Variable(value.GetType()));
BlockExpression block = Expression.Block(vars, Expression.Constant(value, value.GetType()));
Assert.Equal(blockSize, block.Variables.Count);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void RewriteToSameWithSameValues(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
Assert.Same(block, block.Update(block.Variables.ToArray(), expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void CanFindItems(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
IList<Expression> expressions = block.Expressions;
for (int i = 0; i != values.Length; ++i)
Assert.Equal(i, expressions.IndexOf(values[i]));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void IdentifyNonAbsentItemAsAbsent(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Equal(-1, block.Expressions.IndexOf(Expression.Default(typeof(long))));
Assert.False(block.Expressions.Contains(null));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void ExpressionsEnumerable(object value, int blockSize)
{
ConstantExpression[] values = new ConstantExpression[blockSize];
for (int i = 0; i != values.Length; ++i)
values[i] = Expression.Constant(value);
BlockExpression block = Expression.Block(SingleParameter, values);
Assert.True(values.SequenceEqual(block.Expressions));
int index = 0;
foreach (Expression exp in ((IEnumerable)block.Expressions))
Assert.Same(exp, values[index++]);
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void UpdateWithExpressionsReturnsSame(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.Same(block, block.Update(block.Variables, block.Expressions));
Assert.Same(block, NoOpVisitor.Instance.Visit(block));
}
[Theory]
[MemberData(nameof(ConstantValuesAndSizes))]
public void Visit(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(ObjectAssignableConstantValuesAndSizes))]
public void VisitTyped(object value, int blockSize)
{
ConstantExpression constant = Expression.Constant(value, value.GetType());
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant);
BlockExpression block = Expression.Block(typeof(object), SingleParameter, expressions);
Assert.NotSame(block, new TestVistor().Visit(block));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void NullVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(default(ParameterExpression), 1);
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions));
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(vars, expressions.ToArray()));
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions));
AssertExtensions.Throws<ArgumentNullException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void ByRefVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(Expression.Parameter(typeof(int).MakeByRefType()), 1);
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(vars, expressions.ToArray()));
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[0]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory]
[MemberData(nameof(BlockSizes))]
public void RepeatedVariables(int blockSize)
{
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, Expression.Constant(0));
ParameterExpression variable = Expression.Variable(typeof(int));
IEnumerable<ParameterExpression> vars = Enumerable.Repeat(variable, 2);
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(vars, expressions.ToArray()));
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions));
AssertExtensions.Throws<ArgumentException>("variables[1]", () => Expression.Block(typeof(object), vars, expressions.ToArray()));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDoesntRepeatEnumeration(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
ParameterExpression[] vars = {Expression.Variable(typeof(int)), Expression.Variable(typeof(string))};
BlockExpression block = Expression.Block(vars, expressions);
Assert.Same(block, block.Update(new RunOnceEnumerable<ParameterExpression>(vars), block.Expressions));
vars = new[] {Expression.Variable(typeof(int)), Expression.Variable(typeof(string))};
Assert.NotSame(block, block.Update(new RunOnceEnumerable<ParameterExpression>(vars), block.Expressions));
}
[Theory, MemberData(nameof(BlockSizes))]
public void UpdateDifferentSizeReturnsDifferent(int blockSize)
{
ConstantExpression constant = Expression.Constant(0);
IEnumerable<Expression> expressions = PadBlock(blockSize - 1, constant).ToArray();
ParameterExpression[] vars = { Expression.Variable(typeof(int)), Expression.Variable(typeof(string)) };
BlockExpression block = Expression.Block(vars, expressions);
Assert.NotSame(block, block.Update(vars, block.Expressions.Prepend(Expression.Empty())));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace MvcApplication4.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and mediaType
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ActionDescriptor.ReturnType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using Avalonia.Markup.Xaml.XamlIl.CompilerExtensions;
using Microsoft.Build.Framework;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using XamlX;
using XamlX.Ast;
using XamlX.Parsers;
using XamlX.Transform;
using XamlX.TypeSystem;
using FieldAttributes = Mono.Cecil.FieldAttributes;
using MethodAttributes = Mono.Cecil.MethodAttributes;
using TypeAttributes = Mono.Cecil.TypeAttributes;
using XamlX.IL;
namespace Avalonia.Build.Tasks
{
public static partial class XamlCompilerTaskExecutor
{
static bool CheckXamlName(IResource r) => r.Name.ToLowerInvariant().EndsWith(".xaml")
|| r.Name.ToLowerInvariant().EndsWith(".paml")
|| r.Name.ToLowerInvariant().EndsWith(".axaml");
public class CompileResult
{
public bool Success { get; set; }
public bool WrittenFile { get; }
public CompileResult(bool success, bool writtenFile = false)
{
Success = success;
WrittenFile = writtenFile;
}
}
public static CompileResult Compile(IBuildEngine engine, string input, string[] references,
string projectDirectory,
string output, bool verifyIl, MessageImportance logImportance, string strongNameKey, bool patchCom,
bool skipXamlCompilation)
{
return Compile(engine, input, references, projectDirectory, output, verifyIl, logImportance, strongNameKey, patchCom, skipXamlCompilation, debuggerLaunch:false);
}
internal static CompileResult Compile(IBuildEngine engine, string input, string[] references,
string projectDirectory,
string output, bool verifyIl, MessageImportance logImportance, string strongNameKey, bool patchCom, bool skipXamlCompilation, bool debuggerLaunch)
{
var typeSystem = new CecilTypeSystem(references
.Where(r => !r.ToLowerInvariant().EndsWith("avalonia.build.tasks.dll"))
.Concat(new[] { input }), input);
var asm = typeSystem.TargetAssemblyDefinition;
if (!skipXamlCompilation)
{
var compileRes = CompileCore(engine, typeSystem, projectDirectory, verifyIl, logImportance, debuggerLaunch);
if (compileRes == null && !patchCom)
return new CompileResult(true);
if (compileRes == false)
return new CompileResult(false);
}
if (patchCom)
ComInteropHelper.PatchAssembly(asm, typeSystem);
var writerParameters = new WriterParameters { WriteSymbols = asm.MainModule.HasSymbols };
if (!string.IsNullOrWhiteSpace(strongNameKey))
writerParameters.StrongNameKeyBlob = File.ReadAllBytes(strongNameKey);
asm.Write(output, writerParameters);
return new CompileResult(true, true);
}
static bool? CompileCore(IBuildEngine engine, CecilTypeSystem typeSystem,
string projectDirectory, bool verifyIl,
MessageImportance logImportance
, bool debuggerLaunch = false)
{
if (debuggerLaunch)
{
// According this https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.debugger.launch?view=net-6.0#remarks
// documentation, on not windows platform Debugger.Launch() always return true without running a debugger.
if (System.Diagnostics.Debugger.Launch())
{
// Set timeout at 1 minut.
var time = new System.Diagnostics.Stopwatch();
var timeout = TimeSpan.FromMinutes(1);
time.Start();
// wait for the debugger to be attacked or timeout.
while (!System.Diagnostics.Debugger.IsAttached && time.Elapsed < timeout)
{
engine.LogMessage($"[PID:{System.Diagnostics.Process.GetCurrentProcess().Id}] Wating attach debugger. Elapsed {time.Elapsed}...", MessageImportance.High);
System.Threading.Thread.Sleep(100);
}
time.Stop();
if (time.Elapsed >= timeout)
{
engine.LogMessage("Wating attach debugger timeout.", MessageImportance.Normal);
}
}
else
{
engine.LogMessage("Debugging cancelled.", MessageImportance.Normal);
}
}
var asm = typeSystem.TargetAssemblyDefinition;
var emres = new EmbeddedResources(asm);
var avares = new AvaloniaResources(asm, projectDirectory);
if (avares.Resources.Count(CheckXamlName) == 0 && emres.Resources.Count(CheckXamlName) == 0)
// Nothing to do
return null;
var clrPropertiesDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlHelpers",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(clrPropertiesDef);
var indexerAccessorClosure = new TypeDefinition("CompiledAvaloniaXaml", "!IndexerAccessorFactoryClosure",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(indexerAccessorClosure);
var trampolineBuilder = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlTrampolines",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(trampolineBuilder);
var (xamlLanguage , emitConfig) = AvaloniaXamlIlLanguage.Configure(typeSystem);
var compilerConfig = new AvaloniaXamlIlCompilerConfiguration(typeSystem,
typeSystem.TargetAssembly,
xamlLanguage,
XamlXmlnsMappings.Resolve(typeSystem, xamlLanguage),
AvaloniaXamlIlLanguage.CustomValueConverter,
new XamlIlClrPropertyInfoEmitter(typeSystem.CreateTypeBuilder(clrPropertiesDef)),
new XamlIlPropertyInfoAccessorFactoryEmitter(typeSystem.CreateTypeBuilder(indexerAccessorClosure)),
new XamlIlTrampolineBuilder(typeSystem.CreateTypeBuilder(trampolineBuilder)),
new DeterministicIdGenerator());
var contextDef = new TypeDefinition("CompiledAvaloniaXaml", "XamlIlContext",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
asm.MainModule.Types.Add(contextDef);
var contextClass = XamlILContextDefinition.GenerateContextClass(typeSystem.CreateTypeBuilder(contextDef), typeSystem,
xamlLanguage, emitConfig);
var compiler = new AvaloniaXamlIlCompiler(compilerConfig, emitConfig, contextClass) { EnableIlVerification = verifyIl };
var editorBrowsableAttribute = typeSystem
.GetTypeReference(typeSystem.FindType("System.ComponentModel.EditorBrowsableAttribute"))
.Resolve();
var editorBrowsableCtor =
asm.MainModule.ImportReference(editorBrowsableAttribute.GetConstructors()
.First(c => c.Parameters.Count == 1));
var runtimeHelpers = typeSystem.GetType("Avalonia.Markup.Xaml.XamlIl.Runtime.XamlIlRuntimeHelpers");
var createRootServiceProviderMethod = asm.MainModule.ImportReference(
typeSystem.GetTypeReference(runtimeHelpers).Resolve().Methods
.First(x => x.Name == "CreateRootServiceProviderV2"));
var loaderDispatcherDef = new TypeDefinition("CompiledAvaloniaXaml", "!XamlLoader",
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
loaderDispatcherDef.CustomAttributes.Add(new CustomAttribute(editorBrowsableCtor)
{
ConstructorArguments = {new CustomAttributeArgument(editorBrowsableCtor.Parameters[0].ParameterType, 1)}
});
var loaderDispatcherMethod = new MethodDefinition("TryLoad",
MethodAttributes.Static | MethodAttributes.Public,
asm.MainModule.TypeSystem.Object)
{
Parameters = {new ParameterDefinition(asm.MainModule.TypeSystem.String)}
};
loaderDispatcherDef.Methods.Add(loaderDispatcherMethod);
asm.MainModule.Types.Add(loaderDispatcherDef);
var stringEquals = asm.MainModule.ImportReference(asm.MainModule.TypeSystem.String.Resolve().Methods.First(
m =>
m.IsStatic && m.Name == "Equals" && m.Parameters.Count == 2 &&
m.ReturnType.FullName == "System.Boolean"
&& m.Parameters[0].ParameterType.FullName == "System.String"
&& m.Parameters[1].ParameterType.FullName == "System.String"));
bool CompileGroup(IResourceGroup group)
{
var typeDef = new TypeDefinition("CompiledAvaloniaXaml", "!"+ group.Name,
TypeAttributes.Class, asm.MainModule.TypeSystem.Object);
typeDef.CustomAttributes.Add(new CustomAttribute(editorBrowsableCtor)
{
ConstructorArguments = {new CustomAttributeArgument(editorBrowsableCtor.Parameters[0].ParameterType, 1)}
});
asm.MainModule.Types.Add(typeDef);
var builder = typeSystem.CreateTypeBuilder(typeDef);
foreach (var res in group.Resources.Where(CheckXamlName).OrderBy(x=>x.FilePath.ToLowerInvariant()))
{
try
{
engine.LogMessage($"XAMLIL: {res.Name} -> {res.Uri}", logImportance);
// StreamReader is needed here to handle BOM
var xaml = new StreamReader(new MemoryStream(res.FileContents)).ReadToEnd();
var parsed = XDocumentXamlParser.Parse(xaml);
var initialRoot = (XamlAstObjectNode)parsed.Root;
var precompileDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Precompile");
if (precompileDirective != null)
{
var precompileText = (precompileDirective.Values[0] as XamlAstTextNode)?.Text.Trim()
.ToLowerInvariant();
if (precompileText == "false")
continue;
if (precompileText != "true")
throw new XamlParseException("Invalid value for x:Precompile", precompileDirective);
}
var classDirective = initialRoot.Children.OfType<XamlAstXmlDirective>()
.FirstOrDefault(d => d.Namespace == XamlNamespaces.Xaml2006 && d.Name == "Class");
IXamlType classType = null;
if (classDirective != null)
{
if (classDirective.Values.Count != 1 || !(classDirective.Values[0] is XamlAstTextNode tn))
throw new XamlParseException("x:Class should have a string value", classDirective);
classType = typeSystem.TargetAssembly.FindType(tn.Text);
if (classType == null)
throw new XamlParseException($"Unable to find type `{tn.Text}`", classDirective);
compiler.OverrideRootType(parsed,
new XamlAstClrTypeReference(classDirective, classType, false));
initialRoot.Children.Remove(classDirective);
}
compiler.Transform(parsed);
var populateName = classType == null ? "Populate:" + res.Name : "!XamlIlPopulate";
var buildName = classType == null ? "Build:" + res.Name : null;
var classTypeDefinition =
classType == null ? null : typeSystem.GetTypeReference(classType).Resolve();
var populateBuilder = classTypeDefinition == null ?
builder :
typeSystem.CreateTypeBuilder(classTypeDefinition);
compiler.Compile(parsed, contextClass,
compiler.DefinePopulateMethod(populateBuilder, parsed, populateName,
classTypeDefinition == null),
buildName == null ? null : compiler.DefineBuildMethod(builder, parsed, buildName, true),
builder.DefineSubType(compilerConfig.WellKnownTypes.Object, "NamespaceInfo:" + res.Name,
true),
(closureName, closureBaseType) =>
populateBuilder.DefineSubType(closureBaseType, closureName, false),
(closureName, returnType, parameterTypes) =>
populateBuilder.DefineDelegateSubType(closureName, false, returnType, parameterTypes),
res.Uri, res
);
if (classTypeDefinition != null)
{
var compiledPopulateMethod = typeSystem.GetTypeReference(populateBuilder).Resolve()
.Methods.First(m => m.Name == populateName);
var designLoaderFieldType = typeSystem
.GetType("System.Action`1")
.MakeGenericType(typeSystem.GetType("System.Object"));
var designLoaderFieldTypeReference = (GenericInstanceType)typeSystem.GetTypeReference(designLoaderFieldType);
designLoaderFieldTypeReference.GenericArguments[0] =
asm.MainModule.ImportReference(designLoaderFieldTypeReference.GenericArguments[0]);
designLoaderFieldTypeReference = (GenericInstanceType)
asm.MainModule.ImportReference(designLoaderFieldTypeReference);
var designLoaderLoad =
typeSystem.GetMethodReference(
designLoaderFieldType.Methods.First(m => m.Name == "Invoke"));
designLoaderLoad =
asm.MainModule.ImportReference(designLoaderLoad);
designLoaderLoad.DeclaringType = designLoaderFieldTypeReference;
var designLoaderField = new FieldDefinition("!XamlIlPopulateOverride",
FieldAttributes.Static | FieldAttributes.Private, designLoaderFieldTypeReference);
classTypeDefinition.Fields.Add(designLoaderField);
const string TrampolineName = "!XamlIlPopulateTrampoline";
var trampoline = new MethodDefinition(TrampolineName,
MethodAttributes.Static | MethodAttributes.Private, asm.MainModule.TypeSystem.Void);
trampoline.Parameters.Add(new ParameterDefinition(classTypeDefinition));
classTypeDefinition.Methods.Add(trampoline);
var regularStart = Instruction.Create(OpCodes.Call, createRootServiceProviderMethod);
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, designLoaderField));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Brfalse, regularStart));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldsfld, designLoaderField));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Call, designLoaderLoad));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
trampoline.Body.Instructions.Add(regularStart);
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ldarg_0));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Call, compiledPopulateMethod));
trampoline.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
CopyDebugDocument(trampoline, compiledPopulateMethod);
var foundXamlLoader = false;
// Find AvaloniaXamlLoader.Load(this) and replace it with !XamlIlPopulateTrampoline(this)
foreach (var method in classTypeDefinition.Methods
.Where(m => !m.Attributes.HasFlag(MethodAttributes.Static)))
{
var i = method.Body.Instructions;
for (var c = 1; c < i.Count; c++)
{
if (i[c].OpCode == OpCodes.Call)
{
var op = i[c].Operand as MethodReference;
// TODO: Throw an error
// This usually happens when same XAML resource was added twice for some weird reason
// We currently support it for dual-named default theme resource
if (op != null
&& op.Name == TrampolineName)
{
foundXamlLoader = true;
break;
}
if (op != null
&& op.Name == "Load"
&& op.Parameters.Count == 1
&& op.Parameters[0].ParameterType.FullName == "System.Object"
&& op.DeclaringType.FullName == "Avalonia.Markup.Xaml.AvaloniaXamlLoader")
{
if (MatchThisCall(i, c - 1))
{
i[c].Operand = trampoline;
foundXamlLoader = true;
}
}
}
}
}
if (!foundXamlLoader)
{
var ctors = classTypeDefinition.GetConstructors()
.Where(c => !c.IsStatic).ToList();
// We can inject xaml loader into default constructor
if (ctors.Count == 1 && ctors[0].Body.Instructions.Count(o=>o.OpCode != OpCodes.Nop) == 3)
{
var i = ctors[0].Body.Instructions;
var retIdx = i.IndexOf(i.Last(x => x.OpCode == OpCodes.Ret));
i.Insert(retIdx, Instruction.Create(OpCodes.Call, trampoline));
i.Insert(retIdx, Instruction.Create(OpCodes.Ldarg_0));
}
else
{
throw new InvalidProgramException(
$"No call to AvaloniaXamlLoader.Load(this) call found anywhere in the type {classType.FullName} and type seems to have custom constructors.");
}
}
}
if (buildName != null || classTypeDefinition != null)
{
var compiledBuildMethod = buildName == null ?
null :
typeSystem.GetTypeReference(builder).Resolve()
.Methods.First(m => m.Name == buildName);
var parameterlessConstructor = compiledBuildMethod != null ?
null :
classTypeDefinition.GetConstructors().FirstOrDefault(c =>
c.IsPublic && !c.IsStatic && !c.HasParameters);
if (compiledBuildMethod != null || parameterlessConstructor != null)
{
var i = loaderDispatcherMethod.Body.Instructions;
var nop = Instruction.Create(OpCodes.Nop);
i.Add(Instruction.Create(OpCodes.Ldarg_0));
i.Add(Instruction.Create(OpCodes.Ldstr, res.Uri));
i.Add(Instruction.Create(OpCodes.Call, stringEquals));
i.Add(Instruction.Create(OpCodes.Brfalse, nop));
if (parameterlessConstructor != null)
i.Add(Instruction.Create(OpCodes.Newobj, parameterlessConstructor));
else
{
i.Add(Instruction.Create(OpCodes.Call, createRootServiceProviderMethod));
i.Add(Instruction.Create(OpCodes.Call, compiledBuildMethod));
}
i.Add(Instruction.Create(OpCodes.Ret));
i.Add(nop);
}
}
}
catch (Exception e)
{
int lineNumber = 0, linePosition = 0;
if (e is XamlParseException xe)
{
lineNumber = xe.LineNumber;
linePosition = xe.LinePosition;
}
engine.LogErrorEvent(new BuildErrorEventArgs("Avalonia", "XAMLIL", res.FilePath,
lineNumber, linePosition, lineNumber, linePosition,
e.Message, "", "Avalonia"));
return false;
}
res.Remove();
}
// Technically that's a hack, but it fixes corert incompatibility caused by deterministic builds
int dupeCounter = 1;
foreach (var grp in typeDef.NestedTypes.GroupBy(x => x.Name))
{
if (grp.Count() > 1)
{
foreach (var dupe in grp)
dupe.Name += "_dup" + dupeCounter++;
}
}
return true;
}
if (emres.Resources.Count(CheckXamlName) != 0)
if (!CompileGroup(emres))
return false;
if (avares.Resources.Count(CheckXamlName) != 0)
{
if (!CompileGroup(avares))
return false;
avares.Save();
}
loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ldnull));
loaderDispatcherMethod.Body.Instructions.Add(Instruction.Create(OpCodes.Ret));
return true;
}
}
}
| |
using System.Runtime.CompilerServices;
namespace System
{
/// <summary>
/// Represents an instant in time, typically expressed as a date and time of day.
/// </summary>
[Bridge.Convention(Member = Bridge.ConventionMember.Field | Bridge.ConventionMember.Method, Notation = Bridge.Notation.CamelCase)]
[Bridge.External]
[Bridge.Reflectable]
public struct DateTime : IComparable, IComparable<DateTime>, IEquatable<DateTime>, IFormattable
{
[Bridge.Template("System.DateTime.TicksPerDay")]
private const long TicksPerDay = 864000000000;
[Bridge.Template("System.DateTime.DaysTo1970")]
internal const int DaysTo1970 = 719162;
[Bridge.Template("System.DateTime.getMinTicks()")]
internal const long MinTicks = 0;
[Bridge.Template("System.DateTime.getMaxTicks()")]
internal const long MaxTicks = 3652059 * 864000000000 - 1;
/// <summary>
/// Represents the largest possible value of DateTime. This field is read-only.
/// </summary>
[Bridge.Template("System.DateTime.getMaxValue()")]
public static readonly DateTime MaxValue;
/// <summary>
/// Represents the smallest possible value of DateTime. This field is read-only.
/// </summary>
[Bridge.Template("System.DateTime.getMinValue()")]
public static readonly DateTime MinValue;
/// <summary>
/// Initializes a new instance of the DateTime structure.
/// </summary>
[Bridge.Template("System.DateTime.getDefaultValue()")]
private extern DateTime(DummyTypeUsedToAddAttributeToDefaultValueTypeConstructor _);
/// <summary>
/// Initializes a new instance of the DateTime structure to a specified number of ticks.
/// </summary>
/// <param name="ticks">A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar.</param>
[Bridge.Template("System.DateTime.create$2({0})")]
public extern DateTime(long ticks);
/// <summary>
/// Initializes a new instance of the DateTime structure to a specified number of ticks and to Coordinated Universal Time (UTC) or local time.
/// </summary>
/// <param name="ticks">A date and time expressed in the number of 100-nanosecond intervals that have elapsed since January 1, 0001 at 00:00:00.000 in the Gregorian calendar.</param>
/// <param name="kind">One of the enumeration values that indicates whether ticks specifies a local time, Coordinated Universal Time (UTC), or neither.</param>
[Bridge.Template("System.DateTime.create$2({0}, {1})")]
public extern DateTime(long ticks, DateTimeKind kind);
/// <summary>
/// Initializes a new instance of the DateTime structure to the specified year, month, and day.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in month).</param>
[Bridge.Template("System.DateTime.create({0}, {1}, {2})")]
public extern DateTime(int year, int month, int day);
/// <summary>
/// Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, and second.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in month).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
[Bridge.Template("System.DateTime.create({0}, {1}, {2}, {3}, {4}, {5})")]
public extern DateTime(int year, int month, int day, int hour, int minute, int second);
/// <summary>
/// Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and Coordinated Universal Time (UTC) or local time.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in month).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="kind">One of the enumeration values that indicates whether year, month, day, hour, minute, second, and millisecond specify a local time, Coordinated Universal Time (UTC), or neither.</param>
[Bridge.Template("System.DateTime.create({0}, {1}, {2}, {3}, {4}, {5}, 0, {6})")]
public extern DateTime(int year, int month, int day, int hour, int minute, int second, DateTimeKind kind);
/// <summary>
/// Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, and millisecond.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in month).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
[Bridge.Template("System.DateTime.create({0}, {1}, {2}, {3}, {4}, {5}, {6})")]
public extern DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond);
/// <summary>
/// Initializes a new instance of the DateTime structure to the specified year, month, day, hour, minute, second, millisecond, and Coordinated Universal Time (UTC) or local time.
/// </summary>
/// <param name="year">The year (1 through 9999).</param>
/// <param name="month">The month (1 through 12).</param>
/// <param name="day">The day (1 through the number of days in month).</param>
/// <param name="hour">The hours (0 through 23).</param>
/// <param name="minute">The minutes (0 through 59).</param>
/// <param name="second">The seconds (0 through 59).</param>
/// <param name="millisecond">The milliseconds (0 through 999).</param>
/// <param name="kind">One of the enumeration values that indicates whether year, month, day, hour, minute, second, and millisecond specify a local time, Coordinated Universal Time (UTC), or neither.</param>
[Bridge.Template("System.DateTime.create({0}, {1}, {2}, {3}, {4}, {5}, {6}, {7})")]
public extern DateTime(int year, int month, int day, int hour, int minute, int second, int millisecond, DateTimeKind kind);
/// <summary>
/// Gets the current date.
/// </summary>
public static extern DateTime Today
{
[Bridge.Template("System.DateTime.getToday()")]
get;
}
/// <summary>
/// Gets a DateTime object that is set to the current date and time on this computer, expressed as the local time.
/// </summary>
public static extern DateTime Now
{
[Bridge.Template("System.DateTime.getNow()")]
get;
}
/// <summary>
/// Gets a DateTime object that is set to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
/// </summary>
public static extern DateTime UtcNow
{
[Bridge.Template("System.DateTime.getUtcNow()")]
get;
}
/// <summary>
/// Gets a value that indicates whether the time represented by this instance is based on local time, Coordinated Universal Time (UTC), or neither.
/// </summary>
public DateTimeKind Kind
{
[Bridge.Template("System.DateTime.getKind({this})")]
get;
}
/// <summary>
/// Creates a new DateTime object that has the same number of ticks as the specified DateTime, but is designated as either local time, Coordinated Universal Time (UTC), or neither, as indicated by the specified DateTimeKind value.
/// </summary>
/// <param name="value">A date and time.</param>
/// <param name="kind">One of the enumeration values that indicates whether the new object represents local time, UTC, or neither.</param>
/// <returns>A new object that has the same number of ticks as the object represented by the value parameter and the DateTimeKind value specified by the kind parameter.</returns>
[Bridge.Template("System.DateTime.specifyKind({0}, {1})")]
public extern static DateTime SpecifyKind(DateTime value, DateTimeKind kind);
/// <summary>
/// Creates a DateTime from a Windows filetime. A Windows filetime is a long representing the date and time as the number of 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
/// </summary>
/// <param name="fileTime">Ticks</param>
/// <returns>DateTime</returns>
[Bridge.Template("System.DateTime.FromFileTime({0})")]
public extern static DateTime FromFileTime(long fileTime);
/// <summary>
/// Creates a DateTime from a Windows filetime. A Windows filetime is a long representing the date and time as the number of 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am UTC.
/// </summary>
/// <param name="fileTime">Ticks</param>
/// <returns>DateTime</returns>
[Bridge.Template("System.DateTime.FromFileTimeUtc({0})")]
public extern static DateTime FromFileTimeUtc(long fileTime);
[Bridge.Template("System.DateTime.ToFileTime({this})")]
public extern long ToFileTime();
[Bridge.Template("System.DateTime.ToFileTimeUtc({this})")]
public extern long ToFileTimeUtc();
[Bridge.Template(Fn = "System.DateTime.format")]
public override extern string ToString();
[Bridge.Template("System.DateTime.format({this}, {0})")]
public extern string ToString(string format);
[Bridge.Template("System.DateTime.format({this}, {0}, {1})")]
public extern string ToString(string format, IFormatProvider provider);
[Bridge.Template("System.DateTime.parse({0})")]
public static extern DateTime Parse(string s);
[Bridge.Template("System.DateTime.parse({0}, {1})")]
public static extern DateTime Parse(string s, IFormatProvider provider);
[Bridge.Template("System.DateTime.tryParse({0}, null, {1})")]
public static extern bool TryParse(string s, out DateTime result);
[Bridge.Template("System.DateTime.parseExact({0}, {1}, {2})")]
public static extern DateTime ParseExact(string s, string format, IFormatProvider provider);
[Bridge.Template("System.DateTime.tryParseExact({0}, {1}, {2}, {3})")]
public static extern bool TryParseExact(string s, string format, IFormatProvider provider, out DateTime result);
[Bridge.Template("System.DateTime.subdt({0}, {1})")]
public static extern DateTime operator -(DateTime d, TimeSpan t);
[Bridge.Template("System.DateTime.adddt({0}, {1})")]
public static extern DateTime operator +(DateTime d, TimeSpan t);
[Bridge.Template("System.DateTime.subdd({0}, {1})")]
public static extern TimeSpan operator -(DateTime a, DateTime b);
[Bridge.Template("System.DateTime.subdd({this}, {0})")]
public extern TimeSpan Subtract(DateTime value);
[Bridge.Template("Bridge.equals({0}, {1})")]
public static extern bool operator ==(DateTime a, DateTime b);
[Bridge.Template("!Bridge.equals({0}, {1})")]
public static extern bool operator !=(DateTime a, DateTime b);
[Bridge.Template("System.DateTime.lt({0}, {1})")]
public static extern bool operator <(DateTime a, DateTime b);
[Bridge.Template("System.DateTime.gt({0}, {1})")]
public static extern bool operator >(DateTime a, DateTime b);
[Bridge.Template("System.DateTime.lte({0}, {1})")]
public static extern bool operator <=(DateTime a, DateTime b);
[Bridge.Template("System.DateTime.gte({0}, {1})")]
public static extern bool operator >=(DateTime a, DateTime b);
/// <summary>
/// Gets the date component of this instance.
/// </summary>
public extern DateTime Date
{
[Bridge.Template("System.DateTime.getDate({this})")]
get;
}
/// <summary>
/// Gets the day of the year represented by this instance.
/// </summary>
public extern int DayOfYear
{
[Bridge.Template("System.DateTime.getDayOfYear({this})")]
get;
}
/// <summary>
/// Gets the day of the week represented by this instance.
/// </summary>
public extern DayOfWeek DayOfWeek
{
[Bridge.Template("System.DateTime.getDayOfWeek({this})")]
get;
}
/// <summary>
/// Gets the year component of the date represented by this instance.
/// </summary>
public extern int Year
{
[Bridge.Template("System.DateTime.getYear({this})")]
get;
}
/// <summary>
/// Gets the month component of the date represented by this instance.
/// </summary>
public extern int Month
{
[Bridge.Template("System.DateTime.getMonth({this})")]
get;
}
/// <summary>
/// Gets the day of the month represented by this instance.
/// </summary>
public extern int Day
{
[Bridge.Template("System.DateTime.getDay({this})")]
get;
}
/// <summary>
/// Gets the hour component of the date represented by this instance.
/// </summary>
public extern int Hour
{
[Bridge.Template("System.DateTime.getHour({this})")]
get;
}
/// <summary>
/// Gets the milliseconds component of the date represented by this instance.
/// </summary>
public extern int Millisecond
{
[Bridge.Template("System.DateTime.getMillisecond({this})")]
get;
}
/// <summary>
/// Gets the minute component of the date represented by this instance.
/// </summary>
public extern int Minute
{
[Bridge.Template("System.DateTime.getMinute({this})")]
get;
}
/// <summary>
/// Gets the seconds component of the date represented by this instance.
/// </summary>
public extern int Second
{
[Bridge.Template("System.DateTime.getSecond({this})")]
get;
}
/// <summary>
/// Gets the time of day for this instance.
/// </summary>
public extern TimeSpan TimeOfDay
{
[Bridge.Template("System.DateTime.getTimeOfDay({this})")]
get;
}
/// <summary>
/// Gets the number of ticks that represent the date and time of this instance.
/// </summary>
public extern long Ticks
{
[Bridge.Template("System.DateTime.getTicks({this})")]
get;
}
/// <summary>
/// Returns a new DateTime that adds the specified number of years to the value of this instance.
/// </summary>
/// <param name="value">A number of years. The value parameter can be negative or positive.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the number of years represented by value.</returns>
[Bridge.Template("System.DateTime.addYears({this}, {0})")]
public extern DateTime AddYears(int value);
/// <summary>
/// Returns a new DateTime that adds the specified number of months to the value of this instance.
/// </summary>
/// <param name="months">A number of months. The months parameter can be negative or positive.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and months.</returns>
[Bridge.Template("System.DateTime.addMonths({this}, {0})")]
public extern DateTime AddMonths(int months);
/// <summary>
/// Returns a new DateTime that adds the specified number of days to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional days. The value parameter can be negative or positive.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the number of days represented by value.</returns>
[Bridge.Template("System.DateTime.addDays({this}, {0})")]
public extern DateTime AddDays(double value);
/// <summary>
/// Returns a new DateTime that adds the specified number of hours to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional hours. The value parameter can be negative or positive.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the number of hours represented by value.</returns>
[Bridge.Template("System.DateTime.addHours({this}, {0})")]
public extern DateTime AddHours(double value);
/// <summary>
/// Returns a new DateTime that adds the specified number of minutes to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional minutes. The value parameter can be negative or positive.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the number of minutes represented by value.</returns>
[Bridge.Template("System.DateTime.addMinutes({this}, {0})")]
public extern DateTime AddMinutes(double value);
/// <summary>
/// Returns a new DateTime that adds the specified number of seconds to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional seconds. The value parameter can be negative or positive.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the number of seconds represented by value.</returns>
[Bridge.Template("System.DateTime.addSeconds({this}, {0})")]
public extern DateTime AddSeconds(double value);
/// <summary>
/// Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
/// </summary>
/// <param name="value">A number of whole and fractional milliseconds. The value parameter can be negative or positive. Note that this value is rounded to the nearest integer.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the number of milliseconds represented by value.</returns>
[Bridge.Template("System.DateTime.addMilliseconds({this}, {0})")]
public extern DateTime AddMilliseconds(double value);
/// <summary>
/// Returns a new DateTime that adds the specified number of ticks to the value of this instance.
/// </summary>
/// <param name="value">A number of 100-nanosecond ticks. The value parameter can be positive or negative.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the time represented by value.</returns>
[Bridge.Template("System.DateTime.addTicks({this}, {0})")]
public extern DateTime AddTicks(long value);
/// <summary>
/// Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
/// </summary>
/// <param name="value">A positive or negative time interval.</param>
/// <returns>An object whose value is the sum of the date and time represented by this instance and the time interval represented by value.</returns>
[Bridge.Template("System.DateTime.add({this}, {0})")]
public extern DateTime Add(TimeSpan value);
/// <summary>
/// Subtracts the specified time or duration from this instance.
/// </summary>
/// <param name="value">The time interval to subtract.</param>
/// <returns>An object that is equal to the date and time represented by this instance minus the time interval represented by value.</returns>
[Bridge.Template("System.DateTime.subtract({this}, {0})")]
public extern DateTime Subtract(TimeSpan value);
/// <summary>
/// Returns the number of days in the specified month and year.
/// </summary>
/// <param name="year">The year.</param>
/// <param name="month">The month (a number ranging from 1 to 12).</param>
/// <returns>The number of days in month for the specified year.</returns>
[Bridge.Template("System.DateTime.getDaysInMonth({0}, {1})")]
public static extern int DaysInMonth(int year, int month);
/// <summary>
/// Returns an indication whether the specified year is a leap year.
/// </summary>
/// <param name="year">A 4-digit year.</param>
/// <returns>true if year is a leap year; otherwise, false.</returns>
[Bridge.Template("System.DateTime.getIsLeapYear({0})")]
public static extern bool IsLeapYear(int year);
[Bridge.Template("Bridge.compare({this}, {0})")]
public extern int CompareTo(DateTime other);
[Bridge.Template("Bridge.compare({this}, {0})")]
public extern int CompareTo(object other);
[Bridge.Template("Bridge.compare({t1}, {t2})")]
public static extern int Compare(DateTime t1, DateTime t2);
[Bridge.Template("Bridge.equalsT({this}, {0})")]
public extern bool Equals(DateTime other);
[Bridge.Template("Bridge.equalsT({0}, {1})")]
public static extern bool Equals(DateTime t1, DateTime t2);
/// <summary>
/// Indicates whether this instance of DateTime is within the daylight saving time range for the current time zone.
/// </summary>
/// <returns>true if the value of the Kind property is Local or Unspecified and the value of this instance of DateTime is within the daylight saving time range for the local time zone; false if Kind is Utc.</returns>
[Bridge.Template("System.DateTime.isDaylightSavingTime({this})")]
public extern bool IsDaylightSavingTime();
/// <summary>
/// Converts the value of the current DateTime object to Coordinated Universal Time (UTC).
/// </summary>
/// <returns>An object whose Kind property is Utc, and whose value is the UTC equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented by a DateTime object.</returns>
[Bridge.Template("System.DateTime.toUniversalTime({this})")]
public extern DateTime ToUniversalTime();
/// <summary>
/// Converts the value of the current DateTime object to local time.
/// </summary>
/// <returns>An object whose Kind property is Local, and whose value is the local time equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented as a DateTime object.</returns>
[Bridge.Template("System.DateTime.toLocalTime({this})")]
public extern DateTime ToLocalTime();
/// <summary>
/// Converts the value of the current DateTime object to local time.
/// </summary>
/// <returns>An object whose Kind property is Local, and whose value is the local time equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented as a DateTime object.</returns>
[Bridge.Template("System.DateTime.toLocalTime({this}, {0})")]
public extern DateTime ToLocalTime(bool throwOnOverflow);
/// <summary>
/// Converts the value of the current DateTime object to its equivalent short date string representation.
/// </summary>
/// <returns>A string that contains the short date string representation of the current DateTime object.</returns>
[Bridge.Template("System.DateTime.format({this}, \"d\")")]
public extern string ToShortDateString();
/// <summary>
/// Converts the value of the current DateTime object to its equivalent short time string representation.
/// </summary>
/// <returns>A string that contains the short time string representation of the current DateTime object.</returns>
[Bridge.Template("System.DateTime.format({this}, \"t\")")]
public extern string ToShortTimeString();
}
}
| |
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
namespace InControl
{
[InitializeOnLoad]
internal class InputManagerAssetGenerator
{
const string productName = "InControl";
static List<AxisPreset> axisPresets = new List<AxisPreset>();
static InputManagerAssetGenerator()
{
if (!CheckAxisPresets())
{
Debug.LogError( productName + " has detected invalid InputManager settings. To fix, execute 'Edit > Project Settings > " + productName + " > Setup InputManager Settings'." );
}
}
[MenuItem( "Edit/Project Settings/" + productName + "/Setup InputManager Settings" )]
static void GenerateInputManagerAsset()
{
ApplyAxisPresets();
Debug.Log( productName + " has successfully generated new InputManager settings." );
}
[MenuItem( "Edit/Project Settings/" + productName + "/Check InputManager Settings" )]
static void CheckInputManagerAsset()
{
if (CheckAxisPresets())
{
Debug.Log( "InputManager settings are fine." );
}
else
{
Debug.LogError( productName + " has detected invalid InputManager settings. To fix, execute 'Edit > Project Settings > " + productName + " > Setup InputManager Settings'." );
}
}
static bool CheckAxisPresets()
{
SetupAxisPresets();
var axisArray = GetInputManagerAxisArray();
if (axisArray.arraySize != axisPresets.Count)
{
return false;
}
for (int i = 0; i < axisPresets.Count; i++)
{
var axisEntry = axisArray.GetArrayElementAtIndex( i );
if (!axisPresets[i].EqualTo( axisEntry ))
{
return false;
}
}
return true;
}
static void ApplyAxisPresets()
{
SetupAxisPresets();
var inputManagerAsset = AssetDatabase.LoadAllAssetsAtPath( "ProjectSettings/InputManager.asset" )[0];
var serializedObject = new SerializedObject( inputManagerAsset );
var axisArray = serializedObject.FindProperty( "m_Axes" );
axisArray.arraySize = axisPresets.Count;
serializedObject.ApplyModifiedProperties();
for (int i = 0; i < axisPresets.Count; i++)
{
var axisEntry = axisArray.GetArrayElementAtIndex( i );
axisPresets[i].ApplyTo( ref axisEntry );
}
serializedObject.ApplyModifiedProperties();
AssetDatabase.Refresh();
}
static void SetupAxisPresets()
{
axisPresets.Clear();
CreateRequiredAxisPresets();
ImportExistingAxisPresets();
CreateCompatibilityAxisPresets();
}
static void CreateRequiredAxisPresets()
{
for (int device = 1; device <= UnityInputDevice.MaxDevices; device++)
{
for (int analog = 0; analog < UnityInputDevice.MaxAnalogs; analog++)
{
axisPresets.Add( new AxisPreset( device, analog ) );
}
}
axisPresets.Add( new AxisPreset( "mouse x", 1, 0, 1.0f ) );
axisPresets.Add( new AxisPreset( "mouse y", 1, 1, 1.0f ) );
axisPresets.Add( new AxisPreset( "mouse z", 1, 2, 1.0f ) );
}
static void ImportExistingAxisPresets()
{
var axisArray = GetInputManagerAxisArray();
for (int i = 0; i < axisArray.arraySize; i++)
{
var axisEntry = axisArray.GetArrayElementAtIndex( i );
var axisPreset = new AxisPreset( axisEntry );
if (!axisPreset.ReservedName)
{
axisPresets.Add( axisPreset );
}
}
}
static void CreateCompatibilityAxisPresets()
{
if (!HasAxisPreset( "Mouse ScrollWheel" ))
{
axisPresets.Add( new AxisPreset( "Mouse ScrollWheel", 1, 2, 0.1f ) );
}
if (!HasAxisPreset( "Horizontal" ))
{
axisPresets.Add( new AxisPreset() {
name = "Horizontal",
negativeButton = "left",
positiveButton = "right",
altNegativeButton = "a",
altPositiveButton = "d",
gravity = 3.0f,
deadZone = 0.001f,
sensitivity = 3.0f,
snap = true,
type = 0,
axis = 0,
joyNum = 0
} );
axisPresets.Add( new AxisPreset() {
name = "Horizontal",
gravity = 0.0f,
deadZone = 0.19f,
sensitivity = 1.0f,
type = 2,
axis = 0,
joyNum = 0
} );
}
if (!HasAxisPreset( "Vertical" ))
{
axisPresets.Add( new AxisPreset() {
name = "Vertical",
negativeButton = "down",
positiveButton = "up",
altNegativeButton = "s",
altPositiveButton = "w",
gravity = 3.0f,
deadZone = 0.001f,
sensitivity = 3.0f,
snap = true,
type = 0,
axis = 0,
joyNum = 0
} );
axisPresets.Add( new AxisPreset() {
name = "Vertical",
gravity = 0.0f,
deadZone = 0.19f,
sensitivity = 1.0f,
type = 2,
axis = 0,
invert = true,
joyNum = 0
} );
}
if (!HasAxisPreset( "Submit" ))
{
axisPresets.Add( new AxisPreset() {
name = "Submit",
positiveButton = "return",
altPositiveButton = "joystick button 0",
gravity = 1000.0f,
deadZone = 0.001f,
sensitivity = 1000.0f,
type = 0,
axis = 0,
joyNum = 0
} );
axisPresets.Add( new AxisPreset() {
name = "Submit",
positiveButton = "enter",
altPositiveButton = "space",
gravity = 1000.0f,
deadZone = 0.001f,
sensitivity = 1000.0f,
type = 0,
axis = 0,
joyNum = 0
} );
}
if (!HasAxisPreset( "Cancel" ))
{
axisPresets.Add( new AxisPreset() {
name = "Cancel",
positiveButton = "escape",
altPositiveButton = "joystick button 1",
gravity = 1000.0f,
deadZone = 0.001f,
sensitivity = 1000.0f,
type = 0,
axis = 0,
joyNum = 0
} );
}
}
static bool HasAxisPreset( string name )
{
for (int i = 0; i < axisPresets.Count; i++)
{
if (axisPresets[i].name == name)
{
return true;
}
}
return false;
}
static SerializedProperty GetInputManagerAxisArray()
{
var inputManagerAsset = AssetDatabase.LoadAllAssetsAtPath( "ProjectSettings/InputManager.asset" )[0];
var serializedObject = new SerializedObject( inputManagerAsset );
return serializedObject.FindProperty( "m_Axes" );
}
static SerializedProperty GetChildProperty( SerializedProperty parent, string name )
{
SerializedProperty child = parent.Copy();
child.Next( true );
do
{
if (child.name == name)
{
return child;
}
} while (child.Next( false ));
return null;
}
internal class AxisPreset
{
public string name;
public string descriptiveName;
public string descriptiveNegativeName;
public string negativeButton;
public string positiveButton;
public string altNegativeButton;
public string altPositiveButton;
public float gravity;
public float deadZone = 0.001f;
public float sensitivity = 1.0f;
public bool snap;
public bool invert;
public int type;
public int axis;
public int joyNum;
public AxisPreset()
{
}
public AxisPreset( SerializedProperty axisPreset )
{
this.name = GetChildProperty( axisPreset, "m_Name" ).stringValue;
this.descriptiveName = GetChildProperty( axisPreset, "descriptiveName" ).stringValue;
this.descriptiveNegativeName = GetChildProperty( axisPreset, "descriptiveNegativeName" ).stringValue;
this.negativeButton = GetChildProperty( axisPreset, "negativeButton" ).stringValue;
this.positiveButton = GetChildProperty( axisPreset, "positiveButton" ).stringValue;
this.altNegativeButton = GetChildProperty( axisPreset, "altNegativeButton" ).stringValue;
this.altPositiveButton = GetChildProperty( axisPreset, "altPositiveButton" ).stringValue;
this.gravity = GetChildProperty( axisPreset, "gravity" ).floatValue;
this.deadZone = GetChildProperty( axisPreset, "dead" ).floatValue;
this.sensitivity = GetChildProperty( axisPreset, "sensitivity" ).floatValue;
this.snap = GetChildProperty( axisPreset, "snap" ).boolValue;
this.invert = GetChildProperty( axisPreset, "invert" ).boolValue;
this.type = GetChildProperty( axisPreset, "type" ).intValue;
this.axis = GetChildProperty( axisPreset, "axis" ).intValue;
this.joyNum = GetChildProperty( axisPreset, "joyNum" ).intValue;
}
public AxisPreset( string name, int type, int axis, float sensitivity )
{
this.name = name;
this.descriptiveName = "";
this.descriptiveNegativeName = "";
this.negativeButton = "";
this.positiveButton = "";
this.altNegativeButton = "";
this.altPositiveButton = "";
this.gravity = 0.0f;
this.deadZone = 0.001f;
this.sensitivity = sensitivity;
this.snap = false;
this.invert = false;
this.type = type;
this.axis = axis;
this.joyNum = 0;
}
public AxisPreset( int device, int analog )
{
this.name = string.Format( "joystick {0} analog {1}", device, analog );
this.descriptiveName = "";
this.descriptiveNegativeName = "";
this.negativeButton = "";
this.positiveButton = "";
this.altNegativeButton = "";
this.altPositiveButton = "";
this.gravity = 0.0f;
this.deadZone = 0.001f;
this.sensitivity = 1.0f;
this.snap = false;
this.invert = false;
this.type = 2;
this.axis = analog;
this.joyNum = device;
}
public bool ReservedName
{
get
{
if (Regex.Match( name, @"^joystick \d+ analog \d+$" ).Success ||
Regex.Match( name, @"^mouse (x|y|z)$" ).Success)
{
return true;
}
return false;
}
}
public void ApplyTo( ref SerializedProperty axisPreset )
{
GetChildProperty( axisPreset, "m_Name" ).stringValue = name;
GetChildProperty( axisPreset, "descriptiveName" ).stringValue = descriptiveName;
GetChildProperty( axisPreset, "descriptiveNegativeName" ).stringValue = descriptiveNegativeName;
GetChildProperty( axisPreset, "negativeButton" ).stringValue = negativeButton;
GetChildProperty( axisPreset, "positiveButton" ).stringValue = positiveButton;
GetChildProperty( axisPreset, "altNegativeButton" ).stringValue = altNegativeButton;
GetChildProperty( axisPreset, "altPositiveButton" ).stringValue = altPositiveButton;
GetChildProperty( axisPreset, "gravity" ).floatValue = gravity;
GetChildProperty( axisPreset, "dead" ).floatValue = deadZone;
GetChildProperty( axisPreset, "sensitivity" ).floatValue = sensitivity;
GetChildProperty( axisPreset, "snap" ).boolValue = snap;
GetChildProperty( axisPreset, "invert" ).boolValue = invert;
GetChildProperty( axisPreset, "type" ).intValue = type;
GetChildProperty( axisPreset, "axis" ).intValue = axis;
GetChildProperty( axisPreset, "joyNum" ).intValue = joyNum;
}
public bool EqualTo( SerializedProperty axisPreset )
{
if (GetChildProperty( axisPreset, "m_Name" ).stringValue != name)
return false;
if (GetChildProperty( axisPreset, "descriptiveName" ).stringValue != descriptiveName)
return false;
if (GetChildProperty( axisPreset, "descriptiveNegativeName" ).stringValue != descriptiveNegativeName)
return false;
if (GetChildProperty( axisPreset, "negativeButton" ).stringValue != negativeButton)
return false;
if (GetChildProperty( axisPreset, "positiveButton" ).stringValue != positiveButton)
return false;
if (GetChildProperty( axisPreset, "altNegativeButton" ).stringValue != altNegativeButton)
return false;
if (GetChildProperty( axisPreset, "altPositiveButton" ).stringValue != altPositiveButton)
return false;
if (!Mathf.Approximately( GetChildProperty( axisPreset, "gravity" ).floatValue, gravity ))
return false;
if (!Mathf.Approximately( GetChildProperty( axisPreset, "dead" ).floatValue, deadZone ))
return false;
if (!Mathf.Approximately( GetChildProperty( axisPreset, "sensitivity" ).floatValue, this.sensitivity ))
return false;
if (GetChildProperty( axisPreset, "snap" ).boolValue != snap)
return false;
if (GetChildProperty( axisPreset, "invert" ).boolValue != invert)
return false;
if (GetChildProperty( axisPreset, "type" ).intValue != type)
return false;
if (GetChildProperty( axisPreset, "axis" ).intValue != axis)
return false;
if (GetChildProperty( axisPreset, "joyNum" ).intValue != joyNum)
return false;
return true;
}
}
}
}
#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.
using System.Diagnostics;
using System.Text;
namespace System.IO
{
public static partial class Path
{
public static char[] GetInvalidFileNameChars() => new char[]
{
'\"', '<', '>', '|', '\0',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31, ':', '*', '?', '\\', '/'
};
public static char[] GetInvalidPathChars() => new char[]
{
'|', '\0',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31
};
// Expands the given path to a fully qualified path.
public static string GetFullPath(string path)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
// If the path would normalize to string empty, we'll consider it empty
if (PathInternal.IsEffectivelyEmpty(path))
throw new ArgumentException(SR.Arg_PathEmpty, nameof(path));
// Embedded null characters are the only invalid character case we trully care about.
// This is because the nulls will signal the end of the string to Win32 and therefore have
// unpredictable results.
if (path.IndexOf('\0') != -1)
throw new ArgumentException(SR.Argument_InvalidPathChars, nameof(path));
if (PathInternal.IsExtended(path))
{
// \\?\ paths are considered normalized by definition. Windows doesn't normalize \\?\
// paths and neither should we. Even if we wanted to GetFullPathName does not work
// properly with device paths. If one wants to pass a \\?\ path through normalization
// one can chop off the prefix, pass it to GetFullPath and add it again.
return path;
}
return PathHelper.Normalize(path);
}
public static string GetFullPath(string path, string basePath)
{
if (path == null)
throw new ArgumentNullException(nameof(path));
if (basePath == null)
throw new ArgumentNullException(nameof(basePath));
if (!IsPathFullyQualified(basePath))
throw new ArgumentException(SR.Arg_BasePathNotFullyQualified, nameof(basePath));
if (basePath.Contains('\0') || path.Contains('\0'))
throw new ArgumentException(SR.Argument_InvalidPathChars);
if (IsPathFullyQualified(path))
return GetFullPath(path);
int length = path.Length;
string combinedPath = null;
if ((length >= 1 && PathInternal.IsDirectorySeparator(path[0])))
{
// Path is current drive rooted i.e. starts with \:
// "\Foo" and "C:\Bar" => "C:\Foo"
// "\Foo" and "\\?\C:\Bar" => "\\?\C:\Foo"
combinedPath = CombineNoChecks(GetPathRoot(basePath), path.AsSpan().Slice(1));
}
else if (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar)
{
// Drive relative paths
Debug.Assert(length == 2 || !PathInternal.IsDirectorySeparator(path[2]));
if (StringSpanHelpers.Equals(GetVolumeName(path.AsSpan()), GetVolumeName(basePath.AsSpan())))
{
// Matching root
// "C:Foo" and "C:\Bar" => "C:\Bar\Foo"
// "C:Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
combinedPath = CombineNoChecks(basePath, path.AsSpan().Slice(2));
}
else
{
// No matching root, root to specified drive
// "D:Foo" and "C:\Bar" => "D:Foo"
// "D:\Foo" and "\\?\C:\Bar" => "\\?\D:\Foo"
combinedPath = path.Insert(2, "\\");
}
}
else
{
// "Simple" relative path
// "Foo" and "C:\Bar" => "C:\Bar\Foo"
// "Foo" and "\\?\C:\Bar" => "\\?\C:\Bar\Foo"
combinedPath = CombineNoChecks(basePath, path);
}
// Device paths are normalized by definition, so passing something of this format
// to GetFullPath() won't do anything by design. Additionally, GetFullPathName() in
// Windows doesn't root them properly. As such we need to manually remove segments.
return PathInternal.IsDevice(combinedPath)
? RemoveRelativeSegments(combinedPath, PathInternal.GetRootLength(combinedPath))
: GetFullPath(combinedPath);
}
public static string GetTempPath()
{
StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH);
uint r = Interop.Kernel32.GetTempPathW(Interop.Kernel32.MAX_PATH, sb);
if (r == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
return GetFullPath(StringBuilderCache.GetStringAndRelease(sb));
}
// Returns a unique temporary file name, and creates a 0-byte file by that
// name on disk.
public static string GetTempFileName()
{
string path = GetTempPath();
StringBuilder sb = StringBuilderCache.Acquire(Interop.Kernel32.MAX_PATH);
uint r = Interop.Kernel32.GetTempFileNameW(path, "tmp", 0, sb);
if (r == 0)
throw Win32Marshal.GetExceptionForLastWin32Error();
return StringBuilderCache.GetStringAndRelease(sb);
}
// Tests if the given path contains a root. A path is considered rooted
// if it starts with a backslash ("\") or a valid drive letter and a colon (":").
public static bool IsPathRooted(string path)
{
return path != null && IsPathRooted(path.AsSpan());
}
public static bool IsPathRooted(ReadOnlySpan<char> path)
{
int length = path.Length;
return (length >= 1 && PathInternal.IsDirectorySeparator(path[0]))
|| (length >= 2 && PathInternal.IsValidDriveChar(path[0]) && path[1] == PathInternal.VolumeSeparatorChar);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null. If the path is empty or
// only contains whitespace characters an ArgumentException gets thrown.
public static string GetPathRoot(string path)
{
if (PathInternal.IsEffectivelyEmpty(path))
return null;
ReadOnlySpan<char> result = GetPathRoot(path.AsSpan());
if (path.Length == result.Length)
return PathInternal.NormalizeDirectorySeparators(path);
return PathInternal.NormalizeDirectorySeparators(new string(result));
}
/// <remarks>
/// Unlike the string overload, this method will not normalize directory separators.
/// </remarks>
public static ReadOnlySpan<char> GetPathRoot(ReadOnlySpan<char> path)
{
if (PathInternal.IsEffectivelyEmpty(path))
return ReadOnlySpan<char>.Empty;
int pathRoot = PathInternal.GetRootLength(path);
return pathRoot <= 0 ? ReadOnlySpan<char>.Empty : path.Slice(0, pathRoot);
}
/// <summary>Gets whether the system is case-sensitive.</summary>
internal static bool IsCaseSensitive { get { return false; } }
/// <summary>
/// Returns the volume name for dos, UNC and device paths.
/// </summary>
internal static ReadOnlySpan<char> GetVolumeName(ReadOnlySpan<char> path)
{
// 3 cases: UNC ("\\server\share"), Device ("\\?\C:\"), or Dos ("C:\")
ReadOnlySpan<char> root = GetPathRoot(path);
if (root.Length == 0)
return root;
int offset = GetUncRootLength(path);
if (offset >= 0)
{
// Cut from "\\?\UNC\Server\Share" to "Server\Share"
// Cut from "\\Server\Share" to "Server\Share"
return TrimEndingDirectorySeparator(root.Slice(offset));
}
else if (PathInternal.IsDevice(path))
{
return TrimEndingDirectorySeparator(root.Slice(4)); // Cut from "\\?\C:\" to "C:"
}
return TrimEndingDirectorySeparator(root); // e.g. "C:"
}
/// <summary>
/// Returns true if the path ends in a directory separator.
/// </summary>
internal static bool EndsInDirectorySeparator(ReadOnlySpan<char> path)
{
return path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]);
}
/// <summary>
/// Trims the ending directory separator if present.
/// </summary>
/// <param name="path"></param>
internal static ReadOnlySpan<char> TrimEndingDirectorySeparator(ReadOnlySpan<char> path) =>
EndsInDirectorySeparator(path) ?
path.Slice(0, path.Length - 1) :
path;
/// <summary>
/// Returns offset as -1 if the path is not in Unc format, otherwise returns the root length.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
internal static int GetUncRootLength(ReadOnlySpan<char> path)
{
bool isDevice = PathInternal.IsDevice(path);
if (!isDevice && StringSpanHelpers.Equals(path.Slice(0, 2), @"\\") )
return 2;
else if (isDevice && path.Length >= 8
&& (StringSpanHelpers.Equals(path.Slice(0, 8), PathInternal.UncExtendedPathPrefix)
|| StringSpanHelpers.Equals(path.Slice(5, 4), @"UNC\")))
return 8;
return -1;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
using System;
using System.IO;
using System.Text;
namespace FileSystemTest
{
public class FileDelete : IMFTestInterface
{
[SetUp]
public InitializeResult Initialize()
{
Log.Comment("Adding set up for the tests.");
// Add your functionality here.
try
{
IOTests.IntializeVolume();
Directory.CreateDirectory(sourceDir);
Directory.CreateDirectory("Test " + sourceDir);
Directory.SetCurrentDirectory(sourceDir);
}
catch (Exception ex)
{
Log.Comment("Skipping: Unable to initialize file system" + ex.Message);
return InitializeResult.Skip;
}
return InitializeResult.ReadyToGo;
}
[TearDown]
public void CleanUp()
{
}
#region Local vars
private const string file1Name = "file1.tmp";
private const string file2Name = "file2.txt";
private const string sourceDir = "source";
#endregion Local vars
#region Helper methods
private bool TestDelete(string file)
{
bool success = true;
Log.Comment("Deleting " + file);
if (!File.Exists(file))
{
Log.Comment("Create " + file);
File.Create(file).Close();
if (!File.Exists(file))
{
Log.Exception("Could not find file after creation!");
success = false;
}
}
File.Delete(file);
if (File.Exists(file))
{
Log.Exception("File still exists after delete!");
success = false;
}
return success;
}
#endregion Helper methods
#region Test Cases
[TestMethod]
public MFTestResults ArgumentExceptionTests()
{
MFTestResults result = MFTestResults.Pass;
try
{
Log.Comment("Current Directory: " + Directory.GetCurrentDirectory());
try
{
Log.Comment("Null argument");
File.Delete(null);
Log.Exception( "Expected ArgumentException" );
return MFTestResults.Fail;
}
catch (ArgumentNullException ane)
{
/* pass case */ Log.Comment( "Got correct exception: " + ane.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("String.Empty argument");
File.Delete(string.Empty);
Log.Exception( "Expected ArgumentException" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Whitespace argument");
File.Delete(" ");
Log.Exception( "Expected ArgumentException" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("*.* argument");
File.Delete("*.*");
Log.Exception( "Expected ArgumentException" );
return MFTestResults.Fail;
}
catch (ArgumentException ae)
{
/* pass case */ Log.Comment( "Got correct exception: " + ae.Message );
result = MFTestResults.Pass;
}
try
{
Log.Comment("Current dir '.' argument");
File.Delete(".");
Log.Exception( "Expected ArgumentException" );
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
} // UnauthorizedAccess
try
{
Log.Comment("parent dir '..' argument");
File.Delete("..");
Log.Exception( "Expected ArgumentException" );
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
} // UnauthorizedAccess
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults IOExceptionTests()
{
MFTestResults result = MFTestResults.Pass;
FileStream fs = null;
try
{
Log.Comment("Current Directory: " + Directory.GetCurrentDirectory());
try
{
Log.Comment("non-existent file");
File.Delete("non-existent.file");
/// No exception is thrown for non existent file.
}
catch (IOException)
{
Log.Exception( "Unexpected IOException" );
return MFTestResults.Fail;
}
try
{
Log.Comment("Read only file");
File.Create(file1Name).Close();
File.SetAttributes(file1Name, FileAttributes.ReadOnly);
File.Delete(file1Name);
Log.Exception( "Expected IOException" );
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
} // UnauthorizedAccess
finally
{
if (File.Exists(file1Name))
{
Log.Comment("Clean up read only file");
File.SetAttributes(file1Name, FileAttributes.Normal);
File.Delete(file1Name);
}
}
try
{
Log.Comment("file in use");
fs = File.Create(file1Name);
File.Delete(file1Name);
Log.Exception( "Expected IOException" );
return MFTestResults.Fail;
}
catch (IOException ioe)
{
/* pass case */ Log.Comment( "Got correct exception: " + ioe.Message );
result = MFTestResults.Pass;
}
finally
{
if (fs != null)
{
Log.Comment("Clean up file in use");
fs.Close();
File.Delete(file1Name);
}
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults ValidCases()
{
MFTestResults result = MFTestResults.Pass;
FileStream fs = null;
try
{
Log.Comment("Current Directory: " + Directory.GetCurrentDirectory());
Log.Comment("relative delete");
if (!TestDelete(file1Name))
return MFTestResults.Fail;
Log.Comment("absolute delete");
if (!TestDelete(Directory.GetCurrentDirectory() + "\\" + file1Name))
return MFTestResults.Fail;
Log.Comment("Case insensitive lower delete");
File.Create(file1Name).Close();
if (!TestDelete(file1Name.ToLower()))
return MFTestResults.Fail;
Log.Comment("Case insensitive UPPER delete");
File.Create(file2Name).Close();
if (!TestDelete(file2Name.ToUpper()))
return MFTestResults.Fail;
Log.Comment("Write content to file");
byte[] hello = UTF8Encoding.UTF8.GetBytes("Hello world!");
fs = File.Create(file1Name);
fs.Write(hello, 0, hello.Length);
fs.Close();
if (!TestDelete(file1Name))
return MFTestResults.Fail;
Log.Comment("relative . delete");
File.Create(file2Name).Close();
if (!TestDelete(@".\" + file2Name))
return MFTestResults.Fail;
Log.Comment("relative .. delete");
File.Create(Path.Combine(IOTests.Volume.RootDirectory, file2Name)).Close();
if (!TestDelete(@"..\" + file2Name))
return MFTestResults.Fail;
Log.Comment("hidden file delete");
File.Create(file1Name).Close();
File.SetAttributes(file1Name, FileAttributes.Hidden);
if (!TestDelete(file1Name))
return MFTestResults.Fail;
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
[TestMethod]
public MFTestResults SpecialFileNames()
{
MFTestResults result = MFTestResults.Pass;
char[] special = new char[] { '!', '#', '$', '%', '\'', '(', ')', '+', '-', '.', '@', '[', ']', '_', '`', '{', '}', '~' };
try
{
Log.Comment("Create file each with special char file names");
for (int i = 0; i < special.Length; i++)
{
string file = i + "_" + new string(new char[] { special[i] }) + "_z.file";
if (!TestDelete(file))
return MFTestResults.Fail;
}
}
catch (Exception ex)
{
Log.Exception("Unexpected exception: " + ex.Message);
return MFTestResults.Fail;
}
return result;
}
#endregion Test Cases
public MFTestMethod[] Tests
{
get
{
return new MFTestMethod[]
{
new MFTestMethod( ArgumentExceptionTests, "ArgumentExceptionTests" ),
new MFTestMethod( IOExceptionTests, "IOExceptionTests" ),
new MFTestMethod( ValidCases, "ValidCases" ),
new MFTestMethod( SpecialFileNames, "SpecialFileNames" ),
};
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Debugger.Interop;
using Cosmos.Debug.Common;
using Cosmos.VS.DebugEngine.AD7.Definitions;
using Cosmos.VS.DebugEngine.Engine.Impl;
namespace Cosmos.VS.DebugEngine.AD7.Impl
{
// AD7Engine is the primary entrypoint object for the the debugger.
//
// It implements:
//
// IDebugEngine2: This interface represents a debug engine (DE). It is used to manage various aspects of a debugging session,
// from creating breakpoints to setting and clearing exceptions.
//
// IDebugEngineLaunch2: Used by a debug engine (DE) to launch and terminate programs.
//
// IDebugProgram3: This interface represents a program that is running in a process. Since this engine only debugs one process at a time and each
// process only contains one program, it is implemented on the engine.
//
// IDebugEngineProgram2: This interface provides simultanious debugging of multiple threads in a debuggee.
[ComVisible(true)]
[Guid(Guids.guidDebugEngineString)]
public class AD7Engine : IDebugEngine2, IDebugEngineLaunch2, IDebugProgram3, IDebugEngineProgram2
{
internal IDebugProgram2 mProgram;
// We only support one process, so we just keep a ref to it and save a lot of accounting.
internal AD7Process mProcess;
// A unique identifier for the program being debugged.
Guid mProgramID;
public static readonly Guid EngineID = new Guid("fa1da3a6-66ff-4c65-b077-e65f7164ef83");
internal AD7Module mModule;
internal AD7Thread mThread;
private AD7ProgramNode mProgNode;
public IList<IDebugBoundBreakpoint2> Breakpoints = null;
// This object facilitates calling from this thread into the worker thread of the engine. This is necessary because the Win32 debugging
// api requires thread affinity to several operations.
// This object manages breakpoints in the sample engine.
protected BreakpointManager mBPMgr;
public BreakpointManager BPMgr
{
get { return mBPMgr; }
}
public AD7Engine()
{
mBPMgr = new BreakpointManager(this);
}
// Used to send events to the debugger. Some examples of these events are thread create, exception thrown, module load.
EngineCallback mEngineCallback;
internal EngineCallback Callback
{
get { return mEngineCallback; }
}
#region Startup Methods
// During startup these methods are called in this order:
// -LaunchSuspended
// -ResumeProcess
// -Attach - Triggered by Attach
int IDebugEngineLaunch2.LaunchSuspended(string aPszServer, IDebugPort2 aPort, string aDebugInfo
, string aArgs, string aDir, string aEnv, string aOptions, enum_LAUNCH_FLAGS aLaunchFlags
, uint aStdInputHandle, uint aStdOutputHandle, uint hStdError, IDebugEventCallback2 aAD7Callback
, out IDebugProcess2 oProcess)
{
// Launches a process by means of the debug engine.
// Normally, Visual Studio launches a program using the IDebugPortEx2::LaunchSuspended method and then attaches the debugger
// to the suspended program. However, there are circumstances in which the debug engine may need to launch a program
// (for example, if the debug engine is part of an interpreter and the program being debugged is an interpreted language),
// in which case Visual Studio uses the IDebugEngineLaunch2::LaunchSuspended method
// The IDebugEngineLaunch2::ResumeProcess method is called to start the process after the process has been successfully launched in a suspended state.
oProcess = null;
try
{
mEngineCallback = new EngineCallback(this, aAD7Callback);
var xDebugInfo = new Dictionary<string, string>();
DictionaryHelper.LoadFromString(xDebugInfo, aDebugInfo);
//TODO: In the future we might support command line args for kernel etc
//string xCmdLine = EngineUtils.BuildCommandLine(exe, args);
//var processLaunchInfo = new ProcessLaunchInfo(exe, xCmdLine, dir, env, options, launchFlags, hStdInput, hStdOutput, hStdError);
AD7EngineCreateEvent.Send(this);
oProcess = mProcess = new AD7Process(xDebugInfo, mEngineCallback, this, aPort);
// We only support one process, so just use its ID for the program ID
mProgramID = mProcess.ID;
//AD7ThreadCreateEvent.Send(this, xProcess.Thread);
mModule = new AD7Module();
mProgNode = new AD7ProgramNode(mProcess.PhysID);
}
catch (NotSupportedException)
{
return VSConstants.S_FALSE;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngine2.Attach(IDebugProgram2[] rgpPrograms, IDebugProgramNode2[] rgpProgramNodes, uint aCeltPrograms, IDebugEventCallback2 ad7Callback, enum_ATTACH_REASON dwReason)
{
// Attach the debug engine to a program.
//
// Attach can either be called to attach to a new process, or to complete an attach
// to a launched process.
// So could we simplify and move code from LaunchSuspended to here and maybe even
// eliminate the debughost? Although I supposed DebugHost has some other uses as well.
if (aCeltPrograms != 1)
{
System.Diagnostics.Debug.Fail("Cosmos Debugger only supports one debug target at a time.");
throw new ArgumentException();
}
try
{
EngineUtils.RequireOk(rgpPrograms[0].GetProgramId(out mProgramID));
mProgram = rgpPrograms[0];
AD7EngineCreateEvent.Send(this);
AD7ProgramCreateEvent.Send(this);
AD7ModuleLoadEvent.Send(this, mModule, true);
// Dummy main thread
// We dont support threads yet, but the debugger expects threads.
// So we create a dummy object to represente our only "thread".
mThread = new AD7Thread(this, mProcess);
AD7LoadCompleteEvent.Send(this, mThread);
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngineLaunch2.ResumeProcess(IDebugProcess2 aProcess)
{
// Resume a process launched by IDebugEngineLaunch2.LaunchSuspended
try
{
// Send a program node to the SDM. This will cause the SDM to turn around and call IDebugEngine2.Attach
// which will complete the hookup with AD7
var xProcess = aProcess as AD7Process;
if (xProcess == null)
{
return VSConstants.E_INVALIDARG;
}
IDebugPort2 xPort;
EngineUtils.RequireOk(aProcess.GetPort(out xPort));
var xDefPort = (IDebugDefaultPort2)xPort;
IDebugPortNotify2 xNotify;
EngineUtils.RequireOk(xDefPort.GetPortNotify(out xNotify));
// This triggers Attach
EngineUtils.RequireOk(xNotify.AddProgramNode(mProgNode));
Callback.OnModuleLoad(mModule);
Callback.OnSymbolSearch(mModule, xProcess.mISO.Replace("iso", "pdb"), enum_MODULE_INFO_FLAGS.MIF_SYMBOLS_LOADED);
// Important!
//
// This call triggers setting of breakpoints that exist before run.
// So it must be called before we resume the process.
// If not called VS will call it after our 3 startup events, but thats too late.
// This line was commented out in earlier Cosmos builds and caused problems with
// breakpoints and timing.
Callback.OnThreadStart(mThread);
// Not sure what this does exactly. It was commented out before
// but so was a lot of stuff we actually needed. If its uncommented it
// throws:
// "Operation is not valid due to the current state of the object."
//AD7EntrypointEvent.Send(this);
// Now finally release our process to go after breakpoints are set
mProcess.ResumeFromLaunch();
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
#endregion
#region Other implemented support methods
int IDebugEngine2.ContinueFromSynchronousEvent(IDebugEvent2 aEvent)
{
// Called by the SDM to indicate that a synchronous debug event, previously sent by the DE to the SDM,
// was received and processed. The only event the engine sends in this fashion is Program Destroy.
// It responds to that event by shutting down the engine.
//
// This is used in some cases - I set a BP here and it does get hit sometime during breakpoints
// being triggered for example.
try
{
if (aEvent is AD7ProgramDestroyEvent)
{
mEngineCallback = null;
mProgramID = Guid.Empty;
mThread = null;
mProgNode = null;
}
else
{
System.Diagnostics.Debug.Fail("Unknown synchronious event");
}
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngine2.CreatePendingBreakpoint(IDebugBreakpointRequest2 pBPRequest, out IDebugPendingBreakpoint2 ppPendingBP)
{
// Creates a pending breakpoint in the engine. A pending breakpoint is contains all the information needed to bind a breakpoint to
// a location in the debuggee.
ppPendingBP = null;
try
{
BPMgr.CreatePendingBreakpoint(pBPRequest, out ppPendingBP);
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
int IDebugEngine2.DestroyProgram(IDebugProgram2 pProgram)
{
// Informs a DE that the program specified has been atypically terminated and that the DE should
// clean up all references to the program and send a program destroy event.
//
// Tell the SDM that the engine knows that the program is exiting, and that the
// engine will send a program destroy. We do this because the Win32 debug api will always
// tell us that the process exited, and otherwise we have a race condition.
return AD7_HRESULT.E_PROGRAM_DESTROY_PENDING;
}
int IDebugEngine2.GetEngineId(out Guid oGuidEngine)
{
// Gets the GUID of the DebugEngine.
oGuidEngine = EngineID;
return VSConstants.S_OK;
}
int IDebugEngineLaunch2.TerminateProcess(IDebugProcess2 aProcess)
{
// This function is used to terminate a process that the SampleEngine launched
// The debugger will call IDebugEngineLaunch2::CanTerminateProcess before calling this method.
try
{
mProcess.Terminate();
mEngineCallback.OnProcessExit(0);
mProgram = null;
}
catch (Exception e)
{
return EngineUtils.UnexpectedException(e);
}
return VSConstants.S_OK;
}
public int Continue(IDebugThread2 aThread)
{
// We don't appear to use or support this currently.
// Continue is called from the SDM when it wants execution to continue in the debugee
// but have stepping state remain. An example is when a tracepoint is executed,
// and the debugger does not want to actually enter break mode.
var xThread = (AD7Thread)aThread;
//if (AfterBreak) {
//Callback.OnBreak(xThread);
//}
return VSConstants.S_OK;
}
int IDebugEngine2.CauseBreak()
{
// Requests that all programs being debugged by this DE stop execution the next time one of their threads attempts to run.
// This is normally called in response to the user clicking on the pause button in the debugger.
// When the break is complete, an AsyncBreakComplete event will be sent back to the debugger.
return ((IDebugProgram2)this).CauseBreak();
}
public int Detach()
{
// Detach is called when debugging is stopped and the process was attached to (as opposed to launched)
// or when one of the Detach commands are executed in the UI.
BPMgr.ClearBoundBreakpoints();
return VSConstants.S_OK;
}
public int EnumModules(out IEnumDebugModules2 ppEnum)
{
// EnumModules is called by the debugger when it needs to enumerate the modules in the program.
ppEnum = new AD7ModuleEnum(new[] { mModule });
return VSConstants.S_OK;
}
public int EnumThreads(out IEnumDebugThreads2 ppEnum)
{
// EnumThreads is called by the debugger when it needs to enumerate the threads in the program.
ppEnum = new AD7ThreadEnum(new[] { mThread });
return VSConstants.S_OK;
}
public int GetEngineInfo(out string engineName, out Guid engineGuid)
{
// Gets the name and identifier of the debug engine (DE) running this program.
engineName = "Cosmos Debug Engine";
engineGuid = EngineID;
return VSConstants.S_OK;
}
public int GetProgramId(out Guid aGuidProgramId)
{
// Gets a GUID for this program. A debug engine (DE) must return the program identifier originally passed to the IDebugProgramNodeAttach2::OnAttach
// or IDebugEngine2::Attach methods. This allows identification of the program across debugger components.
aGuidProgramId = mProgramID;
return VSConstants.S_OK;
}
public int Step(IDebugThread2 pThread, enum_STEPKIND sk, enum_STEPUNIT Step)
{
// This method is deprecated. Use the IDebugProcess3::Step method instead.
mProcess.Step((enum_STEPKIND)sk);
return VSConstants.S_OK;
}
public int ExecuteOnThread(IDebugThread2 pThread)
{
// ExecuteOnThread is called when the SDM wants execution to continue and have
// stepping state cleared.
mProcess.Continue();
return VSConstants.S_OK;
}
#endregion
#region Unimplemented methods
// Gets the name of the program.
// The name returned by this method is always a friendly, user-displayable name that describes the program.
public int GetName(out string programName)
{
// The Sample engine uses default transport and doesn't need to customize the name of the program,
// so return NULL.
programName = null;
return VSConstants.S_OK;
}
// This method gets the Edit and Continue (ENC) update for this program. A custom debug engine always returns E_NOTIMPL
public int GetENCUpdate(out object update)
{
// The sample engine does not participate in managed edit & continue.
update = null;
return VSConstants.S_OK;
}
// Removes the list of exceptions the IDE has set for a particular run-time architecture or language.
// We dont support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.RemoveAllSetExceptions(ref Guid guidType)
{
return VSConstants.S_OK;
}
// Removes the specified exception so it is no longer handled by the debug engine.
// The sample engine does not support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.RemoveSetException(EXCEPTION_INFO[] pException)
{
// We stop on all exceptions.
return VSConstants.S_OK;
}
// Specifies how the DE should handle a given exception.
// We dont support exceptions in the debuggee so this method is not actually implemented.
int IDebugEngine2.SetException(EXCEPTION_INFO[] pException)
{
return VSConstants.S_OK;
}
// Sets the locale of the DE.
// This method is called by the session debug manager (SDM) to propagate the locale settings of the IDE so that
// strings returned by the DE are properly localized. The sample engine is not localized so this is not implemented.
int IDebugEngine2.SetLocale(ushort wLangID)
{
return VSConstants.S_OK;
}
// A metric is a registry value used to change a debug engine's behavior or to advertise supported functionality.
// This method can forward the call to the appropriate form of the Debugging SDK Helpers function, SetMetric.
int IDebugEngine2.SetMetric(string pszMetric, object varValue)
{
// The sample engine does not need to understand any metric settings.
return VSConstants.S_OK;
}
// Sets the registry root currently in use by the DE. Different installations of Visual Studio can change where their registry information is stored
// This allows the debugger to tell the engine where that location is.
int IDebugEngine2.SetRegistryRoot(string pszRegistryRoot)
{
// The sample engine does not read settings from the registry.
return VSConstants.S_OK;
}
public string GetAddressDescription(uint ip)
{
// DebuggedModule module = m_debuggedProcess.ResolveAddress(ip);
return EngineUtils.GetAddressDescription(/*module,*/this, ip);
}
// Determines if a debug engine (DE) can detach from the program.
public int CanDetach()
{
// We always support detach
return VSConstants.S_OK;
}
// The debugger calls CauseBreak when the user clicks on the pause button in VS. The debugger should respond by entering
// breakmode.
public int CauseBreak()
{
return this.mProcess.CauseBreak();
}
// EnumCodePaths is used for the step-into specific feature -- right click on the current statment and decide which
// function to step into. This is not something that the SampleEngine supports.
public int EnumCodePaths(string hint, IDebugCodeContext2 start, IDebugStackFrame2 frame, int fSource, out IEnumCodePaths2 pathEnum, out IDebugCodeContext2 safetyContext)
{
pathEnum = null;
safetyContext = null;
return VSConstants.E_NOTIMPL;
}
// The properties returned by this method are specific to the program. If the program needs to return more than one property,
// then the IDebugProperty2 object returned by this method is a container of additional properties and calling the
// IDebugProperty2::EnumChildren method returns a list of all properties.
// A program may expose any number and type of additional properties that can be described through the IDebugProperty2 interface.
// An IDE might display the additional program properties through a generic property browser user interface.
// The sample engine does not support this
public int GetDebugProperty(out IDebugProperty2 ppProperty)
{
throw new NotImplementedException();
}
// The debugger calls this when it needs to obtain the IDebugDisassemblyStream2 for a particular code-context.
// The sample engine does not support dissassembly so it returns E_NOTIMPL
public int GetDisassemblyStream(enum_DISASSEMBLY_STREAM_SCOPE dwScope, IDebugCodeContext2 codeContext, out IDebugDisassemblyStream2 disassemblyStream)
{
disassemblyStream = null;
return VSConstants.E_NOTIMPL;
}
// The memory bytes as represented by the IDebugMemoryBytes2 object is for the program's image in memory and not any memory
// that was allocated when the program was executed.
public int GetMemoryBytes(out IDebugMemoryBytes2 ppMemoryBytes)
{
throw new Exception("The method or operation is not implemented.");
}
// Writes a dump to a file.
public int WriteDump(enum_DUMPTYPE DUMPTYPE, string pszDumpUrl)
{
// The sample debugger does not support creating or reading mini-dumps.
return VSConstants.E_NOTIMPL;
}
// Stops all threads running in this program.
// This method is called when this program is being debugged in a multi-program environment. When a stopping event from some other program
// is received, this method is called on this program. The implementation of this method should be asynchronous;
// that is, not all threads should be required to be stopped before this method returns. The implementation of this method may be
// as simple as calling the IDebugProgram2::CauseBreak method on this program.
//
// The sample engine only supports debugging native applications and therefore only has one program per-process
public int Stop()
{
throw new Exception("The method or operation is not implemented.");
}
// WatchForExpressionEvaluationOnThread is used to cooperate between two different engines debugging
// the same process. The sample engine doesn't cooperate with other engines, so it has nothing
// to do here.
public int WatchForExpressionEvaluationOnThread(IDebugProgram2 pOriginatingProgram, uint dwTid, uint dwEvalFlags, IDebugEventCallback2 pExprCallback, int fWatch)
{
return VSConstants.S_OK;
}
// WatchForThreadStep is used to cooperate between two different engines debugging the same process.
// The sample engine doesn't cooperate with other engines, so it has nothing to do here.
public int WatchForThreadStep(IDebugProgram2 pOriginatingProgram, uint dwTid, int fWatch, uint dwFrame)
{
return VSConstants.S_OK;
}
// Terminates the program.
public int Terminate()
{
mProgram = null;
// Because the sample engine is a native debugger, it implements IDebugEngineLaunch2, and will terminate
// the process in IDebugEngineLaunch2.TerminateProcess
return VSConstants.S_OK;
}
// Enumerates the code contexts for a given position in a source file.
public int EnumCodeContexts(IDebugDocumentPosition2 pDocPos, out IEnumDebugCodeContexts2 ppEnum)
{
throw new NotImplementedException();
}
// Determines if a process can be terminated.
int IDebugEngineLaunch2.CanTerminateProcess(IDebugProcess2 process)
{
return VSConstants.S_OK;
//try {
// int processId = EngineUtils.GetProcessId(process);
// //if (processId == m_debuggedProcess.Id)
// {
// return VSConstants.S_OK;
// }
// //else
// {
// //return VSConstants.S_FALSE;
// }
//}
// //catch (ComponentException e)
// //{
// // return e.HResult;
// //}
//catch (Exception e) {
// return EngineUtils.UnexpectedException(e);
//}
}
#endregion
#region Deprecated interface methods
// These methods are not called by the Visual Studio debugger, so they don't need to be implemented
int IDebugEngine2.EnumPrograms(out IEnumDebugPrograms2 programs)
{
System.Diagnostics.Debug.Fail("This function is not called by the debugger");
programs = null;
return VSConstants.E_NOTIMPL;
}
public int Attach(IDebugEventCallback2 pCallback)
{
System.Diagnostics.Debug.Fail("This function is not called by the debugger");
return VSConstants.E_NOTIMPL;
}
public int GetProcess(out IDebugProcess2 process)
{
System.Diagnostics.Debug.Fail("This function is not called by the debugger");
process = null;
return VSConstants.E_NOTIMPL;
}
public int Execute()
{
System.Diagnostics.Debug.Fail("This function is not called by the debugger.");
return VSConstants.E_NOTIMPL;
}
#endregion
}
}
| |
//-----------------------------------------------------------------------------
//
// <copyright file="TextAnchor.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description:
// TextAnchor represents a set of TextSegments that are part of an annotation's
// attached anchor. The TextSegments do not overlap and are ordered.
//
// We cannot use TextRange for this purpose because we need to represent sets of
// TextSegments that are not valid TextRanges (such as non-rectangular regions of
// a table).
//
// History:
// 11/16/2005: rruiz: creates the TextAnchor class
//
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using MS.Internal;
namespace System.Windows.Annotations
{
/// <summary>
/// </summary>
public sealed class TextAnchor
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// Creates an empty TextAnchor. If left empty it will be invalid for most operations.
/// </summary>
internal TextAnchor()
{
}
/// <summary>
/// Creates a clone of the passed in TextAnchor.
/// </summary>
/// <param name="anchor"></param>
internal TextAnchor(TextAnchor anchor)
{
Invariant.Assert(anchor != null, "Anchor to clone is null.");
foreach (TextSegment segment in anchor.TextSegments)
{
_segments.Add(new TextSegment(segment.Start, segment.End));
}
}
/*
* Code used to trim text segments for alternative display of sticky note anchors
*
/// <summary>
/// ctor that initializes the TextSegments array by cloning and trimming the input segment Array
/// </summary>
/// <param name="segments">input segment</param>
/// <remarks>This is used to convert a TextRange into TextAnchor.
/// Input segments must be ordered and non overlapping</remarks>
internal TextAnchor(IList<TextSegment> segments)
{
if (segments == null)
return;
ITextPointer lastPointer = null;
for (int i = 0; i < segments.Count; i++)
{
Invariant.Assert((lastPointer == null) || (lastPointer.CompareTo(segments[i].Start) <= 0), "overlapped segments found");
TextSegment newSegment = TextAnchor.Trim(segments[i]);
if (newSegment.IsNull)
continue;
_segments.Add(newSegment);
lastPointer = newSegment.End;
}
}
*/
#endregion Constructors
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
#region Public Methods
/// <summary>
/// Determines if the text pointer is contained by one of the
/// anchor's TextSegment.s
/// </summary>
/// <param name="textPointer">text pointer to test</param>
internal bool Contains(ITextPointer textPointer)
{
if (textPointer == null)
{
throw new ArgumentNullException("textPointer");
}
if (textPointer.TextContainer != this.Start.TextContainer)
{
throw new ArgumentException(SR.Get(SRID.NotInAssociatedTree, "textPointer"));
}
// Correct position normalization on range boundary so that
// our test would not depend on what side of formatting tags
// pointer is located.
if (textPointer.CompareTo(this.Start) < 0)
{
textPointer = textPointer.GetInsertionPosition(LogicalDirection.Forward);
}
else if (textPointer.CompareTo(this.End) > 0)
{
textPointer = textPointer.GetInsertionPosition(LogicalDirection.Backward);
}
// Check if at least one segment contains this position.
for (int i = 0; i < _segments.Count; i++)
{
if (_segments[i].Contains(textPointer))
{
return true;
}
}
return false;
}
/// <summary>
/// Add a text segment with the specified text pointers.
/// </summary>
/// <param name="start">start pointer for the new text segment</param>
/// <param name="end">end pointer for the new text segment</param>
internal void AddTextSegment(ITextPointer start, ITextPointer end)
{
Invariant.Assert(start != null, "Non-null start required to create segment.");
Invariant.Assert(end != null, "Non-null end required to create segment.");
TextSegment newSegment = CreateNormalizedSegment(start, end);
InsertSegment(newSegment);
}
/// <summary>
/// Returns the hash code for this anchor. Implementation is required
/// because Equals was overriden.
/// </summary>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// Determines if two TextAnchors are equal - they contain
/// the same number of segments and the segments all have the
/// same start and ends.
/// </summary>
/// <param name="obj">the other TextAnchor to compare to</param>
public override bool Equals(object obj)
{
TextAnchor other = obj as TextAnchor;
if (other == null)
return false;
if (other._segments.Count != this._segments.Count)
return false;
for (int i = 0; i < _segments.Count; i++)
{
if ((_segments[i].Start.CompareTo(other._segments[i].Start) != 0) ||
(_segments[i].End.CompareTo(other._segments[i].End) != 0))
return false;
}
return true;
}
/// <summary>
/// Determines if there is any overlap between this anchor and the passed
/// in set of TextSegments.
/// </summary>
/// <param name="textSegments">set of segments to test against</param>
internal bool IsOverlapping(ICollection<TextSegment> textSegments)
{
Invariant.Assert(textSegments != null, "TextSegments must not be null.");
textSegments = SortTextSegments(textSegments, false);
TextSegment ourSegment, theirSegment;
IEnumerator<TextSegment> ourEnumerator = _segments.GetEnumerator();
IEnumerator<TextSegment> theirEnumerator = textSegments.GetEnumerator();
bool moreOurs = ourEnumerator.MoveNext();
bool moreTheirs = theirEnumerator.MoveNext();
while (moreOurs && moreTheirs)
{
ourSegment = ourEnumerator.Current;
theirSegment = theirEnumerator.Current;
//special case for 0 length segments
if (theirSegment.Start.CompareTo(theirSegment.End) == 0)
{
// Check boundaries. If theirSegment is at the beginning/end of ourSegment
// we check the LogicalDirection. Thus we can handle end of lines, end of pages,
// bidiractional texts (arabic etc)
// If their segment is at the start of ourSegment
// We have overlapping if the direction of theirSegment.Start is toward ourSegment
if ((ourSegment.Start.CompareTo(theirSegment.Start) == 0) &&
(theirSegment.Start.LogicalDirection == LogicalDirection.Forward))
return true;
// If their segment is at the end of ourSegment
// We have overlapping if the direction of theirSegment.End is toward ourSegment
if ((ourSegment.End.CompareTo(theirSegment.End) == 0) &&
(theirSegment.End.LogicalDirection == LogicalDirection.Backward))
return true;
}
// our segment is after their segment, so try the next of their segments
if (ourSegment.Start.CompareTo(theirSegment.End) >= 0)
{
moreTheirs = theirEnumerator.MoveNext(); // point to the next of their segments
continue;
}
// our segment is before their segment so try next of our segments
if (ourSegment.End.CompareTo(theirSegment.Start) <= 0)
{
moreOurs = ourEnumerator.MoveNext(); // point to the next of our segments
continue;
}
// at this point we know for sure that there is some overlap
return true;
}
// no overlaps found
return false;
}
/// <summary>
/// Calculate the 'exclusive' union of the two anchors. Exclusive means none of the segments
/// contributed by either anchor are allowed to overlap. The method will throw an exception if
/// they do. This method modifies the first anchor passed in. Callers should assign the
/// result of this method to the anchor they passed in.
/// </summary>
internal static TextAnchor ExclusiveUnion(TextAnchor anchor, TextAnchor otherAnchor)
{
Invariant.Assert(anchor != null, "anchor must not be null.");
Invariant.Assert(otherAnchor != null, "otherAnchor must not be null.");
foreach (TextSegment segment in otherAnchor.TextSegments)
{
anchor.InsertSegment(segment);
}
return anchor;
}
/// <summary>
/// Modifies the passed in TextAnchor to contain its relative
/// complement to the set of text segments passed in. The resulting
/// TextAnchor contains those segments or portions of segments that do
/// not overlap with the passed in segments in anyway. If after trimming
/// the anchor has no more segments, null is returned instead. Callers
/// should assign the result of this method to the anchor they passed in.
/// </summary>
/// <param name="anchor">the anchor to trim</param>
/// <param name="textSegments">the text segments to calculate relative complement with</param>
/// <remarks>Note: textSegments is expected to be ordered and contain no overlapping segments</remarks>
internal static TextAnchor TrimToRelativeComplement(TextAnchor anchor, ICollection<TextSegment> textSegments)
{
Invariant.Assert(anchor != null, "Anchor must not be null.");
Invariant.Assert(textSegments != null, "TextSegments must not be null.");
textSegments = SortTextSegments(textSegments, true);
IEnumerator<TextSegment> enumerator = textSegments.GetEnumerator();
bool hasMore = enumerator.MoveNext();
int currentIndex = 0;
TextSegment current;
TextSegment otherSegment = TextSegment.Null;
while (currentIndex < anchor._segments.Count && hasMore)
{
Invariant.Assert(otherSegment.Equals(TextSegment.Null) || otherSegment.Equals(enumerator.Current) || otherSegment.End.CompareTo(enumerator.Current.Start) <= 0, "TextSegments are overlapping or not ordered.");
current = anchor._segments[currentIndex];
otherSegment = enumerator.Current;
// Current segment is after other segment, no overlap
// Also, done with the other segment, move to the next one
if (current.Start.CompareTo(otherSegment.End) >= 0)
{
hasMore = enumerator.MoveNext();
continue; // No increment, still processing the current segment
}
// Current segment starts after other segment starts and ...
if (current.Start.CompareTo(otherSegment.Start) >= 0)
{
// ends before other segment ends, complete overlap, remove the segment
if (current.End.CompareTo(otherSegment.End) <= 0)
{
anchor._segments.RemoveAt(currentIndex);
continue; // No increment, happens implicitly because of the removal
}
else
{
// ends after other segment, first portion of current overlaps,
// create new segment from end of other segment to end of current
anchor._segments[currentIndex] = CreateNormalizedSegment(otherSegment.End, current.End);
// Done with the other segment, move to the next one
hasMore = enumerator.MoveNext();
continue; // No increment, need to process just created segment
}
}
// Current segment starts before other segment starts and ...
else
{
// ends after it starts, first portion of current does not overlap,
// create new segment for that portion
if (current.End.CompareTo(otherSegment.Start) > 0)
{
anchor._segments[currentIndex] = CreateNormalizedSegment(current.Start, otherSegment.Start);
// If there's any portion of current after other segment, create a new segment for that which
// will be the next one processed
if (current.End.CompareTo(otherSegment.End) > 0)
{
// Overlap ends before current segment's end, we create a new segment with the remainder of current segment
anchor._segments.Insert(currentIndex + 1, CreateNormalizedSegment(otherSegment.End, current.End));
// Done with the other segment, move to the next one
hasMore = enumerator.MoveNext();
}
}
// ends before it starts, current is completely before other, no overlap, do nothing
}
currentIndex++;
}
if (anchor._segments.Count > 0)
return anchor;
else
return null;
}
/// <summary>
/// Modifies the text anchor's TextSegments so all of them
/// overlap with the passed in text segments. This is used
/// for instance to clamp a TextAnchor to a set of visible
/// text segments. If after trimming the anchor has no more
/// segments, null is returned instead. Callers should
/// assign the result of this method to the anchor they
/// passed in.
/// </summary>
/// <remarks>
/// Note: This method assumes textSegments is ordered and do not overlap amongs themselves
///
/// The target of the method is to trim this anchor's segments to overlap with the passed in segments.
/// The loop handles the following three cases -
/// 1. Current segment is after other segment, the other segment doesn't contribute at all, we move to the next other segment
/// 2. Current segment is before other segment, no overlap, remove current segment
/// 3. Current segment starts before other segment, and ends after other segment begins,
/// therefore the portion from current's start to other's start should be trimmed
/// 4. Current segment starts in the middle of other segment, two possibilities
/// a. current segment is completely within other segment, the whole segment overlaps
/// so we move on to the next current segment
/// b. current segment ends after other segment ends, we split current into the
/// overlapped portion and the remainder which will be looked at separately
/// </remarks>
/// <param name="anchor">the anchor to trim</param>
/// <param name="textSegments">collection of text segments to intersect with</param>
internal static TextAnchor TrimToIntersectionWith(TextAnchor anchor, ICollection<TextSegment> textSegments)
{
Invariant.Assert(anchor != null, "Anchor must not be null.");
Invariant.Assert(textSegments != null, "TextSegments must not be null.");
textSegments = SortTextSegments(textSegments, true);
TextSegment currentSegment, otherSegment = TextSegment.Null;
int current = 0;
IEnumerator<TextSegment> enumerator = textSegments.GetEnumerator();
bool hasMore = enumerator.MoveNext();
while (current < anchor._segments.Count && hasMore)
{
Invariant.Assert(otherSegment.Equals(TextSegment.Null) || otherSegment.Equals(enumerator.Current) || otherSegment.End.CompareTo(enumerator.Current.Start) <= 0, "TextSegments are overlapping or not ordered.");
currentSegment = anchor._segments[current];
otherSegment = enumerator.Current;
// Current segment is after other segment, so try the next other segment
if (currentSegment.Start.CompareTo(otherSegment.End) >= 0)
{
hasMore = enumerator.MoveNext(); // point to the next other
continue; // Do not increment, we are still on the same current
}
// Current segment is before other segment, no overlap so remove it and continue
if (currentSegment.End.CompareTo(otherSegment.Start) <= 0)
{
anchor._segments.RemoveAt(current);
continue; // Do not increment, it happens implicitly because of the remove
}
//
// We know from here down that there is some overlap.
//
// Current starts before the other segment and ends after other segment begins, the first portion of current segment doesn't overlap so we remove it
if (currentSegment.Start.CompareTo(otherSegment.Start) < 0)
{
anchor._segments[current] = CreateNormalizedSegment(otherSegment.Start, currentSegment.End);
continue; // Do not increment, we need to look at this just created segment
}
// Current segment begins in the middle of other segment...
else
{
// and ends after other segment does, we split current into the portion that is overlapping and the remainder
if (currentSegment.End.CompareTo(otherSegment.End) > 0)
{
anchor._segments[current] = CreateNormalizedSegment(currentSegment.Start, otherSegment.End);
// This segment will be the first one looked at next
anchor._segments.Insert(current + 1, CreateNormalizedSegment(otherSegment.End, currentSegment.End));
hasMore = enumerator.MoveNext();
}
// and ends at the same place as other segment, its completely overlapping, we move on to the next other
else if (currentSegment.End.CompareTo(otherSegment.End) == 0)
{
hasMore = enumerator.MoveNext();
}
// and ends within other segment, its completely overlapping, but we aren't done with other so we just continue
}
current++;
}
// If we finished and there are no more other segments, then any remaining segments
// in our list must not overlap, so we remove them.
if (!hasMore && current < anchor._segments.Count)
{
anchor._segments.RemoveRange(current, anchor._segments.Count - current);
}
if (anchor._segments.Count == 0)
return null;
else
return anchor;
}
#endregion Public Methods
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
#region Public Properties
/// <summary>
/// The start of the bounding range of this TextAnchor.
/// </summary>
public ContentPosition BoundingStart
{
get
{
return Start as ContentPosition;
}
}
/// <summary>
/// The end of the bounding range of this TextAnchor.
/// </summary>
public ContentPosition BoundingEnd
{
get
{
return End as ContentPosition;
}
}
#endregion Public Properties
//------------------------------------------------------
//
// Internal Properties
//
//------------------------------------------------------
#region Internal Properties
/// <summary>
/// The start pointer of the first segment in the TextAnchor
/// </summary>
internal ITextPointer Start
{
get
{
return _segments.Count > 0 ? _segments[0].Start : null;
}
}
/// <summary>
/// The end pointer of the last segment in the TextAnchor
/// </summary>
internal ITextPointer End
{
get
{
return _segments.Count > 0 ? _segments[_segments.Count - 1].End : null;
}
}
/// <summary>
/// Returns whether or not this text anchor is empty - meaning
/// it has one text segment whose start and end are the same.
/// </summary>
internal bool IsEmpty
{
get
{
return (_segments.Count == 1 && (object)_segments[0].Start == (object)_segments[0].End);
}
}
/// <summary>
/// Returns a concatenation of the text for each of this anchor's
/// TextSegments.
/// </summary>
internal string Text
{
get
{
// Buffer for building a resulting plain text
StringBuilder textBuffer = new StringBuilder();
for (int i = 0; i < _segments.Count; i++)
{
textBuffer.Append(TextRangeBase.GetTextInternal(_segments[i].Start, _segments[i].End));
}
return textBuffer.ToString();
}
}
/// <summary>
/// Returns a read only collection of this anchor's TextSegments.
/// </summary>
internal ReadOnlyCollection<TextSegment> TextSegments
{
get
{
return _segments.AsReadOnly();
}
}
#endregion Internal Properties
//------------------------------------------------------
//
// Private Methods
//
//------------------------------------------------------
#region Private Methods
/// <summary>
/// Sorts a list of text segments by their Start pointer first then End pointer.
/// Used because list of TextSegments from a TextView are not guaranteed to be sorted
/// but in most cases they are.
/// Note: In most cases the set of segments is of count 1 and this method is a no-op.
/// In the majority of other cases the number of segments is less than 5.
/// In extreme cases (such as a table with many, many columns and each cell
/// in a row being split across pages) you may have more than 5 segments
/// but this is very rare.
/// </summary>
/// <param name="textSegments">segments to be sorted</param>
/// <param name="excludeZeroLength">We've seen 0 length segments in the TextView that overlap other segments
/// this will break our algorithm, so we remove them (excludeZeroLength = true). When we calculate
/// IsOverlapping 0-length segments are OK - then excludeZeroLength is false</param>
private static ICollection<TextSegment> SortTextSegments(ICollection<TextSegment> textSegments, bool excludeZeroLength)
{
Invariant.Assert(textSegments != null, "TextSegments must not be null.");
List<TextSegment> orderedList = new List<TextSegment>(textSegments.Count);
orderedList.AddRange(textSegments);
if (excludeZeroLength)
{
//remove 0 length segments - work around for a bug in MultiPageTextView
for (int i = orderedList.Count - 1; i >= 0; i--)
{
TextSegment segment = orderedList[i];
if (segment.Start.CompareTo(segment.End) >= 0)
{
//remove that one
orderedList.Remove(segment);
}
}
}
// If there are 0 or 1 segments, no need to sort, just return the original collection
if (orderedList.Count > 1)
{
orderedList.Sort(new TextSegmentComparer());
}
return orderedList;
}
/// <summary>
/// Inserts a segment into this anchor in the right order. If the new segment
/// overlaps with existing anchors it throws an exception.
/// </summary>
private void InsertSegment(TextSegment newSegment)
{
int i = 0;
for (; i < _segments.Count; i++)
{
if (newSegment.Start.CompareTo(_segments[i].Start) < 0)
break;
}
// Make sure it starts after the one its being put behind
if (i > 0 && newSegment.Start.CompareTo(_segments[i - 1].End) < 0)
throw new InvalidOperationException(SR.Get(SRID.TextSegmentsMustNotOverlap));
// Make sure it ends before the one its being put ahead of
if (i < _segments.Count && newSegment.End.CompareTo(_segments[i].Start) > 0)
throw new InvalidOperationException(SR.Get(SRID.TextSegmentsMustNotOverlap));
_segments.Insert(i, newSegment);
}
/// <summary>
/// Creates a new segment with the specified pointers, but first
/// normalizes them to make sure they are on insertion positions.
/// </summary>
/// <param name="start">start of the new segment</param>
/// <param name="end">end of the new segment</param>
private static TextSegment CreateNormalizedSegment(ITextPointer start, ITextPointer end)
{
// Normalize the segment
if (start.CompareTo(end) == 0)
{
// When the range is empty we must keep it that way during normalization
if (!TextPointerBase.IsAtInsertionPosition(start, start.LogicalDirection))
{
start = start.GetInsertionPosition(start.LogicalDirection);
end = start;
}
}
else
{
if (!TextPointerBase.IsAtInsertionPosition(start, start.LogicalDirection))
{
start = start.GetInsertionPosition(LogicalDirection.Forward);
}
if (!TextPointerBase.IsAtInsertionPosition(end, start.LogicalDirection))
{
end = end.GetInsertionPosition(LogicalDirection.Backward);
}
// Collapse range in case of overlapped normalization result
if (start.CompareTo(end) >= 0)
{
// The range is effectuvely empty, so collapse it to single pointer instance
if (start.LogicalDirection == LogicalDirection.Backward)
{
// Choose a position normalized backward,
start = end.GetFrozenPointer(LogicalDirection.Backward);
// NOTE that otherwise we will use start position,
// which is oriented and normalizd Forward
}
end = start;
}
}
return new TextSegment(start, end);
}
//
// Code used to trim text segments for alternative display of sticky note anchors.
//
///// <summary>
///// Trims certain whitespace off ends of segments if they fit certain
///// conditions - such as being inside of an embedded element.
///// Returns a whole new TextSegment that's been trimmed or TextSegment.Null
///// if the trimming results in a non-existent TextSegment.
///// </summary>
//private static TextSegment Trim(TextSegment segment)
//{
// ITextPointer cursor = segment.Start.CreatePointer();
// ITextPointer segmentStart = null;
// TextPointerContext nextContext = cursor.GetPointerContext(LogicalDirection.Forward);
// while ((cursor.CompareTo(segment.End) < 0) &&
// (nextContext != TextPointerContext.Text) &&
// (nextContext != TextPointerContext.EmbeddedElement))
// {
// // Simply skip all other opening tags
// cursor.MoveToNextContextPosition(LogicalDirection.Forward);
// nextContext = cursor.GetPointerContext(LogicalDirection.Forward);
// }
// while (cursor.CompareTo(segment.End) >= 0)
// return TextSegment.Null;
// segmentStart = cursor;
// cursor = segment.End.CreatePointer();
// nextContext = cursor.GetPointerContext(LogicalDirection.Backward);
// while ((cursor.CompareTo(segmentStart) > 0) &&
// (nextContext != TextPointerContext.Text) &&
// (nextContext != TextPointerContext.EmbeddedElement))
// {
// cursor.MoveToNextContextPosition(LogicalDirection.Backward);
// nextContext = cursor.GetPointerContext(LogicalDirection.Backward);
// }
// return segmentStart.CompareTo(cursor) < 0 ? new TextSegment(segmentStart, cursor) : TextSegment.Null;
//}
//
#endregion Private Methods
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Private Fields
// List of text segments for this anchor
private List<TextSegment> _segments = new List<TextSegment>(1);
#endregion Private Fields
//------------------------------------------------------
//
// Private Classes
//
//------------------------------------------------------
#region Private Classes
/// <summary>
/// Simple comparer class that sorts TextSegments by their Start pointers.
/// If Start pointers are the same, then they are sorted by their End pointers.
/// Null is sorted as less than a non-null result.
/// </summary>
private class TextSegmentComparer : IComparer<TextSegment>
{
/// <summary>
/// All comparisons are done a segments Start pointer. If
/// those are the same, then the End pointers are compared.
/// Returns 0 if x is == to y; -1 if x is less than y; 1 if x is greater than y.
/// If x is null and y is not, returns -1; if y is null and x is not, returns 1.
/// </summary>
public int Compare(TextSegment x, TextSegment y)
{
if (x.Equals(TextSegment.Null))
{
// Both are null
if (y.Equals(TextSegment.Null))
return 0;
// x is null but y is not
else
return -1;
}
else
{
// x is not null but y is
if (y.Equals(TextSegment.Null))
return 1;
else
{
int retVal = x.Start.CompareTo(y.Start);
// If starts are different, return their comparison
if (retVal != 0)
return retVal;
// Otherwise return the comparison of the ends
else
return x.End.CompareTo(y.End);
}
}
}
}
#endregion Private Classes
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Apache.Geode.Client;
using System.Collections;
namespace PdxTests
{
[Serializable]
public class PdxTypes1 : IPdxSerializable
{
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes1()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes1();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes1 pap = obj as PdxTypes1;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4)
return true;
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_i1 = reader.ReadInt("i1");
m_i2 = reader.ReadInt("i2");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("i1", m_i1);
writer.WriteInt("i2", m_i2);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
}
#endregion
}
[Serializable]
public class PdxTypes2 : IPdxSerializable
{
string m_s1 = "one";
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes2()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes2();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes2 pap = obj as PdxTypes2;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1)
return true;
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_s1 = reader.ReadString("s1");
m_i1 = reader.ReadInt("i1");
m_i2 = reader.ReadInt("i2");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
}
public void ToData(IPdxWriter writer)
{
writer.WriteString("s1", m_s1);
writer.WriteInt("i1", m_i1);
writer.WriteInt("i2", m_i2);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
}
#endregion
}
[Serializable]
public class PdxTypes3 : IPdxSerializable
{
string m_s1 = "one";
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes3()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes3();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes3 pap = obj as PdxTypes3;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1)
return true;
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_i1 = reader.ReadInt("i1");
m_i2 = reader.ReadInt("i2");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
m_s1 = reader.ReadString("s1");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("i1", m_i1);
writer.WriteInt("i2", m_i2);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
writer.WriteString("s1", m_s1);
}
#endregion
}
[Serializable]
public class PdxTypes4 : IPdxSerializable
{
string m_s1 = "one";
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes4()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes4();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes4 pap = obj as PdxTypes4;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1)
return true;
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_i1 = reader.ReadInt("i1");
m_i2 = reader.ReadInt("i2");
m_s1 = reader.ReadString("s1");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("i1", m_i1);
writer.WriteInt("i2", m_i2);
writer.WriteString("s1", m_s1);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
}
#endregion
}
[Serializable]
public class PdxTypes5 : IPdxSerializable
{
string m_s1 = "one";
string m_s2 = "two";
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes5()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes5();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes5 pap = obj as PdxTypes5;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1
&& m_s2 == pap.m_s2)
return true;
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_s1 = reader.ReadString("s1");
m_s2 = reader.ReadString("s2");
m_i1 = reader.ReadInt("i1");
m_i2 = reader.ReadInt("i2");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
}
public void ToData(IPdxWriter writer)
{
writer.WriteString("s1", m_s1);
writer.WriteString("s2", m_s2);
writer.WriteInt("i1", m_i1);
writer.WriteInt("i2", m_i2);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
}
#endregion
}
[Serializable]
public class PdxTypes6 : IPdxSerializable
{
string m_s1 = "one";
string m_s2 = "two";
byte[] bytes128 = new byte[128];
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes6()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes6();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes6 pap = obj as PdxTypes6;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1
&& m_s2 == pap.m_s2)
{
if(bytes128.Length == pap.bytes128.Length)
return true;
}
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_s1 = reader.ReadString("s1");
m_i1 = reader.ReadInt("i1");
bytes128 = reader.ReadByteArray("bytes128");
m_i2 = reader.ReadInt("i2");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
m_s2 = reader.ReadString("s2");
}
public void ToData(IPdxWriter writer)
{
writer.WriteString("s1", m_s1);
writer.WriteInt("i1", m_i1);
writer.WriteByteArray("bytes128", bytes128);
writer.WriteInt("i2", m_i2);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
writer.WriteString("s2", m_s2);
}
#endregion
}
[Serializable]
public class PdxTypes7 : IPdxSerializable
{
string m_s1 = "one";
string m_s2 = "two";
int m_i1 = 34324;
byte[] bytes38000 = new byte[38000];
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes7()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes7();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes7 pap = obj as PdxTypes7;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1
&& m_s2 == pap.m_s2)
{
if(bytes38000.Length == pap.bytes38000.Length)
return true;
}
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_i1 = reader.ReadInt("i1");
m_i2 = reader.ReadInt("i2");
m_s1 = reader.ReadString("s1");
bytes38000 = reader.ReadByteArray("bytes38000");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
m_s2 = reader.ReadString("s2");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("i1", m_i1);
writer.WriteInt("i2", m_i2);
writer.WriteString("s1", m_s1);
writer.WriteByteArray("bytes38000", bytes38000);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
writer.WriteString("s2", m_s2);
}
#endregion
}
[Serializable]
public class PdxTypes8 : IPdxSerializable
{
string m_s1 = "one";
string m_s2 = "two";
int m_i1 = 34324;
byte[] bytes300 = new byte[300];
pdxEnumTest _enum = pdxEnumTest.pdx2;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public PdxTypes8()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes8();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes8 pap = obj as PdxTypes8;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1
&& m_s2 == pap.m_s2
&& _enum == pap._enum)
{
if(bytes300.Length == pap.bytes300.Length)
return true;
}
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_i1 = reader.ReadInt("i1");
m_i2 = reader.ReadInt("i2");
m_s1 = reader.ReadString("s1");
bytes300 = reader.ReadByteArray("bytes300");
_enum = (pdxEnumTest)reader.ReadObject("_enum");
m_s2 = reader.ReadString("s2");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("i1", m_i1);
writer.WriteInt("i2", m_i2);
writer.WriteString("s1", m_s1);
writer.WriteByteArray("bytes300", bytes300);
writer.WriteObject("_enum", _enum);
writer.WriteString("s2", m_s2);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
}
#endregion
}
[Serializable]
public class PdxTypes9 : IPdxSerializable
{
string m_s1 = "one";
string m_s2 = "two";
string m_s3 = "three";
byte[] m_bytes66000 = new byte[66000];
string m_s4 = "four";
string m_s5 = "five";
public PdxTypes9()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new PdxTypes9();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes9 pap = obj as PdxTypes9;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_s1 == pap.m_s1
&& m_s2 == pap.m_s2
&& m_s3 == pap.m_s3
&& m_s4 == pap.m_s4
&& m_s5 == pap.m_s5)
{
if(m_bytes66000.Length == pap.m_bytes66000.Length )
return true;
}
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_s1 = reader.ReadString("s1");
m_s2 = reader.ReadString("s2");
m_bytes66000 = reader.ReadByteArray("bytes66000");
m_s3 = reader.ReadString("s3");
m_s4 = reader.ReadString("s4");
m_s5 = reader.ReadString("s5");
}
public void ToData(IPdxWriter writer)
{
writer.WriteString("s1", m_s1);
writer.WriteString("s2", m_s2);
writer.WriteByteArray("bytes66000", m_bytes66000);
writer.WriteString("s3", m_s3);
writer.WriteString("s4", m_s4);
writer.WriteString("s5", m_s5);
}
#endregion
}
[Serializable]
public class PdxTypes10 : IPdxSerializable
{
string m_s1 = "one";
string m_s2 = "two";
string m_s3 = "three";
byte[] m_bytes66000 = new byte[66000];
string m_s4 = "four";
string m_s5 = "five";
public PdxTypes10()
{
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxTypes10 pap = obj as PdxTypes10;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_s1 == pap.m_s1
&& m_s2 == pap.m_s2
&& m_s3 == pap.m_s3
&& m_s4 == pap.m_s4
&& m_s5 == pap.m_s5)
{
if (m_bytes66000.Length == pap.m_bytes66000.Length)
return true;
}
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_s1 = reader.ReadString("s1");
m_s2 = reader.ReadString("s2");
m_bytes66000 = reader.ReadByteArray("bytes66000");
m_s3 = reader.ReadString("s3");
m_s4 = reader.ReadString("s4");
m_s5 = reader.ReadString("s5");
}
public void ToData(IPdxWriter writer)
{
writer.WriteString("s1", m_s1);
writer.WriteString("s2", m_s2);
writer.WriteByteArray("bytes66000", m_bytes66000);
writer.WriteString("s3", m_s3);
writer.WriteString("s4", m_s4);
writer.WriteString("s5", m_s5);
}
#endregion
}
[Serializable]
public class NestedPdx : IPdxSerializable
{
PdxTypes1 m_pd1 = new PdxTypes1();
PdxTypes2 m_pd2 = new PdxTypes2();
string m_s1 = "one";
string m_s2 = "two";
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public NestedPdx()
{
}
public static IPdxSerializable CreateDeserializable()
{
return new NestedPdx();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
NestedPdx pap = obj as NestedPdx;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1
&& m_s2 == pap.m_s2
&& m_pd1.Equals(pap.m_pd1)
&& m_pd2.Equals(pap.m_pd2))
return true;
return false;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
m_i1 = reader.ReadInt("i1");
m_pd1 = (PdxTypes1)reader.ReadObject("pd1");
m_i2 = reader.ReadInt("i2");
m_s1 = reader.ReadString("s1");
m_s2 = reader.ReadString("s2");
m_pd2 = (PdxTypes2)reader.ReadObject("pd2");
m_i3 = reader.ReadInt("i3");
m_i4 = reader.ReadInt("i4");
}
public void ToData(IPdxWriter writer)
{
writer.WriteInt("i1", m_i1);
writer.WriteObject("pd1", m_pd1);
writer.WriteInt("i2", m_i2);
writer.WriteString("s1", m_s1);
writer.WriteString("s2", m_s2);
writer.WriteObject("pd2", m_pd2);
writer.WriteInt("i3", m_i3);
writer.WriteInt("i4", m_i4);
}
#endregion
}
[Serializable]
public class PdxInsideIGeodeSerializable : IGeodeSerializable
{
NestedPdx m_npdx = new NestedPdx();
PdxTypes3 m_pdx3 = new PdxTypes3();
string m_s1 = "one";
string m_s2 = "two";
int m_i1 = 34324;
int m_i2 = 2144;
int m_i3 = 4645734;
int m_i4 = 73567;
public static IGeodeSerializable CreateDeserializable()
{
return new PdxInsideIGeodeSerializable();
}
public override int GetHashCode()
{
return base.GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
PdxInsideIGeodeSerializable pap = obj as PdxInsideIGeodeSerializable;
if (pap == null)
return false;
//if (pap == this)
//return true;
if (m_i1 == pap.m_i1
&& m_i2 == pap.m_i2
&& m_i3 == pap.m_i3
&& m_i4 == pap.m_i4
&& m_s1 == pap.m_s1
&& m_s2 == pap.m_s2
&& m_npdx.Equals(pap.m_npdx)
&& m_pdx3.Equals(pap.m_pdx3))
return true;
return false;
}
#region IGeodeSerializable Members
public uint ClassId
{
get { return 5005; }
}
public void FromData(DataInput input)
{
m_i1 = input.ReadInt32();
m_npdx = (NestedPdx)input.ReadObject();
m_i2 = input.ReadInt32();
m_s1 = input.ReadUTF();
m_s2 = input.ReadUTF();
m_pdx3 = (PdxTypes3)input.ReadObject();
m_i3 = input.ReadInt32();
m_i4 = input.ReadInt32();
}
public uint ObjectSize
{
get { return 0; }
}
public void ToData(DataOutput output)
{
output.WriteInt32( m_i1);
output.WriteObject( m_npdx);
output.WriteInt32( m_i2);
output.WriteUTF(m_s1);
output.WriteUTF(m_s2);
output.WriteObject(m_pdx3);
output.WriteInt32(m_i3);
output.WriteInt32(m_i4);
}
#endregion
}
#region Test class for all primitives types array
public class AllPdxTypes : IPdxSerializable
{
private string _asciiNULL = null;
private string _ascii0 = "";
private string _ascii255 = new string('a', 255);
private string _ascii35000 = new string('a', 35000);
private string _ascii89000 = new string('a', 89000);
private string _utf10 = new string((char)0x2345, 10);
private string _utf255 = new string((char)0x2345, 255);
private string _utf2000 = new string((char)0x2345, 2000);
private string _utf4000 = new string((char)0x2345, 4000);
private List<object> _listNULL = null;
private List<object> _list0 = new List<object>();
private List<object> _list252 = new List<object>();
private List<object> _list253 = new List<object>();
private List<object> _list35000 = new List<object>();
private List<object> _list70000 = new List<object>();
private List<object> _oalistNULL = null;
private List<object> _oalist0 = new List<object>();
private List<object> _oalist252 = new List<object>();
private List<object> _oalist253 = new List<object>();
private List<object> _oalist35000 = new List<object>();
private List<object> _oalist70000 = new List<object>();
private ArrayList _arraylistNULL = null;
private ArrayList _arraylist0 = new ArrayList();
private ArrayList _arraylist252 = new ArrayList();
private ArrayList _arraylist253 = new ArrayList();
private ArrayList _arraylist35000 = new ArrayList();
private ArrayList _arraylist70000 = new ArrayList();
private Hashtable _hashtableNULL = null;
private Hashtable _hashtable0 = new Hashtable();
private Hashtable _hashtable252 = new Hashtable();
private Hashtable _hashtable253 = new Hashtable();
private Hashtable _hashtable35000 = new Hashtable();
private Hashtable _hashtable70000 = new Hashtable();
private Dictionary<object, object> _dictNULL = null;
private Dictionary<object, object> _dict0 = new Dictionary<object, object>();
private Dictionary<object, object> _dict252 = new Dictionary<object, object>();
private Dictionary<object, object> _dict253 = new Dictionary<object, object>();
private Dictionary<object, object> _dict35000 = new Dictionary<object, object>();
private Dictionary<object, object> _dict70000 = new Dictionary<object, object>();
private string[] _stringArrayNULL = null;
private string[] _stringArrayEmpty = new string[0];
private string[] _stringArray252 = new string[252];
private string[] _stringArray253 = new string[253];
private string[] _stringArray255 = new string[255];
private string[] _stringArray40000 = new string[40000];
private string[] _stringArray70000 = new string[70000];
private byte[] _byteArrayNULL = null;
private byte[] _byteArrayEmpty = new byte[0];
private byte[] _byteArray252 = new byte[252];
private byte[] _byteArray253 = new byte[253];
private byte[] _byteArray255 = new byte[255];
private byte[] _byteArray40000 = new byte[40000];
private byte[] _byteArray70000 = new byte[70000];
private short[] _shortArrayNULL = null;
private short[] _shortArrayEmpty = new short[0];
private short[] _shortArray252 = new short[252];
private short[] _shortArray253 = new short[253];
private short[] _shortArray255 = new short[255];
private short[] _shortArray40000 = new short[40000];
private short[] _shortArray70000 = new short[70000];
//int
private int[] _intArrayNULL = null;
private int[] _intArrayEmpty = new int[0];
private int[] _intArray252 = new int[252];
private int[] _intArray253 = new int[253];
private int[] _intArray255 = new int[255];
private int[] _intArray40000 = new int[40000];
private int[] _intArray70000 = new int[70000];
//long
private long[] _longArrayNULL = null;
private long[] _longArrayEmpty = new long[0];
private long[] _longArray252 = new long[252];
private long[] _longArray253 = new long[253];
private long[] _longArray255 = new long[255];
private long[] _longArray40000 = new long[40000];
private long[] _longArray70000 = new long[70000];
//double
private double[] _doubleArrayNULL = null;
private double[] _doubleArrayEmpty = new double[0];
private double[] _doubleArray252 = new double[252];
private double[] _doubleArray253 = new double[253];
private double[] _doubleArray255 = new double[255];
private double[] _doubleArray40000 = new double[40000];
private double[] _doubleArray70000 = new double[70000];
//float
private float[] _floatArrayNULL = null;
private float[] _floatArrayEmpty = new float[0];
private float[] _floatArray252 = new float[252];
private float[] _floatArray253 = new float[253];
private float[] _floatArray255 = new float[255];
private float[] _floatArray40000 = new float[40000];
private float[] _floatArray70000 = new float[70000];
//char
private char[] _charArrayNULL = null;
private char[] _charArrayEmpty = new char[0];
private char[] _charArray252 = new char[252];
private char[] _charArray253 = new char[253];
private char[] _charArray255 = new char[255];
private char[] _charArray40000 = new char[40000];
private char[] _charArray70000 = new char[70000];
private byte[][] _bytebytearrayNULL = null;
private byte[][] _bytebytearrayEmpty = null;
private byte[][] _bytebyteArray252 = null;
private byte[][] _bytebyteArray253 = null;
private byte[][] _bytebyteArray255 = null;
private byte[][] _bytebyteArray40000 = null;
private byte[][] _bytebyteArray70000 = null;
public AllPdxTypes() { }
public static IPdxSerializable Create() {
return new AllPdxTypes();
}
public AllPdxTypes(bool initialize)
{
if (initialize)
init();
}
private void init()
{
_list252 = new List<object>();
for (int i = 0; i < 252; i++)
_list252.Add(i);
_list253 = new List<object>();
for (int i = 0; i < 253; i++)
_list253.Add(i);
_list35000 = new List<object>();
for (int i = 0; i < 35000; i++)
_list35000.Add(i);
_list70000 = new List<object>();
for (int i = 0; i < 70000; i++)
_list70000.Add(i);
_oalist252 = new List<object>();
for (int i = 0; i < 252; i++)
_oalist252.Add(i);
_oalist253 = new List<object>();
for (int i = 0; i < 253; i++)
_oalist253.Add(i);
_oalist35000 = new List<object>();
for (int i = 0; i < 35000; i++)
_oalist35000.Add(i);
_oalist70000 = new List<object>();
for (int i = 0; i < 70000; i++)
_oalist70000.Add(i);
_arraylist252 = new ArrayList();
for (int i = 0; i < 252; i++)
_arraylist252.Add(i);
_arraylist253 = new ArrayList();
for (int i = 0; i < 253; i++)
_arraylist253.Add(i);
_arraylist35000 = new ArrayList();
for (int i = 0; i < 35000; i++)
_arraylist35000.Add(i);
_arraylist70000 = new ArrayList();
for (int i = 0; i < 70000; i++)
_arraylist70000.Add(i);
_hashtable252 = new Hashtable();
for (int i = 0; i < 252; i++)
_hashtable252.Add(i, i);
_hashtable253 = new Hashtable();
for (int i = 0; i < 253; i++)
_hashtable253.Add(i, i);
_hashtable35000 = new Hashtable();
for (int i = 0; i < 35000; i++)
_hashtable35000.Add(i, i);
_hashtable70000 = new Hashtable();
for (int i = 0; i < 70000; i++)
_hashtable70000.Add(i, i);
_dict252 = new Dictionary<object, object>();
for (int i = 0; i < 252; i++)
_dict252.Add(i, i);
_dict253 = new Dictionary<object, object>();
for (int i = 0; i < 253; i++)
_dict253.Add(i, i);
_dict35000 = new Dictionary<object, object>();
for (int i = 0; i < 35000; i++)
_dict35000.Add(i, i);
_dict70000 = new Dictionary<object, object>();
for (int i = 0; i < 70000; i++)
_dict70000.Add(i, i);
_stringArray252 = new string[252];
for (int i = 0; i < 252; i++)
{
if (i % 2 == 0)
_stringArray252[i] = new string('1', 1);
else
_stringArray252[i] = "";
}
_stringArray253 = new string[253];
for (int i = 0; i < 253; i++)
{
if (i % 2 == 0)
_stringArray253[i] = new string('1', 1);
else
_stringArray253[i] = "";
}
_stringArray255 = new string[255];
for (int i = 0; i < 255; i++)
{
if (i % 2 == 0)
_stringArray255[i] = new string('1', 1);
else
_stringArray255[i] = "";
}
_stringArray40000 = new string[40000];
for (int i = 0; i < 40000; i++)
{
if (i % 2 == 0)
_stringArray40000[i] = new string('1', 1);
else
_stringArray40000[i] = "";
}
_stringArray70000 = new string[70000];
for (int i = 0; i < 70000; i++)
{
if (i % 2 == 0)
_stringArray70000[i] = new string('1', 1);
else
_stringArray70000[i] = "";
}
_bytebytearrayEmpty = new byte[0][];
_bytebyteArray252 = new byte[252][];
_bytebyteArray253 = new byte[253][];
_bytebyteArray255 = new byte[255][];
_bytebyteArray40000 = new byte[40000][];
_bytebyteArray70000 = new byte[70000][];
}
public override bool Equals(object obj)
{
AllPdxTypes other = obj as AllPdxTypes;
if (other == null)
return false;
if (_asciiNULL != null || _asciiNULL != other._asciiNULL) return false;
if (_ascii0 != "" || !_ascii0.Equals(other._ascii0)) return false;
if (_ascii255.Length != 255 || !_ascii255.Equals(other._ascii255)) return false;
if (_ascii35000.Length != 35000 || !_ascii35000.Equals(other._ascii35000)) return false;
if (_ascii89000.Length != 89000 || !_ascii89000.Equals(other._ascii89000)) return false;
if (!_utf10.Equals(other._utf10)) return false;
if (!_utf255.Equals(other._utf255)) return false;
if (!_utf2000.Equals(other._utf2000)) return false;
if (!_utf4000.Equals(other._utf4000)) return false;
if (_listNULL != null || _listNULL != other._listNULL) return false;
if (_list0.Count != 0 || _list0.Count != other._list0.Count) return false;
//_list252
if (_list252.Count != 252 || _list252.Count != other._list252.Count) return false;
//_list253
if (_list253.Count != 253 || _list253.Count != other._list253.Count) return false;
//_list35000
if (_list35000.Count != 35000 || _list35000.Count != other._list35000.Count) return false;
//_list70000
if (_list70000.Count != 70000 || _list70000.Count != other._list70000.Count) return false;
//_oalistNULL
if (_oalistNULL != null || _oalistNULL != other._oalistNULL) return false;
//_oalist0
if (_oalist0.Count != 0 || _oalist0.Count != other._oalist0.Count) return false;
//_oalist252
if (_oalist252.Count != 252 || _oalist252.Count != other._oalist252.Count) return false;
//_oalist253
if (_oalist253.Count != 253 || _oalist253.Count != other._oalist253.Count) return false;
//_oalist35000
if (_oalist35000.Count != 35000 || _oalist35000.Count != other._oalist35000.Count) return false;
//_oalist70000
if (_oalist70000.Count != 70000 || _oalist70000.Count != other._oalist70000.Count) return false;
// _arraylistNULL
if (_arraylistNULL != null || _arraylistNULL != other._arraylistNULL) return false;
//_arraylist0
if (_arraylist0.Count != 0 || _arraylist0.Count != other._arraylist0.Count) return false;
//_arraylist252
if (_arraylist252.Count != 252 || _arraylist252.Count != other._arraylist252.Count) return false;
//_arraylist253
if (_arraylist253.Count != 253 || _arraylist253.Count != other._arraylist253.Count) return false;
//_arraylist35000
if (_arraylist35000.Count != 35000 || _arraylist35000.Count != other._arraylist35000.Count) return false;
//_arraylist70000
if (_arraylist70000.Count != 70000 || _arraylist70000.Count != other._arraylist70000.Count) return false;
//_hashtableNULL
if (_hashtableNULL != null || _hashtableNULL != other._hashtableNULL) return false;
//_hashtable0
if (_hashtable0.Count != 0 || _hashtable0.Count != other._hashtable0.Count) return false;
//_hashtable252
if (_hashtable252.Count != 252 || _hashtable252.Count != other._hashtable252.Count) return false;
//_hashtable253
if (_hashtable253.Count != 253 || _hashtable253.Count != other._hashtable253.Count) return false;
//_hashtable35000
if (_hashtable35000.Count != 35000 || _hashtable35000.Count != other._hashtable35000.Count) return false;
//_hashtable70000
if (_hashtable70000.Count != 70000 || _hashtable70000.Count != other._hashtable70000.Count) return false;
//_dictNULL
if (_dictNULL != null || _dictNULL != other._dictNULL) return false;
//_dict0
if (_dict0.Count != 0 || _dict0.Count != other._dict0.Count) return false;
//_dict252
if (_dict252.Count != 252 || _dict252.Count != other._dict252.Count) return false;
//_dict253
if (_dict253.Count != 253 || _dict253.Count != other._dict253.Count) return false;
//_dict35000
if (_dict35000.Count != 35000 || _dict35000.Count != other._dict35000.Count) return false;
//_dict70000
if (_dict70000.Count != 70000 || _dict70000.Count != other._dict70000.Count) return false;
//_stringArrayNULL
if (_stringArrayNULL != null || _stringArrayNULL != other._stringArrayNULL) return false;
//_stringArrayEmpty
if (_stringArrayEmpty.Length != 0 || _stringArrayEmpty.Length != other._stringArrayEmpty.Length) return false;
//_stringArray252
if (_stringArray252.Length != 252 || _stringArray252.Length != other._stringArray252.Length) return false;
//_stringArray253
if (_stringArray253.Length != 253 || _stringArray253.Length != other._stringArray253.Length) return false;
//_stringArray255
if (_stringArray255.Length != 255 || _stringArray255.Length != other._stringArray255.Length) return false;
//_stringArray40000
if (_stringArray40000.Length != 40000 || _stringArray40000.Length != other._stringArray40000.Length) return false;
//_stringArray70000
if (_stringArray70000.Length != 70000 || _stringArray70000.Length != other._stringArray70000.Length) return false;
//_byteArrayNULL
if (_byteArrayNULL != null && _byteArrayNULL != other._byteArrayNULL) return false;
//_byteArrayEmpty
if (_byteArrayEmpty.Length != 0 || _byteArrayEmpty.Length != other._byteArrayEmpty.Length) return false;
//_byteArray252
if (_byteArray252.Length != 252 || _byteArray252.Length != other._byteArray252.Length) return false;
//_byteArray253
if (_byteArray253.Length != 253 || _byteArray253.Length != other._byteArray253.Length) return false;
//_byteArray255
if (_byteArray255.Length != 255 || _byteArray255.Length != other._byteArray255.Length) return false;
//_byteArray40000
if (_byteArray40000.Length != 40000 || _byteArray40000.Length != other._byteArray40000.Length) return false;
//_byteArray70000
if (_byteArray70000.Length != 70000 || _byteArray70000.Length != other._byteArray70000.Length) return false;
//_shortArrayNULL
if (_shortArrayNULL != null || _shortArrayNULL != other._shortArrayNULL) return false;
//_shortArrayEmpty
if (_shortArrayEmpty.Length != 0 || _shortArrayEmpty.Length != other._shortArrayEmpty.Length) return false;
//_shortArray252
if (_shortArray252.Length != 252 || _shortArray252.Length != other._shortArray252.Length) return false;
//_shortArray253
if (_shortArray253.Length != 253 || _shortArray253.Length != other._shortArray253.Length) return false;
//_shortArray255
if (_shortArray255.Length != 255 || _shortArray255.Length != other._shortArray255.Length) return false;
//_shortArray40000
if (_shortArray40000.Length != 40000 || _shortArray40000.Length != other._shortArray40000.Length) return false;
//_shortArray70000
if (_shortArray70000.Length != 70000 || _shortArray70000.Length != other._shortArray70000.Length) return false;
//int
//_intArrayNULL
if (_intArrayNULL != null || _intArrayNULL != other._intArrayNULL) return false;
//_intArrayEmpty
if (_intArrayEmpty.Length != 0 || _intArrayEmpty.Length != other._intArrayEmpty.Length) return false;
//_intArray252
if (_intArray252.Length != 252 || _intArray252.Length != other._intArray252.Length) return false;
//_intArray253
if (_intArray253.Length != 253 || _intArray253.Length != other._intArray253.Length) return false;
//_intArray255
if (_intArray255.Length != 255 || _intArray255.Length != other._intArray255.Length) return false;
//_intArray40000
if (_intArray40000.Length != 40000 || _intArray40000.Length != other._intArray40000.Length) return false;
//_intArray70000
if (_intArray70000.Length != 70000 || _intArray70000.Length != other._intArray70000.Length) return false;
//long
//_longArrayNULL
if (_longArrayNULL != null || _longArrayNULL != other._longArrayNULL) return false;
//_longArrayEmpty
if (_longArrayEmpty.Length != 0 || _longArrayEmpty.Length != other._longArrayEmpty.Length) return false;
//_longArray252
if (_longArray252.Length != 252 || _longArray252.Length != other._longArray252.Length) return false;
//_longArray253
if (_longArray253.Length != 253 || _longArray253.Length != other._longArray253.Length) return false;
//_longArray255
if (_longArray255.Length != 255 || _longArray255.Length != other._longArray255.Length) return false;
//_longArray40000
if (_longArray40000.Length != 40000 || _longArray40000.Length != other._longArray40000.Length) return false;
//_longArray70000
if (_longArray70000.Length != 70000 || _longArray70000.Length != other._longArray70000.Length) return false;
//double
//_doubleArrayNULL
if (_doubleArrayNULL != null || _doubleArrayNULL != other._doubleArrayNULL) return false;
//_doubleArrayEmpty
if (_doubleArrayEmpty.Length != 0 || _doubleArrayEmpty.Length != other._doubleArrayEmpty.Length) return false;
//_doubleArray252
if (_doubleArray252.Length != 252 || _doubleArray252.Length != other._doubleArray252.Length) return false;
//_doubleArray253
if (_doubleArray253.Length != 253 || _doubleArray253.Length != other._doubleArray253.Length) return false;
//_doubleArray255
if (_doubleArray255.Length != 255 || _doubleArray255.Length != other._doubleArray255.Length) return false;
//_doubleArray40000
if (_doubleArray40000.Length != 40000 || _doubleArray40000.Length != other._doubleArray40000.Length) return false;
//_doubleArray70000
if (_doubleArray70000.Length != 70000 || _doubleArray70000.Length != other._doubleArray70000.Length) return false;
//float
//_floatArrayNULL
if (_floatArrayNULL != null || _floatArrayNULL != other._floatArrayNULL) return false;
//_floatArrayEmpty
if (_floatArrayEmpty.Length != 0 || _floatArrayEmpty.Length != other._floatArrayEmpty.Length) return false;
//_floatArray252
if (_floatArray252.Length != 252 || _floatArray252.Length != other._floatArray252.Length) return false;
//_floatArray253
if (_floatArray253.Length != 253 || _floatArray253.Length != other._floatArray253.Length) return false;
//_floatArray255
if (_floatArray255.Length != 255 || _floatArray255.Length != other._floatArray255.Length) return false;
//_floatArray40000
if (_floatArray40000.Length != 40000 || _floatArray40000.Length != other._floatArray40000.Length) return false;
//_floatArray70000
if (_floatArray70000.Length != 70000 || _floatArray70000.Length != other._floatArray70000.Length) return false;
//char
//_charArrayNULL
if (_charArrayNULL != null || _charArrayNULL != other._charArrayNULL) return false;
//_charArrayEmpty
if (_charArrayEmpty.Length != 0 || _charArrayEmpty.Length != other._charArrayEmpty.Length) return false;
//_charArray252
if (_charArray252.Length != 252 || _charArray252.Length != other._charArray252.Length) return false;
//_charArray253
if (_charArray253.Length != 253 || _charArray253.Length != other._charArray253.Length) return false;
//_charArray255
if (_charArray255.Length != 255 || _charArray255.Length != other._charArray255.Length) return false;
//_charArray40000
if (_charArray40000.Length != 40000 || _charArray40000.Length != other._charArray40000.Length) return false;
//_charArray70000
if (_charArray70000.Length != 70000 || _charArray70000.Length != other._charArray70000.Length) return false;
//_bytebytearrayNULL
if (_bytebytearrayNULL != null || _bytebytearrayNULL != other._bytebytearrayNULL) return false;
//_bytebytearrayEmpty
if (_bytebytearrayEmpty.Length != 0 || _bytebytearrayEmpty.Length != other._bytebytearrayEmpty.Length) return false;
//_bytebyteArray252
if (_bytebyteArray252.Length != 252 || _bytebyteArray252.Length != other._bytebyteArray252.Length) return false;
//_bytebyteArray253
if (_bytebyteArray253.Length != 253 || _bytebyteArray253.Length != other._bytebyteArray253.Length) return false;
//_bytebyteArray255
if (_bytebyteArray255.Length != 255 || _bytebyteArray255.Length != other._bytebyteArray255.Length) return false;
//_bytebyteArray40000
if (_bytebyteArray40000.Length != 40000 || _bytebyteArray40000.Length != other._bytebyteArray40000.Length) return false;
//_bytebyteArray70000
if (_bytebyteArray70000.Length != 70000 || _bytebyteArray70000.Length != other._bytebyteArray70000.Length) return false;
return true;
}
#region IPdxSerializable Members
public void FromData(IPdxReader reader)
{
_asciiNULL = reader.ReadString("_asciiNULL");
_ascii0 = reader.ReadString("_ascii0");
_ascii255 = reader.ReadString("_ascii255");
_ascii35000 = reader.ReadString("_ascii35000");
_ascii89000 = reader.ReadString("_ascii89000");
_utf10 = reader.ReadString("_utf10");
_utf255 = reader.ReadString("_utf255");
_utf2000 = reader.ReadString("_utf2000");
_utf4000 = reader.ReadString("_utf4000");
_listNULL = (List<object>)reader.ReadObject("_listNULL");
_list0 = (List<object>)reader.ReadObject("_list0");
_list252 = (List<object>)reader.ReadObject("_list252");
_list253 = (List<object>)reader.ReadObject("_list253");
_list35000 = (List<object>)reader.ReadObject("_list35000");
_list70000 = (List<object>)reader.ReadObject("_list70000");
_oalistNULL = reader.ReadObjectArray("_oalistNULL");
_oalist0 = reader.ReadObjectArray("_oalist0");
_oalist252 = reader.ReadObjectArray("_oalist252");
_oalist253 = reader.ReadObjectArray("_oalist253");
_oalist35000 = reader.ReadObjectArray("_oalist35000");
_oalist70000 = reader.ReadObjectArray("_oalist70000");
_arraylistNULL = (ArrayList)reader.ReadObject("_arraylistNULL");
_arraylist0 = (ArrayList)reader.ReadObject("_arraylist0");
_arraylist252 = (ArrayList)reader.ReadObject("_arraylist252");
_arraylist253 = (ArrayList)reader.ReadObject("_arraylist253");
_arraylist35000 = (ArrayList)reader.ReadObject("_arraylist35000");
_arraylist70000 = (ArrayList)reader.ReadObject("_arraylist70000");
_hashtableNULL = (Hashtable)reader.ReadObject("_hashtableNULL");
_hashtable0 = (Hashtable)reader.ReadObject("_hashtable0");
_hashtable252 = (Hashtable)reader.ReadObject("_hashtable252");
_hashtable253 = (Hashtable)reader.ReadObject("_hashtable253");
_hashtable35000 = (Hashtable)reader.ReadObject("_hashtable35000");
_hashtable70000 = (Hashtable)reader.ReadObject("_hashtable70000");
_dictNULL = (Dictionary<object, object>)reader.ReadObject("_dictNULL");
_dict0 = (Dictionary<object, object>)reader.ReadObject("_dict0");
_dict252 = (Dictionary<object, object>)reader.ReadObject("_dict252");
_dict253 = (Dictionary<object, object>)reader.ReadObject("_dict253");
_dict35000 = (Dictionary<object, object>)reader.ReadObject("_dict35000");
_dict70000 = (Dictionary<object, object>)reader.ReadObject("_dict70000");
_stringArrayNULL = reader.ReadStringArray("_stringArrayNULL");
_stringArrayEmpty = reader.ReadStringArray("_stringArrayEmpty");
_stringArray252 = reader.ReadStringArray("_stringArray252");
_stringArray253 = reader.ReadStringArray("_stringArray253");
_stringArray255 = reader.ReadStringArray("_stringArray255");
_stringArray40000 = reader.ReadStringArray("_stringArray40000");
_stringArray70000 = reader.ReadStringArray("_stringArray70000");
_byteArrayNULL = reader.ReadByteArray("_byteArrayNULL");
_byteArrayEmpty = reader.ReadByteArray("_byteArrayEmpty");
_byteArray252 = reader.ReadByteArray("_byteArray252");
_byteArray253 = reader.ReadByteArray("_byteArray253");
_byteArray255 = reader.ReadByteArray("_byteArray255");
_byteArray40000 = reader.ReadByteArray("_byteArray40000");
_byteArray70000 = reader.ReadByteArray("_byteArray70000");
_shortArrayNULL = reader.ReadShortArray("_shortArrayNULL");
_shortArrayEmpty = reader.ReadShortArray("_shortArrayEmpty");
_shortArray252 = reader.ReadShortArray("_shortArray252");
_shortArray253 = reader.ReadShortArray("_shortArray253");
_shortArray255 = reader.ReadShortArray("_shortArray255");
_shortArray40000 = reader.ReadShortArray("_shortArray40000");
_shortArray70000 = reader.ReadShortArray("_shortArray70000");
//int
_intArrayNULL = reader.ReadIntArray("_intArrayNULL");
_intArrayEmpty = reader.ReadIntArray("_intArrayEmpty");
_intArray252 = reader.ReadIntArray("_intArray252");
_intArray253 = reader.ReadIntArray("_intArray253");
_intArray255 = reader.ReadIntArray("_intArray255");
_intArray40000 = reader.ReadIntArray("_intArray40000");
_intArray70000 = reader.ReadIntArray("_intArray70000");
//long
_longArrayNULL = reader.ReadLongArray("_longArrayNULL");
_longArrayEmpty = reader.ReadLongArray("_longArrayEmpty");
_longArray252 = reader.ReadLongArray("_longArray252");
_longArray253 = reader.ReadLongArray("_longArray253");
_longArray255 = reader.ReadLongArray("_longArray255");
_longArray40000 = reader.ReadLongArray("_longArray40000");
_longArray70000 = reader.ReadLongArray("_longArray70000");
//double
_doubleArrayNULL = reader.ReadDoubleArray("_doubleArrayNULL");
_doubleArrayEmpty = reader.ReadDoubleArray("_doubleArrayEmpty");
_doubleArray252 = reader.ReadDoubleArray("_doubleArray252");
_doubleArray253 = reader.ReadDoubleArray("_doubleArray253");
_doubleArray255 = reader.ReadDoubleArray("_doubleArray255");
_doubleArray40000 = reader.ReadDoubleArray("_doubleArray40000");
_doubleArray70000 = reader.ReadDoubleArray("_doubleArray70000");
//float
_floatArrayNULL = reader.ReadFloatArray("_floatArrayNULL");
_floatArrayEmpty = reader.ReadFloatArray("_floatArrayEmpty");
_floatArray252 = reader.ReadFloatArray("_floatArray252");
_floatArray253 = reader.ReadFloatArray("_floatArray253");
_floatArray255 = reader.ReadFloatArray("_floatArray255");
_floatArray40000 = reader.ReadFloatArray("_floatArray40000");
_floatArray70000 = reader.ReadFloatArray("_floatArray70000");
//char
_charArrayNULL = reader.ReadCharArray("_charArrayNULL");
_charArrayEmpty = reader.ReadCharArray("_charArrayEmpty");
_charArray252 = reader.ReadCharArray("_charArray252");
_charArray253 = reader.ReadCharArray("_charArray253");
_charArray255 = reader.ReadCharArray("_charArray255");
_charArray40000 = reader.ReadCharArray("_charArray40000");
_charArray70000 = reader.ReadCharArray("_charArray70000");
_bytebytearrayNULL = reader.ReadArrayOfByteArrays("_bytebytearrayNULL");
_bytebytearrayEmpty = reader.ReadArrayOfByteArrays("_bytebytearrayEmpty");
_bytebyteArray252 = reader.ReadArrayOfByteArrays("_bytebyteArray252");
_bytebyteArray253 = reader.ReadArrayOfByteArrays("_bytebyteArray253");
_bytebyteArray255 = reader.ReadArrayOfByteArrays("_bytebyteArray255");
_bytebyteArray40000 = reader.ReadArrayOfByteArrays("_bytebyteArray40000");
_bytebyteArray70000 = reader.ReadArrayOfByteArrays("_bytebyteArray70000");
}
public void ToData(IPdxWriter writer)
{
writer.WriteString("_asciiNULL", _asciiNULL);
writer.WriteString("_ascii0", _ascii0);
writer.WriteString("_ascii255", _ascii255);
writer.WriteString("_ascii35000", _ascii35000);
writer.WriteString("_ascii89000", _ascii89000);
writer.WriteString("_utf10", _utf10);
writer.WriteString("_utf255", _utf255);
writer.WriteString("_utf2000", _utf2000);
writer.WriteString("_utf4000", _utf4000);
writer.WriteObject("_listNULL", _listNULL);
writer.WriteObject("_list0", _list0);
writer.WriteObject("_list252", _list252);
writer.WriteObject("_list253", _list253);
writer.WriteObject("_list35000", _list35000);
writer.WriteObject("_list70000", _list70000);
writer.WriteObjectArray("_oalistNULL", _oalistNULL);
writer.WriteObjectArray("_oalist0", _oalist0);
writer.WriteObjectArray("_oalist252", _oalist252);
writer.WriteObjectArray("_oalist253", _oalist253);
writer.WriteObjectArray("_oalist35000", _oalist35000);
writer.WriteObjectArray("_oalist70000", _oalist70000);
writer.WriteObject("_arraylistNULL", _arraylistNULL);
writer.WriteObject("_arraylist0", _arraylist0);
writer.WriteObject("_arraylist252", _arraylist252);
writer.WriteObject("_arraylist253", _arraylist253);
writer.WriteObject("_arraylist35000", _arraylist35000);
writer.WriteObject("_arraylist70000", _arraylist70000);
writer.WriteObject("_hashtableNULL", _hashtableNULL);
writer.WriteObject("_hashtable0", _hashtable0);
writer.WriteObject("_hashtable252", _hashtable252);
writer.WriteObject("_hashtable253", _hashtable253);
writer.WriteObject("_hashtable35000", _hashtable35000);
writer.WriteObject("_hashtable70000", _hashtable70000);
writer.WriteObject("_dictNULL", _dictNULL);
writer.WriteObject("_dict0", _dict0);
writer.WriteObject("_dict252", _dict252);
writer.WriteObject("_dict253", _dict253);
writer.WriteObject("_dict35000", _dict35000);
writer.WriteObject("_dict70000", _dict70000);
writer.WriteStringArray("_stringArrayNULL", _stringArrayNULL);
writer.WriteStringArray("_stringArrayEmpty", _stringArrayEmpty);
writer.WriteStringArray("_stringArray252", _stringArray252);
writer.WriteStringArray("_stringArray253", _stringArray253);
writer.WriteStringArray("_stringArray255", _stringArray255);
writer.WriteStringArray("_stringArray40000", _stringArray40000);
writer.WriteStringArray("_stringArray70000", _stringArray70000);
writer.WriteByteArray("_byteArrayNULL", _byteArrayNULL);
writer.WriteByteArray("_byteArrayEmpty", _byteArrayEmpty);
writer.WriteByteArray("_byteArray252", _byteArray252);
writer.WriteByteArray("_byteArray253", _byteArray253);
writer.WriteByteArray("_byteArray255", _byteArray255);
writer.WriteByteArray("_byteArray40000", _byteArray40000);
writer.WriteByteArray("_byteArray70000", _byteArray70000);
writer.WriteShortArray("_shortArrayNULL", _shortArrayNULL);
writer.WriteShortArray("_shortArrayEmpty", _shortArrayEmpty);
writer.WriteShortArray("_shortArray252", _shortArray252);
writer.WriteShortArray("_shortArray253", _shortArray253);
writer.WriteShortArray("_shortArray255", _shortArray255);
writer.WriteShortArray("_shortArray40000", _shortArray40000);
writer.WriteShortArray("_shortArray70000", _shortArray70000);
//int
writer.WriteIntArray("_intArrayNULL", _intArrayNULL);
writer.WriteIntArray("_intArrayEmpty", _intArrayEmpty);
writer.WriteIntArray("_intArray252", _intArray252);
writer.WriteIntArray("_intArray253", _intArray253);
writer.WriteIntArray("_intArray255", _intArray255);
writer.WriteIntArray("_intArray40000", _intArray40000);
writer.WriteIntArray("_intArray70000", _intArray70000);
//long
writer.WriteLongArray("_longArrayNULL", _longArrayNULL);
writer.WriteLongArray("_longArrayEmpty", _longArrayEmpty);
writer.WriteLongArray("_longArray252", _longArray252);
writer.WriteLongArray("_longArray253", _longArray253);
writer.WriteLongArray("_longArray255", _longArray255);
writer.WriteLongArray("_longArray40000", _longArray40000);
writer.WriteLongArray("_longArray70000", _longArray70000);
//double
writer.WriteDoubleArray("_doubleArrayNULL", _doubleArrayNULL);
writer.WriteDoubleArray("_doubleArrayEmpty", _doubleArrayEmpty);
writer.WriteDoubleArray("_doubleArray252", _doubleArray252);
writer.WriteDoubleArray("_doubleArray253", _doubleArray253);
writer.WriteDoubleArray("_doubleArray255", _doubleArray255);
writer.WriteDoubleArray("_doubleArray40000", _doubleArray40000);
writer.WriteDoubleArray("_doubleArray70000", _doubleArray70000);
//float
writer.WriteFloatArray("_floatArrayNULL", _floatArrayNULL);
writer.WriteFloatArray("_floatArrayEmpty", _floatArrayEmpty);
writer.WriteFloatArray("_floatArray252", _floatArray252);
writer.WriteFloatArray("_floatArray253", _floatArray253);
writer.WriteFloatArray("_floatArray255", _floatArray255);
writer.WriteFloatArray("_floatArray40000", _floatArray40000);
writer.WriteFloatArray("_floatArray70000", _floatArray70000);
//char
writer.WriteCharArray("_charArrayNULL", _charArrayNULL);
writer.WriteCharArray("_charArrayEmpty", _charArrayEmpty);
writer.WriteCharArray("_charArray252", _charArray252);
writer.WriteCharArray("_charArray253", _charArray253);
writer.WriteCharArray("_charArray255", _charArray255);
writer.WriteCharArray("_charArray40000", _charArray40000);
writer.WriteCharArray("_charArray70000", _charArray70000);
writer.WriteArrayOfByteArrays("_bytebytearrayNULL", _bytebytearrayNULL);
writer.WriteArrayOfByteArrays("_bytebytearrayEmpty", _bytebytearrayEmpty);
writer.WriteArrayOfByteArrays("_bytebyteArray252", _bytebyteArray252);
writer.WriteArrayOfByteArrays("_bytebyteArray253", _bytebyteArray253);
writer.WriteArrayOfByteArrays("_bytebyteArray255", _bytebyteArray255);
writer.WriteArrayOfByteArrays("_bytebyteArray40000", _bytebyteArray40000);
writer.WriteArrayOfByteArrays("_bytebyteArray70000", _bytebyteArray70000);
}
#endregion
}
#endregion
}
| |
//
// how to capture still images, video and audio using iOS AVFoundation and the AVCAptureSession
//
// This sample handles all of the low-level AVFoundation and capture graph setup required to capture and save media. This code also exposes the
// capture, configuration and notification capabilities in a more '.Netish' way of programming. The client code will not need to deal with threads, delegate classes
// buffer management, or objective-C data types but instead will create .NET objects and handle standard .NET events. The underlying iOS concepts and classes are detailed in
// the iOS developer online help (TP40010188-CH5-SW2).
//
// https://developer.apple.com/library/mac/#documentation/AudioVideo/Conceptual/AVFoundationPG/Articles/04_MediaCapture.html#//apple_ref/doc/uid/TP40010188-CH5-SW2
//
// Enhancements, suggestions and bug reports can be sent to steve.millar@infinitekdev.com
//
using System;
using System.IO;
using Foundation;
namespace MediaCapture
{
public class Settings
{
private enum SettingsNames
{
HaveSettingsBeenLoadedBefore,
Camera,
ImageCaptureEnabled,
AudioCaptureEnabled,
VideoCaptureEnabled,
CaptureResolution,
MaxMovieDurationInSeconds,
AutoRecordNextMovie,
SaveCapturedImagesToPhotoLibrary,
SaveCapturedImagesToMyDocuments,
}
private CameraType camera = CameraType.FrontFacing;
public CameraType Camera
{
get
{
return camera;
}
set
{
camera = value;
}
}
private Resolution captureResolution = Resolution.Medium;
public Resolution CaptureResolution
{
get
{
return captureResolution;
}
set
{
captureResolution = value;
}
}
private bool imageCaptureEnabled = true;
public bool ImageCaptureEnabled
{
get
{
return imageCaptureEnabled;
}
set
{
imageCaptureEnabled = value;
}
}
public bool AudioCaptureEnabled { get; set; }
public bool VideoCaptureEnabled { get; set; }
public bool SaveCapturedImagesToPhotoLibrary { get; set; }
public bool SaveCapturedImagesToMyDocuments { get; set; }
private int imageSaveIntervalInSeconds = 5;
public int ImageSaveIntervalInSeconds
{
get
{
return imageSaveIntervalInSeconds;
}
}
// seconds (0 or negative number means no limit)
private int maxMovieDurationInSeconds = 60;
public int MaxMovieDurationInSeconds
{
get
{
return maxMovieDurationInSeconds;
}
set
{
maxMovieDurationInSeconds = value;
}
}
// whether or not to automatically start recording a new movie once the max duration is reached and recording is forcibly stopped
private bool autoRecordNextMovie = false;
public bool AutoRecordNextMovie
{
get
{
return autoRecordNextMovie;
}
set
{
autoRecordNextMovie = value;
}
}
public void Load()
{
bool isFirstSettingsLoad = (NSUserDefaults.StandardUserDefaults.BoolForKey( SettingsNames.HaveSettingsBeenLoadedBefore.ToString() ) == false);
if ( isFirstSettingsLoad )
{
// this forces the defaults to be written and flag that this has happened for future loads
NSUserDefaults.StandardUserDefaults.SetBool( true, SettingsNames.HaveSettingsBeenLoadedBefore.ToString() );
Save ();
}
camera = NSUserDefaults.StandardUserDefaults.IntForKey( SettingsNames.Camera.ToString()) == 0 ? CameraType.FrontFacing : CameraType.RearFacing ;
ImageCaptureEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey( SettingsNames.ImageCaptureEnabled.ToString() );
AudioCaptureEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey( SettingsNames.AudioCaptureEnabled.ToString() );
VideoCaptureEnabled = NSUserDefaults.StandardUserDefaults.BoolForKey( SettingsNames.VideoCaptureEnabled.ToString() );
//CaptureResolution = (Resolution) NSUserDefaults.StandardUserDefaults.IntForKey( SettingsNames.CaptureResolution.ToString() );
CaptureResolution = Resolution.High;
//MaxMovieDurationInSeconds = NSUserDefaults.StandardUserDefaults.IntForKey( SettingsNames.MaxMovieDurationInSeconds.ToString() );
MaxMovieDurationInSeconds = 60;
AutoRecordNextMovie = NSUserDefaults.StandardUserDefaults.BoolForKey( SettingsNames.AutoRecordNextMovie.ToString() );
SaveCapturedImagesToPhotoLibrary = NSUserDefaults.StandardUserDefaults.BoolForKey( SettingsNames.SaveCapturedImagesToPhotoLibrary.ToString() );
SaveCapturedImagesToMyDocuments = NSUserDefaults.StandardUserDefaults.BoolForKey( SettingsNames.SaveCapturedImagesToMyDocuments.ToString() );
}
public void Save()
{
NSUserDefaults.StandardUserDefaults.SetInt( (int)camera, SettingsNames.Camera.ToString() );
NSUserDefaults.StandardUserDefaults.SetBool( ImageCaptureEnabled, SettingsNames.ImageCaptureEnabled.ToString() );
NSUserDefaults.StandardUserDefaults.SetBool( AudioCaptureEnabled, SettingsNames.AudioCaptureEnabled.ToString() );
NSUserDefaults.StandardUserDefaults.SetBool( VideoCaptureEnabled, SettingsNames.VideoCaptureEnabled.ToString() );
NSUserDefaults.StandardUserDefaults.SetInt( (int)CaptureResolution, SettingsNames.CaptureResolution.ToString() );
NSUserDefaults.StandardUserDefaults.SetBool( AutoRecordNextMovie, SettingsNames.AutoRecordNextMovie.ToString() );
NSUserDefaults.StandardUserDefaults.SetInt( MaxMovieDurationInSeconds, SettingsNames.MaxMovieDurationInSeconds.ToString() );
NSUserDefaults.StandardUserDefaults.SetBool( SaveCapturedImagesToPhotoLibrary, SettingsNames.SaveCapturedImagesToPhotoLibrary.ToString() );
NSUserDefaults.StandardUserDefaults.SetBool( SaveCapturedImagesToMyDocuments, SettingsNames.SaveCapturedImagesToMyDocuments.ToString() );
NSUserDefaults.StandardUserDefaults.Synchronize();
}
private static string createDirectoryIfNeeded( string directory )
{
if (Directory.Exists(directory) == false)
{
Directory.CreateDirectory( directory );
}
return directory;
}
private static string myDocuments = null;
public static string MyDocuments
{
get
{
if ( myDocuments == null )
{
myDocuments = createDirectoryIfNeeded( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) );
}
return myDocuments;
}
}
private static string configDirectory = null;
public static string ConfigDirectory
{
get
{
if ( configDirectory == null )
{
configDirectory = createDirectoryIfNeeded( Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "Config" ) );
}
return configDirectory;
}
}
private static string videoDataPath = null;
public static string VideoDataPath
{
get
{
if ( videoDataPath == null )
{
videoDataPath = createDirectoryIfNeeded( Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "VideoData" ) );
}
return videoDataPath;
}
}
private static string imageDataPath = null;
public static string ImageDataPath
{
get
{
if ( imageDataPath == null )
{
imageDataPath = createDirectoryIfNeeded( Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "ImageData" ) );
}
return imageDataPath;
}
}
}
}
| |
// <copyright file="IPlayGamesClient.cs" company="Google Inc.">
// Copyright (C) 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
#if (UNITY_ANDROID || (UNITY_IPHONE && !NO_GPGS))
namespace GooglePlayGames.BasicApi
{
using System;
using GooglePlayGames.BasicApi.Multiplayer;
using UnityEngine;
using UnityEngine.SocialPlatforms;
/// <summary>
/// Defines an abstract interface for a Play Games Client.
/// </summary>
/// <remarks>Concrete implementations
/// might be, for example, the client for Android or for iOS. One fundamental concept
/// that implementors of this class must adhere to is stable authentication state.
/// This means that once Authenticate() returns true through its callback, the user is
/// considered to be forever after authenticated while the app is running. The implementation
/// must make sure that this is the case -- for example, it must try to silently
/// re-authenticate the user if authentication is lost or wait for the authentication
/// process to get fixed if it is temporarily in a bad state (such as when the
/// Activity in Android has just been brought to the foreground and the connection to
/// the Games services hasn't yet been established). To the user of this
/// interface, once the user is authenticated, they're forever authenticated.
/// Unless, of course, there is an unusual permanent failure such as the underlying
/// service dying, in which it's acceptable that API method calls will fail.
///
/// <para>All methods can be called from the game thread. The user of this interface
/// DOES NOT NEED to call them from the UI thread of the game. Transferring to the UI
/// thread when necessary is a responsibility of the implementors of this interface.</para>
///
/// <para>CALLBACKS: all callbacks must be invoked in Unity's main thread.
/// Implementors of this interface must guarantee that (suggestion: use
/// <see cref="GooglePlayGames.OurUtils.RunOnGameThread(System.Action action)"/>).</para>
/// </remarks>
public interface IPlayGamesClient
{
/// <summary>
/// Starts the authentication process.
/// </summary>
/// <remarks>If silent == true, no UIs will be shown
/// (if UIs are needed, it will fail rather than show them). If silent == false,
/// this may show UIs, consent dialogs, etc.
/// At the end of the process, callback will be invoked to notify of the result.
/// Once the callback returns true, the user is considered to be authenticated
/// forever after.
/// </remarks>
/// <param name="callback">Callback.</param>
/// <param name="silent">If set to <c>true</c> silent.</param>
void Authenticate(System.Action<bool, string> callback, bool silent);
/// <summary>
/// Returns whether or not user is authenticated.
/// </summary>
/// <returns><c>true</c> if the user is authenticated; otherwise, <c>false</c>.</returns>
bool IsAuthenticated();
/// <summary>
/// Signs the user out.
/// </summary>
void SignOut();
/// <summary>
/// Returns the authenticated user's ID. Note that this value may change if a user signs
/// on and signs in with a different account.
/// </summary>
/// <returns>The user's ID, <code>null</code> if the user is not logged in.</returns>
string GetUserId();
/// <summary>
/// Load friends of the authenticated user.
/// </summary>
/// <param name="callback">Callback invoked when complete. bool argument
/// indicates success.</param>
void LoadFriends(Action<bool> callback);
/// <summary>
/// Returns a human readable name for the user, if they are logged in.
/// </summary>
/// <returns>The user's human-readable name. <code>null</code> if they are not logged
/// in</returns>
string GetUserDisplayName();
/// <summary>
/// Returns an id token, which can be verified server side, if they are logged in.
/// </summary>
string GetIdToken();
/// <summary>
/// The server auth code for this client.
/// </summary>
/// <remarks>
/// Note: This function is currently only implemented for Android.
/// </remarks>
string GetServerAuthCode();
/// <summary>
/// Gets another server auth code.
/// </summary>
/// <remarks>This method should be called after authenticating, and exchanging
/// the initial server auth code for a token. This is implemented by signing in
/// silently, which if successful returns almost immediately and with a new
/// server auth code.
/// </remarks>
/// <param name="reAuthenticateIfNeeded">Calls Authenticate if needed when
/// retrieving another auth code. </param>
/// <param name="callback">Callback returning the auth code, or null if there
/// was a problem. NOTE: This callback can be called immediately.</param>
void GetAnotherServerAuthCode(bool reAuthenticateIfNeeded,
Action<string> callback);
/// <summary>
/// Gets the user's email.
/// </summary>
/// <remarks>The email address returned is selected by the user from the accounts present
/// on the device. There is no guarantee this uniquely identifies the player.
/// For unique identification use the id property of the local player.
/// The user can also choose to not select any email address, meaning it is not
/// available.
/// </remarks>
/// <returns>The user email or null if not authenticated or the permission is
/// not available.</returns>
string GetUserEmail();
/// <summary>
/// Returns the user's avatar url, if they are logged in and have an avatar.
/// </summary>
/// <returns>The URL to load the avatar image. <code>null</code> if they are not logged
/// in</returns>
string GetUserImageUrl();
/// <summary>Gets the player stats.</summary>
/// <param name="callback">Callback for response.</param>
void GetPlayerStats(Action<CommonStatusCodes, PlayerStats> callback);
/// <summary>
/// Loads the users specified. This is mainly used by the leaderboard
/// APIs to get the information of a high scorer.
/// </summary>
/// <param name="userIds">User identifiers.</param>
/// <param name="callback">Callback.</param>
void LoadUsers(string[] userIds, Action<IUserProfile[]> callback);
/// <summary>
/// Returns the achievement corresponding to the passed achievement identifier.
/// </summary>
/// <returns>The achievement corresponding to the identifer. <code>null</code> if no such
/// achievement is found or if authentication has not occurred.</returns>
/// <param name="achievementId">The identifier of the achievement.</param>
Achievement GetAchievement(string achievementId);
/// <summary>
/// Loads the achievements for the current signed in user and invokes
/// the callback.
/// </summary>
void LoadAchievements(Action<Achievement[]> callback);
/// <summary>
/// Unlocks the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the callback
/// will be invoked on the game thread with <code>true</code>. If the operation fails, the
/// callback will be invoked with <code>false</code>. This operation will immediately fail if
/// the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>). If the achievement is already unlocked, this call will
/// succeed immediately.
/// </remarks>
/// <param name="achievementId">The ID of the achievement to unlock.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void UnlockAchievement(string achievementId, Action<bool> successOrFailureCalllback);
/// <summary>
/// Reveals the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the callback
/// will be invoked on the game thread with <code>true</code>. If the operation fails, the
/// callback will be invoked with <code>false</code>. This operation will immediately fail if
/// the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>). If the achievement is already in a revealed state, this call will
/// succeed immediately.
/// </remarks>
/// <param name="achievementId">The ID of the achievement to reveal.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void RevealAchievement(string achievementId, Action<bool> successOrFailureCalllback);
/// <summary>
/// Increments the achievement with the passed identifier.
/// </summary>
/// <remarks>If the operation succeeds, the
/// callback will be invoked on the game thread with <code>true</code>. If the operation fails,
/// the callback will be invoked with <code>false</code>. This operation will immediately fail
/// if the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>).
/// </remarks>
/// <param name="achievementId">The ID of the achievement to increment.</param>
/// <param name="steps">The number of steps to increment by.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void IncrementAchievement(string achievementId, int steps,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Set an achievement to have at least the given number of steps completed.
/// </summary>
/// <remarks>
/// Calling this method while the achievement already has more steps than
/// the provided value is a no-op. Once the achievement reaches the
/// maximum number of steps, the achievement is automatically unlocked,
/// and any further mutation operations are ignored.
/// </remarks>
/// <param name="achId">Ach identifier.</param>
/// <param name="steps">Steps.</param>
/// <param name="callback">Callback.</param>
void SetStepsAtLeast(string achId, int steps, Action<bool> callback);
/// <summary>
/// Shows the appropriate platform-specific achievements UI.
/// <param name="callback">The callback to invoke when complete. If null,
/// no callback is called. </param>
/// </summary>
void ShowAchievementsUI(Action<UIStatus> callback);
/// <summary>
/// Shows the leaderboard UI for a specific leaderboard.
/// </summary>
/// <remarks>If the passed ID is <code>null</code>, all leaderboards are displayed.
/// </remarks>
/// <param name="leaderboardId">The leaderboard to display. <code>null</code> to display
/// all.</param>
/// <param name="span">Timespan to display for the leaderboard</param>
/// <param name="callback">If non-null, the callback to invoke when the
/// leaderboard is dismissed.
/// </param>
void ShowLeaderboardUI(string leaderboardId,
LeaderboardTimeSpan span,
Action<UIStatus> callback);
/// <summary>
/// Loads the score data for the given leaderboard.
/// </summary>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="start">Start indicating the top scores or player centric</param>
/// <param name="rowCount">max number of scores to return. non-positive indicates
// no rows should be returned. This causes only the summary info to
/// be loaded. This can be limited
// by the SDK.</param>
/// <param name="collection">leaderboard collection: public or social</param>
/// <param name="timeSpan">leaderboard timespan</param>
/// <param name="callback">callback with the scores, and a page token.
/// The token can be used to load next/prev pages.</param>
void LoadScores(string leaderboardId, LeaderboardStart start,
int rowCount, LeaderboardCollection collection,
LeaderboardTimeSpan timeSpan,
Action<LeaderboardScoreData> callback);
/// <summary>
/// Loads the more scores for the leaderboard.
/// </summary>
/// <remarks>The token is accessed
/// by calling LoadScores() with a positive row count.
/// </remarks>
/// <param name="token">Token for tracking the score loading.</param>
/// <param name="rowCount">max number of scores to return.
/// This can be limited by the SDK.</param>
/// <param name="callback">Callback.</param>
void LoadMoreScores(ScorePageToken token, int rowCount,
Action<LeaderboardScoreData> callback);
/// <summary>
/// Returns the max number of scores returned per call.
/// </summary>
/// <returns>The max results.</returns>
int LeaderboardMaxResults();
/// <summary>
/// Submits the passed score to the passed leaderboard.
/// </summary>
/// <remarks>This operation will immediately fail
/// if the user is not authenticated (i.e. the callback will immediately be invoked with
/// <code>false</code>).
/// </remarks>
/// <param name="leaderboardId">Leaderboard identifier.</param>
/// <param name="score">Score.</param>
/// <param name="successOrFailureCalllback">Callback used to indicate whether the operation
/// succeeded or failed.</param>
void SubmitScore(string leaderboardId, long score,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Submits the score for the currently signed-in player.
/// </summary>
/// <param name="score">Score.</param>
/// <param name="board">leaderboard id.</param>
/// <param name="metadata">metadata about the score.</param>
/// <param name="callback">Callback upon completion.</param>
void SubmitScore(string leaderboardId, long score, string metadata,
Action<bool> successOrFailureCalllback);
/// <summary>
/// Returns a real-time multiplayer client.
/// </summary>
/// <seealso cref="GooglePlayGames.Multiplayer.IRealTimeMultiplayerClient"/>
/// <returns>The rtmp client.</returns>
IRealTimeMultiplayerClient GetRtmpClient();
/// <summary>
/// Returns a turn-based multiplayer client.
/// </summary>
/// <returns>The tbmp client.</returns>
ITurnBasedMultiplayerClient GetTbmpClient();
/// <summary>
/// Gets the saved game client.
/// </summary>
/// <returns>The saved game client.</returns>
SavedGame.ISavedGameClient GetSavedGameClient();
/// <summary>
/// Gets the events client.
/// </summary>
/// <returns>The events client.</returns>
Events.IEventsClient GetEventsClient();
/// <summary>
/// Gets the quests client.
/// </summary>
/// <returns>The quests client.</returns>
[Obsolete("Quests are being removed in 2018.")]
Quests.IQuestsClient GetQuestsClient();
/// <summary>
/// Gets the video client.
/// </summary>
/// <returns>The video client.</returns>
Video.IVideoClient GetVideoClient();
/// <summary>
/// Registers the invitation delegate.
/// </summary>
/// <param name="invitationDelegate">Invitation delegate.</param>
void RegisterInvitationDelegate(InvitationReceivedDelegate invitationDelegate);
IUserProfile[] GetFriends();
/// <summary>
/// Gets the Android API client. Returns null on non-Android players.
/// </summary>
/// <returns>The API client.</returns>
IntPtr GetApiClient();
/// <summary>
/// Sets the gravity for popups (Android only).
/// </summary>
/// <remarks>This can only be called after authentication. It affects
/// popups for achievements and other game services elements.</remarks>
/// <param name="gravity">Gravity for the popup.</param>
void SetGravityForPopups(Gravity gravity);
}
/// <summary>
/// Delegate that handles an incoming invitation (for both RTMP and TBMP).
/// </summary>
/// <param name="invitation">The invitation received.</param>
/// <param name="shouldAutoAccept">If this is true, then the game should immediately
/// accept the invitation and go to the game screen without prompting the user. If
/// false, you should prompt the user before accepting the invitation. As an example,
/// when a user taps on the "Accept" button on a notification in Android, it is
/// clear that they want to accept that invitation right away, so the plugin calls this
/// delegate with shouldAutoAccept = true. However, if we receive an incoming invitation
/// that the player hasn't specifically indicated they wish to accept (for example,
/// we received one in the background from the server), this delegate will be called
/// with shouldAutoAccept=false to indicate that you should confirm with the user
/// to see if they wish to accept or decline the invitation.</param>
public delegate void InvitationReceivedDelegate(Invitation invitation, bool shouldAutoAccept);
}
#endif
| |
using System;
using System.Collections.Generic;
using System.Linq;
// ReSharper disable once CheckNamespace
namespace TronBattle
{
public class Move
{
public static string Up = "UP";
public static string Down = "DOWN";
public static string Left = "LEFT";
public static string Right = "RIGHT";
}
public class Map
{
public Map()
{
MapArray = new Field[30, 20];
for (int i = 0; i < 30; i++)
{
for (int j = 0; j < 20; j++)
{
MapArray[i, j] = new Field();
}
}
}
public static Field[,] MapArray { get; set; }
}
public class Field
{
public Field()
{
OwnerId = -1;
}
public int OwnerId { get; set; }
}
public class Enemy
{
public Coords Position { get; set; }
public Coords LastPosition { get; set; }
public double Distance { get; set; }
public int PlayerId { get; set; }
}
public class Coords
{
public int X { get; set; }
public int Y { get; set; }
}
public class CanGo
{
public const int checkfld = 3;
public Coords Position = new Coords();
public bool Left(Coords pos)
{
if (pos.X > 0)
{
Position.X = pos.X - 1;
Position.Y = pos.Y;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1)
return true;
}
}
return false;
}
public bool LeftTwo(Coords pos)
{
bool canGo = true;
Position.X = pos.X;
for (int i = 0; i < checkfld; i++)
{
if (Position.X > 0)
{
Position.X = Position.X - 1;
Position.Y = pos.Y;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1 && canGo == true)
{
canGo = true;
}
else
{
canGo = false;
}
}
}
else
{
canGo = false;
}
}
return canGo;
}
public bool Right(Coords pos)
{
if (pos.X < 29)
{
Position.X = pos.X + 1;
Position.Y = pos.Y;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1)
return true;
}
}
return false;
}
public bool RightTwo(Coords pos)
{
bool canGo = true;
Position.X = pos.X;
for (int i = 0; i < checkfld; i++)
{
if (Position.X < 29)
{
Position.X = Position.X + 1;
Position.Y = pos.Y;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1 && canGo == true)
{
canGo = true;
}
else
{
canGo = false;
}
}
}
else
{
canGo = false;
}
}
return canGo;
}
public bool Up(Coords pos)
{
if (pos.Y > 0)
{
Position.X = pos.X;
Position.Y = pos.Y - 1;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1)
return true;
}
}
return false;
}
public bool UpTwo(Coords pos)
{
bool canGo = true;
Position.Y = pos.Y;
for (int i = 0; i < checkfld; i++)
{
if (Position.Y > 0)
{
Position.X = pos.X;
Position.Y = Position.Y - 1;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1 && canGo == true)
{
canGo = true;
}
else
{
canGo = false;
}
}
}
else
{
canGo = false;
}
}
return canGo;
}
public bool Down(Coords pos)
{
if (pos.Y < 19)
{
Position.X = pos.X;
Position.Y = pos.Y + 1;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1)
return true;
}
}
return false;
}
public bool DownTwo(Coords pos)
{
bool canGo = true;
Position.Y = pos.Y;
for (int i = 0; i < checkfld; i++)
{
if (Position.Y < 19)
{
Position.X = pos.X;
Position.Y = Position.Y + 1;
if (Map.MapArray[Position.X, Position.Y] != null)
{
if (Map.MapArray[Position.X, Position.Y].OwnerId == -1 && canGo == true)
{
canGo = true;
}
else
{
canGo = false;
}
}
}
else
{
canGo = false;
}
}
return canGo;
}
}
public class Game
{
public Game()
{
MyId = -1;
MyPosition = new Coords { X = -1, Y = -1 };
Targets = new List<Enemy>(3);
}
public void Init()
{
// ReSharper disable once UnusedVariable
var map = new Map();
}
public int MyId { get; set; }
public Coords MyPosition { get; set; }
public List<Enemy> Targets { get; set; }
public double GetDistance(Coords start, Coords end)
{
int y = end.Y - start.Y;
int x = end.X - start.X;
double dist = Math.Sqrt(x * x + y * y);
return dist;
}
}
static class Player
{
static void Main()
{
var game = new Game();
game.Init();
string[] inputs;
string direction = "";
// game loop
while (true)
{
// ReSharper disable once PossibleNullReferenceException
inputs = Console.ReadLine().Split(' ');
int noOfPlayers = int.Parse(inputs[0]); // total number of players (2 to 4).
game.MyId = int.Parse(inputs[1]); // your player number (0 to 3).
for (int i = 0; i < noOfPlayers; i++)
{
// ReSharper disable once PossibleNullReferenceException
inputs = Console.ReadLine().Split(' ');
int startX = int.Parse(inputs[0]); // starting X coordinate of lightcycle (or -1)
int startY = int.Parse(inputs[1]); // starting Y coordinate of lightcycle (or -1)
int tronX = int.Parse(inputs[2]); // starting X coordinate of lightcycle (can be the same as X0 if you play before this player)
int tronY = int.Parse(inputs[3]); // starting Y coordinate of lightcycle (can be the same as Y0 if you play before this player)
if (startX != -1)
{
Map.MapArray[startX, startY].OwnerId = i;
Map.MapArray[tronX, tronY].OwnerId = i;
if (i == game.MyId)
{
game.MyPosition.X = tronX;
game.MyPosition.Y = tronY;
}
else
{
if (!game.Targets.Any())
{
game.Targets.Add(new Enemy { Position = new Coords { X = tronX, Y = tronY }, PlayerId = i });
}
else
{
var target = game.Targets.FirstOrDefault(w => w.PlayerId == i);
if (target != null)
{
target.LastPosition = target.Position;
target.Position.X = tronX;
target.Position.Y = tronY;
}
}
}
}
else
{
ClearDeadBody(i);
}
}
Console.WriteLine(GetWhereToGo(direction, game));
}
// ReSharper disable once FunctionNeverReturns
}
public static string GetWhereToGo(string direction, Game game) {
foreach (var target in game.Targets)
{
target.Distance = game.GetDistance(game.MyPosition, target.Position);
}
var primTarget = game.Targets.OrderBy(o => o.Distance).FirstOrDefault(d => d.Distance < 4);
if (primTarget != null)
{
direction = GetOrientation(game.MyPosition, primTarget);
}
var compass = new CanGo();
if (compass.UpTwo(game.MyPosition) && direction == Move.Up)
{
direction = Move.Up;
}
else if (compass.RightTwo(game.MyPosition) && direction == Move.Right)
{
direction = Move.Right;
}
else if (compass.DownTwo(game.MyPosition) && direction == Move.Down)
{
direction = Move.Down;
}
else if (compass.LeftTwo(game.MyPosition) && direction == Move.Left)
{
direction = Move.Left;
}
else
{
if (compass.UpTwo(game.MyPosition))
{
direction = Move.Up;
}
else if (compass.RightTwo(game.MyPosition))
{
direction = Move.Right;
}
else if (compass.DownTwo(game.MyPosition))
{
direction = Move.Down;
}
else if (compass.LeftTwo(game.MyPosition))
{
direction = Move.Left;
}
else if (compass.Up(game.MyPosition))
{
direction = Move.Up;
}
else if (compass.Right(game.MyPosition))
{
direction = Move.Right;
}
else if (compass.Down(game.MyPosition))
{
direction = Move.Down;
}
else if (compass.Left(game.MyPosition))
{
direction = Move.Left;
}
}
return direction;
}
public static string GetOrientation(Coords my, Enemy enemy)
{
string where = "";
var enemyCords = GetNextCell(enemy.LastPosition, enemy.Position);
if (my.X < enemyCords.X)
{
where = Move.Right;
}
else if (my.X > enemyCords.X)
{
where = Move.Left;
}
else if (my.Y < enemyCords.Y)
{
where = Move.Down;
}
else if (my.Y > enemyCords.Y)
{
where = Move.Up;
}
return where;
}
public static Coords GetNextCell(Coords prevCoords, Coords currCoords)
{
Coords where = currCoords;
if (prevCoords == null)
prevCoords = currCoords;
if (prevCoords.X == currCoords.X)
{
where.X = currCoords.X;
if (prevCoords.Y < currCoords.Y)
{
where.Y = currCoords.Y + 1;
}
else
{
where.Y = currCoords.Y - 1;
}
}
else
{
where.Y = currCoords.Y;
if (prevCoords.X < currCoords.X)
{
where.X = currCoords.X + 1;
}
else
{
where.X = currCoords.X - 1;
}
}
return where;
}
public static void ClearDeadBody(int deadBodyId)
{
for (int i = 0; i < 30; i++)
{
for (int j = 0; j < 20; j++)
{
if (Map.MapArray[i, j].OwnerId == deadBodyId)
{
Map.MapArray[i, j].OwnerId = -1;
}
}
}
}
}
}
| |
// <developer>niklas@protocol7.com</developer>
// <completed>75</completed>
using System;
using System.Diagnostics;
using System.Xml;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using SharpVectors.Net;
using SharpVectors.Dom.Css;
namespace SharpVectors.Dom.Stylesheets
{
/// <summary>
/// The StyleSheet interface is the abstract base interface for any type of style sheet. It represents a single style sheet associated with a structured document. In HTML, the StyleSheet interface represents either an external style sheet, included via the HTML LINK element, or an inline STYLE element. In XML, this interface represents an external style sheet, included via a style sheet processing instruction.
/// </summary>
public class StyleSheet : IStyleSheet
{
#region Private Fields
private bool TriedDownload;
private bool SucceededDownload;
private MediaList _Media;
private string _Title;
private string _Href;
private IStyleSheet _ParentStyleSheet;
private XmlNode ownerNode;
private bool _Disabled;
private string _Type;
private string sheetContent;
#endregion
#region Constructors and Destructor
protected StyleSheet(string media)
{
_Title = String.Empty;
_Href = String.Empty;
_Type = String.Empty;
if (String.IsNullOrEmpty(media))
{
_Media = new MediaList();
}
else
{
_Media = new MediaList(media);
}
}
public StyleSheet(XmlProcessingInstruction pi)
: this(String.Empty)
{
Regex re = new Regex(@"(?<name>[a-z]+)=[""'](?<value>[^""']*)[""']");
Match match = re.Match(pi.Data);
while(match.Success)
{
string name = match.Groups["name"].Value;
string val = match.Groups["value"].Value;
switch(name)
{
case "href":
_Href = val;
break;
case "type":
_Type = val;
break;
case "title":
_Title = val;
break;
case "media":
_Media = new MediaList(val);
break;
}
match = match.NextMatch();
}
ownerNode = pi;
}
public StyleSheet(XmlElement styleElement)
: this(String.Empty)
{
if (styleElement.HasAttribute("href"))
_Href = styleElement.Attributes["href"].Value;
if (styleElement.HasAttribute("type"))
_Type = styleElement.Attributes["type"].Value;
if (styleElement.HasAttribute("title"))
_Title = styleElement.Attributes["title"].Value;
if (styleElement.HasAttribute("media"))
_Media = new MediaList(styleElement.Attributes["media"].Value);
ownerNode = styleElement;
}
public StyleSheet(XmlNode ownerNode, string href, string type, string title, string media)
: this(media)
{
this.ownerNode = ownerNode;
_Href = href;
_Type = type;
_Title = title;
}
#endregion
#region Protected Properties
internal string SheetContent
{
get
{
if(OwnerNode is XmlElement)
{
return OwnerNode.InnerText;
}
else
{
// a PI
if(!TriedDownload)
{
LoadSheet();
}
if(SucceededDownload) return sheetContent;
else return String.Empty;
}
}
}
#endregion
#region Internal methods
/// <summary>
/// Used to find matching style rules in the cascading order
/// </summary>
/// <param name="elt">The element to find styles for</param>
/// <param name="pseudoElt">The pseudo-element to find styles for</param>
/// <param name="ml">The medialist that the document is using</param>
/// <param name="csd">A CssStyleDeclaration that holds the collected styles</param>
protected internal virtual void GetStylesForElement(XmlElement elt, string pseudoElt,
MediaList ml, CssCollectedStyleDeclaration csd)
{
}
internal XmlNode ResolveOwnerNode()
{
if (OwnerNode != null) return OwnerNode;
else
{
return ((StyleSheet)ParentStyleSheet).ResolveOwnerNode();
}
}
#endregion
#region Public Methods
#endregion
#region Protected Methods
internal void LoadSheet()
{
//WebRequest request = (WebRequest)WebRequest.Create(AbsoluteHref);
WebRequest request = new ExtendedHttpWebRequest(AbsoluteHref);
TriedDownload = true;
try
{
WebResponse response = (WebResponse)request.GetResponse();
SucceededDownload = true;
System.IO.StreamReader str = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default, true);
sheetContent = str.ReadToEnd();
str.Close();
}
catch
{
SucceededDownload = false;
sheetContent = String.Empty;
}
}
#endregion
#region IStyleSheet Members
/// <summary>
/// The intended destination media for style information. The media is often specified in the ownerNode. If no media has been specified, the MediaList will be empty. See the media attribute definition for the LINK element in HTML 4.0, and the media pseudo-attribute for the XML style sheet processing instruction . Modifying the media list may cause a change to the attribute disabled.
/// </summary>
public IMediaList Media
{
get
{
return _Media;
}
}
/// <summary>
/// The advisory title. The title is often specified in the ownerNode. See the title attribute definition for the LINK element in HTML 4.0, and the title pseudo-attribute for the XML style sheet processing instruction.
/// </summary>
public string Title
{
get
{
return _Title;
}
}
/// <summary>
/// If the style sheet is a linked style sheet, the value of its attribute is its location. For inline style sheets, the value of this attribute is null. See the href attribute definition for the LINK element in HTML 4.0, and the href pseudo-attribute for the XML style sheet processing instruction.
/// </summary>
public string Href
{
get
{
return _Href;
}
}
/// <summary>
/// The resolved absolute URL to the stylesheet
/// </summary>
public Uri AbsoluteHref
{
get
{
Uri u = null;
if (ownerNode != null)
{
if (ownerNode.BaseURI != null)
{
u = new Uri(new Uri(ownerNode.BaseURI), Href);
}
//else
//{
// u = new Uri(ApplicationContext.DocumentDirectoryUri, Href);
//}
}
if (u == null)
{
throw new InvalidDataException();
}
return u;
}
}
/// <summary>
/// For style sheet languages that support the concept of style sheet inclusion, this attribute represents the including style sheet, if one exists. If the style sheet is a top-level style sheet, or the style sheet language does not support inclusion, the value of this attribute is null.
/// </summary>
public IStyleSheet ParentStyleSheet
{
get
{
return _ParentStyleSheet;
}
set
{
_ParentStyleSheet = value;
}
}
/// <summary>
/// The node that associates this style sheet with the document. For HTML, this may be the corresponding LINK or STYLE element. For XML, it may be the linking processing instruction. For style sheets that are included by other style sheets, the value of this attribute is null.
/// </summary>
public XmlNode OwnerNode
{
get
{
return ownerNode;
}
}
/// <summary>
/// false if the style sheet is applied to the document. true if it is not. Modifying this attribute may cause a new resolution of style for the document. A stylesheet only applies if both an appropriate medium definition is present and the disabled attribute is false. So, if the media doesn't apply to the current user agent, the disabled attribute is ignored.
/// </summary>
public bool Disabled
{
get
{
return _Disabled;
}
set
{
_Disabled = value;
}
}
/// <summary>
/// This specifies the style sheet language for this style sheet. The style sheet language is specified as a content type (e.g. "text/css"). The content type is often specified in the ownerNode. Also see the type attribute definition for the LINK element in HTML 4.0, and the type pseudo-attribute for the XML style sheet processing instruction.
/// </summary>
public string Type
{
get
{
return _Type;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Orleans.GrainDirectory;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.MultiClusterNetwork;
namespace Orleans.Runtime.GrainDirectory
{
internal class LocalGrainDirectory :
MarshalByRefObject,
ILocalGrainDirectory, ISiloStatusListener
{
/// <summary>
/// list of silo members sorted by the hash value of their address
/// </summary>
private readonly List<SiloAddress> membershipRingList;
private readonly HashSet<SiloAddress> membershipCache;
private readonly AsynchAgent maintainer;
private readonly Logger log;
private readonly SiloAddress seed;
private readonly RegistrarManager registrarManager;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IMultiClusterOracle multiClusterOracle;
private readonly IInternalGrainFactory grainFactory;
private Action<SiloAddress, SiloStatus> catalogOnSiloRemoved;
// Consider: move these constants into an apropriate place
internal const int HOP_LIMIT = 3; // forward a remote request no more than two times
public static readonly TimeSpan RETRY_DELAY = TimeSpan.FromSeconds(5); // Pause 5 seconds between forwards to let the membership directory settle down
protected SiloAddress Seed { get { return seed; } }
internal Logger Logger { get { return log; } } // logger is shared with classes that manage grain directory
internal bool Running;
internal SiloAddress MyAddress { get; private set; }
internal IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> DirectoryCache { get; private set; }
internal GrainDirectoryPartition DirectoryPartition { get; private set; }
public RemoteGrainDirectory RemoteGrainDirectory { get; private set; }
public RemoteGrainDirectory CacheValidator { get; private set; }
public ClusterGrainDirectory RemoteClusterGrainDirectory { get; private set; }
private readonly TaskCompletionSource<bool> stopPreparationResolver;
public Task StopPreparationCompletion { get { return stopPreparationResolver.Task; } }
internal OrleansTaskScheduler Scheduler { get; private set; }
internal GrainDirectoryHandoffManager HandoffManager { get; private set; }
public string ClusterId { get; }
internal GlobalSingleInstanceActivationMaintainer GsiActivationMaintainer { get; private set; }
private readonly CounterStatistic localLookups;
private readonly CounterStatistic localSuccesses;
private readonly CounterStatistic fullLookups;
private readonly CounterStatistic cacheLookups;
private readonly CounterStatistic cacheSuccesses;
private readonly CounterStatistic registrationsIssued;
private readonly CounterStatistic registrationsSingleActIssued;
private readonly CounterStatistic unregistrationsIssued;
private readonly CounterStatistic unregistrationsManyIssued;
private readonly IntValueStatistic directoryPartitionCount;
internal readonly CounterStatistic RemoteLookupsSent;
internal readonly CounterStatistic RemoteLookupsReceived;
internal readonly CounterStatistic LocalDirectoryLookups;
internal readonly CounterStatistic LocalDirectorySuccesses;
internal readonly CounterStatistic CacheValidationsSent;
internal readonly CounterStatistic CacheValidationsReceived;
internal readonly CounterStatistic RegistrationsLocal;
internal readonly CounterStatistic RegistrationsRemoteSent;
internal readonly CounterStatistic RegistrationsRemoteReceived;
internal readonly CounterStatistic RegistrationsSingleActLocal;
internal readonly CounterStatistic RegistrationsSingleActRemoteSent;
internal readonly CounterStatistic RegistrationsSingleActRemoteReceived;
internal readonly CounterStatistic UnregistrationsLocal;
internal readonly CounterStatistic UnregistrationsRemoteSent;
internal readonly CounterStatistic UnregistrationsRemoteReceived;
internal readonly CounterStatistic UnregistrationsManyRemoteSent;
internal readonly CounterStatistic UnregistrationsManyRemoteReceived;
public LocalGrainDirectory(
ClusterConfiguration clusterConfig,
ILocalSiloDetails siloDetails,
OrleansTaskScheduler scheduler,
ISiloStatusOracle siloStatusOracle,
IMultiClusterOracle multiClusterOracle,
IInternalGrainFactory grainFactory,
Factory<GrainDirectoryPartition> grainDirectoryPartitionFactory,
RegistrarManager registrarManager,
ILoggerFactory loggerFactory)
{
this.log = new LoggerWrapper<LocalGrainDirectory>(loggerFactory);
var globalConfig = clusterConfig.Globals;
var clusterId = globalConfig.HasMultiClusterNetwork ? globalConfig.ClusterId : null;
MyAddress = siloDetails.SiloAddress;
Scheduler = scheduler;
this.siloStatusOracle = siloStatusOracle;
this.multiClusterOracle = multiClusterOracle;
this.grainFactory = grainFactory;
membershipRingList = new List<SiloAddress>();
membershipCache = new HashSet<SiloAddress>();
ClusterId = clusterId;
clusterConfig.OnConfigChange("Globals/Caching", () =>
{
lock (membershipCache)
{
DirectoryCache = GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCache(globalConfig);
}
});
maintainer =
GrainDirectoryCacheFactory<IReadOnlyList<Tuple<SiloAddress, ActivationId>>>.CreateGrainDirectoryCacheMaintainer(
this,
this.DirectoryCache,
activations => activations.Select(a => Tuple.Create(a.Silo, a.Activation)).ToList().AsReadOnly(),
grainFactory,
loggerFactory);
GsiActivationMaintainer = new GlobalSingleInstanceActivationMaintainer(this, this.Logger, globalConfig, grainFactory, multiClusterOracle, loggerFactory);
if (globalConfig.SeedNodes.Count > 0)
{
seed = globalConfig.SeedNodes.Contains(MyAddress.Endpoint) ? MyAddress : SiloAddress.New(globalConfig.SeedNodes[0], 0);
}
stopPreparationResolver = new TaskCompletionSource<bool>();
DirectoryPartition = grainDirectoryPartitionFactory();
HandoffManager = new GrainDirectoryHandoffManager(this, siloStatusOracle, grainFactory, grainDirectoryPartitionFactory, loggerFactory);
RemoteGrainDirectory = new RemoteGrainDirectory(this, Constants.DirectoryServiceId, loggerFactory);
CacheValidator = new RemoteGrainDirectory(this, Constants.DirectoryCacheValidatorId, loggerFactory);
RemoteClusterGrainDirectory = new ClusterGrainDirectory(this, Constants.ClusterDirectoryServiceId, clusterId, grainFactory, multiClusterOracle, loggerFactory);
// add myself to the list of members
AddServer(MyAddress);
Func<SiloAddress, string> siloAddressPrint = (SiloAddress addr) =>
String.Format("{0}/{1:X}", addr.ToLongString(), addr.GetConsistentHashCode());
localLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_ISSUED);
localSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCAL_SUCCESSES);
fullLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_FULL_ISSUED);
RemoteLookupsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_SENT);
RemoteLookupsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_REMOTE_RECEIVED);
LocalDirectoryLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_ISSUED);
LocalDirectorySuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_LOCALDIRECTORY_SUCCESSES);
cacheLookups = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_ISSUED);
cacheSuccesses = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_SUCCESSES);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_LOOKUPS_CACHE_HITRATIO, () =>
{
long delta1, delta2;
long curr1 = cacheSuccesses.GetCurrentValueAndDelta(out delta1);
long curr2 = cacheLookups.GetCurrentValueAndDelta(out delta2);
return String.Format("{0}, Delta={1}",
(curr2 != 0 ? (float)curr1 / (float)curr2 : 0)
,(delta2 !=0 ? (float)delta1 / (float)delta2 : 0));
});
CacheValidationsSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_SENT);
CacheValidationsReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_VALIDATIONS_CACHE_RECEIVED);
registrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_ISSUED);
RegistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_LOCAL);
RegistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_SENT);
RegistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_REMOTE_RECEIVED);
registrationsSingleActIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_ISSUED);
RegistrationsSingleActLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_LOCAL);
RegistrationsSingleActRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_SENT);
RegistrationsSingleActRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_REGISTRATIONS_SINGLE_ACT_REMOTE_RECEIVED);
unregistrationsIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_ISSUED);
UnregistrationsLocal = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_LOCAL);
UnregistrationsRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_SENT);
UnregistrationsRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_REMOTE_RECEIVED);
unregistrationsManyIssued = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_ISSUED);
UnregistrationsManyRemoteSent = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_SENT);
UnregistrationsManyRemoteReceived = CounterStatistic.FindOrCreate(StatisticNames.DIRECTORY_UNREGISTRATIONS_MANY_REMOTE_RECEIVED);
directoryPartitionCount = IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_PARTITION_SIZE, () => DirectoryPartition.Count);
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGDISTANCE, () => RingDistanceToSuccessor());
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_RINGPERCENTAGE, () => (((float)this.RingDistanceToSuccessor()) / ((float)(int.MaxValue * 2L))) * 100);
FloatValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_MYPORTION_AVERAGERINGPERCENTAGE, () => this.membershipRingList.Count == 0 ? 0 : ((float)100 / (float)this.membershipRingList.Count));
IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_RINGSIZE, () => this.membershipRingList.Count);
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING, () =>
{
lock (this.membershipCache)
{
return Utils.EnumerableToString(this.membershipRingList, siloAddressPrint);
}
});
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_PREDECESSORS, () => Utils.EnumerableToString(this.FindPredecessors(this.MyAddress, 1), siloAddressPrint));
StringValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_RING_SUCCESSORS, () => Utils.EnumerableToString(this.FindSuccessors(this.MyAddress, 1), siloAddressPrint));
this.registrarManager = registrarManager;
}
public void Start()
{
log.Info("Start (SeverityLevel={0})", log.SeverityLevel);
Running = true;
if (maintainer != null)
{
maintainer.Start();
}
if (GsiActivationMaintainer != null)
{
GsiActivationMaintainer.Start();
}
}
// Note that this implementation stops processing directory change requests (Register, Unregister, etc.) when the Stop event is raised.
// This means that there may be a short period during which no silo believes that it is the owner of directory information for a set of
// grains (for update purposes), which could cause application requests that require a new activation to be created to time out.
// The alternative would be to allow the silo to process requests after it has handed off its partition, in which case those changes
// would receive successful responses but would not be reflected in the eventual state of the directory.
// It's easy to change this, if we think the trade-off is better the other way.
public void Stop(bool doOnStopHandoff)
{
// This will cause remote write requests to be forwarded to the silo that will become the new owner.
// Requests might bounce back and forth for a while as membership stabilizes, but they will either be served by the
// new owner of the grain, or will wind up failing. In either case, we avoid requests succeeding at this silo after we've
// begun stopping, which could cause them to not get handed off to the new owner.
Running = false;
if (doOnStopHandoff)
{
HandoffManager.ProcessSiloStoppingEvent();
}
else
{
MarkStopPreparationCompleted();
}
if (maintainer != null)
{
maintainer.Stop();
}
DirectoryCache.Clear();
}
internal void MarkStopPreparationCompleted()
{
stopPreparationResolver.TrySetResult(true);
}
internal void MarkStopPreparationFailed(Exception ex)
{
stopPreparationResolver.TrySetException(ex);
}
/// <inheritdoc />
public void SetSiloRemovedCatalogCallback(Action<SiloAddress, SiloStatus> callback)
{
if (callback == null) throw new ArgumentNullException(nameof(callback));
lock (membershipCache)
{
this.catalogOnSiloRemoved = callback;
}
}
#region Handling membership events
protected void AddServer(SiloAddress silo)
{
lock (membershipCache)
{
if (membershipCache.Contains(silo))
{
// we have already cached this silo
return;
}
membershipCache.Add(silo);
// insert new silo in the sorted order
long hash = silo.GetConsistentHashCode();
// Find the last silo with hash smaller than the new silo, and insert the latter after (this is why we have +1 here) the former.
// Notice that FindLastIndex might return -1 if this should be the first silo in the list, but then
// 'index' will get 0, as needed.
int index = membershipRingList.FindLastIndex(siloAddr => siloAddr.GetConsistentHashCode() < hash) + 1;
membershipRingList.Insert(index, silo);
HandoffManager.ProcessSiloAddEvent(silo);
if (log.IsVerbose) log.Verbose("Silo {0} added silo {1}", MyAddress, silo);
}
}
protected void RemoveServer(SiloAddress silo, SiloStatus status)
{
lock (membershipCache)
{
if (!membershipCache.Contains(silo))
{
// we have already removed this silo
return;
}
if (this.catalogOnSiloRemoved != null)
{
try
{
// Only notify the catalog once. Order is important: call BEFORE updating membershipRingList.
this.catalogOnSiloRemoved(silo, status);
}
catch (Exception exc)
{
log.Error(ErrorCode.Directory_SiloStatusChangeNotification_Exception,
String.Format("CatalogSiloStatusListener.SiloStatusChangeNotification has thrown an exception when notified about removed silo {0}.", silo.ToStringWithHashCode()), exc);
}
}
// the call order is important
HandoffManager.ProcessSiloRemoveEvent(silo);
membershipCache.Remove(silo);
membershipRingList.Remove(silo);
AdjustLocalDirectory(silo);
AdjustLocalCache(silo);
if (log.IsVerbose) log.Verbose("Silo {0} removed silo {1}", MyAddress, silo);
}
}
/// <summary>
/// Adjust local directory following the removal of a silo by droping all activations located on the removed silo
/// </summary>
/// <param name="removedSilo"></param>
protected void AdjustLocalDirectory(SiloAddress removedSilo)
{
var activationsToRemove = (from pair in DirectoryPartition.GetItems()
from pair2 in pair.Value.Instances.Where(pair3 => pair3.Value.SiloAddress.Equals(removedSilo))
select new Tuple<GrainId, ActivationId>(pair.Key, pair2.Key)).ToList();
// drop all records of activations located on the removed silo
foreach (var activation in activationsToRemove)
{
DirectoryPartition.RemoveActivation(activation.Item1, activation.Item2);
}
}
/// Adjust local cache following the removal of a silo by droping:
/// 1) entries that point to activations located on the removed silo
/// 2) entries for grains that are now owned by this silo (me)
/// 3) entries for grains that were owned by this removed silo - we currently do NOT do that.
/// If we did 3, we need to do that BEFORE we change the membershipRingList (based on old Membership).
/// We don't do that since first cache refresh handles that.
/// Second, since Membership events are not guaranteed to be ordered, we may remove a cache entry that does not really point to a failed silo.
/// To do that properly, we need to store for each cache entry who was the directory owner that registered this activation (the original partition owner).
protected void AdjustLocalCache(SiloAddress removedSilo)
{
// remove all records of activations located on the removed silo
foreach (Tuple<GrainId, IReadOnlyList<Tuple<SiloAddress, ActivationId>>, int> tuple in DirectoryCache.KeyValues)
{
// 2) remove entries now owned by me (they should be retrieved from my directory partition)
if (MyAddress.Equals(CalculateTargetSilo(tuple.Item1)))
{
DirectoryCache.Remove(tuple.Item1);
}
// 1) remove entries that point to activations located on the removed silo
RemoveActivations(DirectoryCache, tuple.Item1, tuple.Item2, tuple.Item3, t => t.Item1.Equals(removedSilo));
}
}
internal List<SiloAddress> FindPredecessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100201, "Got request to find predecessors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index - 1; ((i + numMembers) % numMembers) != index && result.Count < count; i--)
{
result.Add(membershipRingList[(i + numMembers) % numMembers]);
}
return result;
}
}
internal List<SiloAddress> FindSuccessors(SiloAddress silo, int count)
{
lock (membershipCache)
{
int index = membershipRingList.FindIndex(elem => elem.Equals(silo));
if (index == -1)
{
log.Warn(ErrorCode.Runtime_Error_100203, "Got request to find successors of silo " + silo + ", which is not in the list of members");
return null;
}
var result = new List<SiloAddress>();
int numMembers = membershipRingList.Count;
for (int i = index + 1; i % numMembers != index && result.Count < count; i++)
{
result.Add(membershipRingList[i % numMembers]);
}
return result;
}
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
// This silo's status has changed
if (Equals(updatedSilo, MyAddress))
{
if (status == SiloStatus.Stopping || status == SiloStatus.ShuttingDown)
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(true), CacheValidator.SchedulingContext).Ignore();
}
else if (status == SiloStatus.Dead)
{
// QueueAction up the "Stop" to run on a system turn
Scheduler.QueueAction(() => Stop(false), CacheValidator.SchedulingContext).Ignore();
}
}
else // Status change for some other silo
{
if (status.IsTerminating())
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => RemoveServer(updatedSilo, status), CacheValidator.SchedulingContext).Ignore();
}
else if (status == SiloStatus.Active) // do not do anything with SiloStatus.Starting -- wait until it actually becomes active
{
// QueueAction up the "Remove" to run on a system turn
Scheduler.QueueAction(() => AddServer(updatedSilo), CacheValidator.SchedulingContext).Ignore();
}
}
}
private bool IsValidSilo(SiloAddress silo)
{
return this.siloStatusOracle.IsFunctionalDirectory(silo);
}
#endregion
/// <summary>
/// Finds the silo that owns the directory information for the given grain ID.
/// This routine will always return a non-null silo address unless the excludeThisSiloIfStopping parameter is true,
/// this is the only silo known, and this silo is stopping.
/// </summary>
/// <param name="grainId"></param>
/// <param name="excludeThisSiloIfStopping"></param>
/// <returns></returns>
public SiloAddress CalculateTargetSilo(GrainId grainId, bool excludeThisSiloIfStopping = true)
{
// give a special treatment for special grains
if (grainId.IsSystemTarget)
{
if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a system target {1}, returned {2}", MyAddress, grainId, MyAddress);
// every silo owns its system targets
return MyAddress;
}
if (Constants.SystemMembershipTableId.Equals(grainId))
{
if (Seed == null)
{
string grainName;
if (!Constants.TryGetSystemGrainName(grainId, out grainName))
grainName = "MembershipTableGrain";
var errorMsg = grainName + " cannot run without Seed node - please check your silo configuration file and make sure it specifies a SeedNode element. " +
" Alternatively, you may want to use AzureTable for LivenessType.";
throw new ArgumentException(errorMsg, "grainId = " + grainId);
}
// Directory info for the membership table grain has to be located on the primary (seed) node, for bootstrapping
if (log.IsVerbose2) log.Verbose2("Silo {0} looked for a special grain {1}, returned {2}", MyAddress, grainId, Seed);
return Seed;
}
SiloAddress siloAddress = null;
int hash = unchecked((int)grainId.GetUniformHashCode());
// excludeMySelf from being a TargetSilo if we're not running and the excludeThisSIloIfStopping flag is true. see the comment in the Stop method.
bool excludeMySelf = !Running && excludeThisSiloIfStopping;
lock (membershipCache)
{
if (membershipRingList.Count == 0)
{
// If the membership ring is empty, then we're the owner by default unless we're stopping.
return excludeThisSiloIfStopping && !Running ? null : MyAddress;
}
// need to implement a binary search, but for now simply traverse the list of silos sorted by their hashes
for (var index = membershipRingList.Count - 1; index >= 0; --index)
{
var item = membershipRingList[index];
if (IsSiloNextInTheRing(item, hash, excludeMySelf))
{
siloAddress = item;
break;
}
}
if (siloAddress == null)
{
// If not found in the traversal, last silo will do (we are on a ring).
// We checked above to make sure that the list isn't empty, so this should always be safe.
siloAddress = membershipRingList[membershipRingList.Count - 1];
// Make sure it's not us...
if (siloAddress.Equals(MyAddress) && excludeMySelf)
{
siloAddress = membershipRingList.Count > 1 ? membershipRingList[membershipRingList.Count - 2] : null;
}
}
}
if (log.IsVerbose2) log.Verbose2("Silo {0} calculated directory partition owner silo {1} for grain {2}: {3} --> {4}", MyAddress, siloAddress, grainId, hash, siloAddress.GetConsistentHashCode());
return siloAddress;
}
#region Implementation of ILocalGrainDirectory
public SiloAddress CheckIfShouldForward(GrainId grainId, int hopCount, string operationDescription)
{
SiloAddress owner = CalculateTargetSilo(grainId);
if (owner == null)
{
// We don't know about any other silos, and we're stopping, so throw
throw new InvalidOperationException("Grain directory is stopping");
}
if (owner.Equals(MyAddress))
{
// if I am the owner, perform the operation locally
return null;
}
if (hopCount >= HOP_LIMIT)
{
// we are not forwarding because there were too many hops already
throw new OrleansException(string.Format("Silo {0} is not owner of {1}, cannot forward {2} to owner {3} because hop limit is reached", MyAddress, grainId, operationDescription, owner));
}
// forward to the silo that we think is the owner
return owner;
}
public async Task<AddressAndTag> RegisterAsync(ActivationAddress address, bool singleActivation, int hopCount)
{
var counterStatistic =
singleActivation
? (hopCount > 0 ? this.RegistrationsSingleActRemoteReceived : this.registrationsSingleActIssued)
: (hopCount > 0 ? this.RegistrationsRemoteReceived : this.registrationsIssued);
counterStatistic.Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, "RegisterAsync(recheck)");
}
if (forwardAddress == null)
{
(singleActivation ? RegistrationsSingleActLocal : RegistrationsLocal).Increment();
// we are the owner
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
return registrar.IsSynchronous ? registrar.Register(address, singleActivation)
: await registrar.RegisterAsync(address, singleActivation);
}
else
{
(singleActivation ? RegistrationsSingleActRemoteSent : RegistrationsRemoteSent).Increment();
// otherwise, notify the owner
AddressAndTag result = await GetDirectoryReference(forwardAddress).RegisterAsync(address, singleActivation, hopCount + 1);
if (singleActivation)
{
// Caching optimization:
// cache the result of a successfull RegisterSingleActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
if (result.Address == null) return result;
if (!address.Equals(result.Address) || !IsValidSilo(address.Silo)) return result;
var cached = new List<Tuple<SiloAddress, ActivationId>>(1) { Tuple.Create(address.Silo, address.Activation) };
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
else
{
if (IsValidSilo(address.Silo))
{
// Caching optimization:
// cache the result of a successfull RegisterActivation call, only if it is not a duplicate activation.
// this way next local lookup will find this ActivationAddress in the cache and we will save a full lookup!
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
if (!DirectoryCache.LookUp(address.Grain, out cached))
{
cached = new List<Tuple<SiloAddress, ActivationId>>(1)
{
Tuple.Create(address.Silo, address.Activation)
};
}
else
{
var newcached = new List<Tuple<SiloAddress, ActivationId>>(cached.Count + 1);
newcached.AddRange(cached);
newcached.Add(Tuple.Create(address.Silo, address.Activation));
cached = newcached;
}
// update the cache so next local lookup will find this ActivationAddress in the cache and we will save full lookup.
DirectoryCache.AddOrUpdate(address.Grain, cached, result.VersionTag);
}
}
return result;
}
}
public Task UnregisterAfterNonexistingActivation(ActivationAddress addr, SiloAddress origin)
{
log.Verbose2("UnregisterAfterNonexistingActivation addr={0} origin={1}", addr, origin);
if (origin == null || membershipCache.Contains(origin))
{
// the request originated in this cluster, call unregister here
return UnregisterAsync(addr, UnregistrationCause.NonexistentActivation, 0);
}
else
{
// the request originated in another cluster, call unregister there
var remoteDirectory = GetDirectoryReference(origin);
return remoteDirectory.UnregisterAsync(addr, UnregistrationCause.NonexistentActivation);
}
}
public async Task UnregisterAsync(ActivationAddress address, UnregistrationCause cause, int hopCount)
{
(hopCount > 0 ? UnregistrationsRemoteReceived : unregistrationsIssued).Increment();
if (hopCount == 0)
InvalidateCacheEntry(address);
// see if the owner is somewhere else (returns null if we are owner)
var forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardaddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardaddress = this.CheckIfShouldForward(address.Grain, hopCount, "UnregisterAsync(recheck)");
}
if (forwardaddress == null)
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
registrar.Unregister(address, cause);
else
await registrar.UnregisterAsync(new List<ActivationAddress>() { address }, cause);
}
else
{
UnregistrationsRemoteSent.Increment();
// otherwise, notify the owner
await GetDirectoryReference(forwardaddress).UnregisterAsync(address, cause, hopCount + 1);
}
}
private void AddToDictionary<K,V>(ref Dictionary<K, List<V>> dictionary, K key, V value)
{
if (dictionary == null)
dictionary = new Dictionary<K,List<V>>();
List<V> list;
if (! dictionary.TryGetValue(key, out list))
dictionary[key] = list = new List<V>();
list.Add(value);
}
// helper method to avoid code duplication inside UnregisterManyAsync
private void UnregisterOrPutInForwardList(IEnumerable<ActivationAddress> addresses, UnregistrationCause cause, int hopCount,
ref Dictionary<SiloAddress, List<ActivationAddress>> forward, List<Task> tasks, string context)
{
Dictionary<IGrainRegistrar, List<ActivationAddress>> unregisterBatches = new Dictionary<IGrainRegistrar, List<ActivationAddress>>();
foreach (var address in addresses)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(address.Grain, hopCount, context);
if (forwardAddress != null)
{
AddToDictionary(ref forward, forwardAddress, address);
}
else
{
// we are the owner
UnregistrationsLocal.Increment();
var registrar = this.registrarManager.GetRegistrarForGrain(address.Grain);
if (registrar.IsSynchronous)
{
registrar.Unregister(address, cause);
}
else
{
List<ActivationAddress> list;
if (!unregisterBatches.TryGetValue(registrar, out list))
unregisterBatches.Add(registrar, list = new List<ActivationAddress>());
list.Add(address);
}
}
}
// batch-unregister for each asynchronous registrar
foreach (var kvp in unregisterBatches)
{
tasks.Add(kvp.Key.UnregisterAsync(kvp.Value, cause));
}
}
public async Task UnregisterManyAsync(List<ActivationAddress> addresses, UnregistrationCause cause, int hopCount)
{
(hopCount > 0 ? UnregistrationsManyRemoteReceived : unregistrationsManyIssued).Increment();
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist = null;
var tasks = new List<Task>();
UnregisterOrPutInForwardList(addresses, cause, hopCount, ref forwardlist, tasks, "UnregisterManyAsync");
// before forwarding to other silos, we insert a retry delay and re-check destination
if (hopCount > 0 && forwardlist != null)
{
await Task.Delay(RETRY_DELAY);
Dictionary<SiloAddress, List<ActivationAddress>> forwardlist2 = null;
UnregisterOrPutInForwardList(forwardlist.SelectMany(kvp => kvp.Value), cause, hopCount, ref forwardlist2, tasks, "UnregisterManyAsync(recheck)");
forwardlist = forwardlist2;
}
// forward the requests
if (forwardlist != null)
{
foreach (var kvp in forwardlist)
{
UnregistrationsManyRemoteSent.Increment();
tasks.Add(GetDirectoryReference(kvp.Key).UnregisterManyAsync(kvp.Value, cause, hopCount + 1));
}
}
// wait for all the requests to finish
await Task.WhenAll(tasks);
}
public bool LocalLookup(GrainId grain, out AddressesAndTag result)
{
localLookups.Increment();
SiloAddress silo = CalculateTargetSilo(grain, false);
// No need to check that silo != null since we're passing excludeThisSiloIfStopping = false
if (log.IsVerbose) log.Verbose("Silo {0} tries to lookup for {1}-->{2} ({3}-->{4})", MyAddress, grain, silo, grain.GetUniformHashCode(), silo.GetConsistentHashCode());
// check if we own the grain
if (silo.Equals(MyAddress))
{
LocalDirectoryLookups.Increment();
result = GetLocalDirectoryData(grain);
if (result.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}=null", grain);
return false;
}
if (log.IsVerbose2) log.Verbose2("LocalLookup mine {0}={1}", grain, result.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
localSuccesses.Increment();
return true;
}
// handle cache
result = new AddressesAndTag();
cacheLookups.Increment();
result.Addresses = GetLocalCacheData(grain);
if (result.Addresses == null)
{
if (log.IsVerbose2) log.Verbose2("TryFullLookup else {0}=null", grain);
return false;
}
if (log.IsVerbose2) log.Verbose2("LocalLookup cache {0}={1}", grain, result.Addresses.ToStrings());
cacheSuccesses.Increment();
localSuccesses.Increment();
return true;
}
public AddressesAndTag GetLocalDirectoryData(GrainId grain)
{
return DirectoryPartition.LookUpActivations(grain);
}
public List<ActivationAddress> GetLocalCacheData(GrainId grain)
{
IReadOnlyList<Tuple<SiloAddress, ActivationId>> cached;
return DirectoryCache.LookUp(grain, out cached) ?
cached.Select(elem => ActivationAddress.GetAddress(elem.Item1, grain, elem.Item2)).Where(addr => IsValidSilo(addr.Silo)).ToList() :
null;
}
public Task<AddressesAndTag> LookupInCluster(GrainId grainId, string clusterId)
{
if (clusterId == null)
throw new ArgumentNullException("clusterId");
if (clusterId == ClusterId)
{
return LookupAsync(grainId);
}
else
{
// find gateway
var gossipOracle = this.multiClusterOracle;
var clusterGatewayAddress = gossipOracle.GetRandomClusterGateway(clusterId);
if (clusterGatewayAddress != null)
{
// call remote grain directory
var remotedirectory = GetDirectoryReference(clusterGatewayAddress);
return remotedirectory.LookupAsync(grainId);
}
else
{
return Task.FromResult(default(AddressesAndTag));
}
}
}
public async Task<AddressesAndTag> LookupAsync(GrainId grainId, int hopCount = 0)
{
(hopCount > 0 ? RemoteLookupsReceived : fullLookups).Increment();
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "LookUpAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
LocalDirectoryLookups.Increment();
var localResult = DirectoryPartition.LookUpActivations(grainId);
if (localResult.Addresses == null)
{
// it can happen that we cannot find the grain in our partition if there were
// some recent changes in the membership
if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}=none", grainId);
localResult.Addresses = new List<ActivationAddress>();
localResult.VersionTag = GrainInfo.NO_ETAG;
return localResult;
}
if (log.IsVerbose2) log.Verbose2("FullLookup mine {0}={1}", grainId, localResult.Addresses.ToStrings());
LocalDirectorySuccesses.Increment();
return localResult;
}
else
{
// Just a optimization. Why sending a message to someone we know is not valid.
if (!IsValidSilo(forwardAddress))
{
throw new OrleansException(String.Format("Current directory at {0} is not stable to perform the lookup for grainId {1} (it maps to {2}, which is not a valid silo). Retry later.", MyAddress, grainId, forwardAddress));
}
RemoteLookupsSent.Increment();
var result = await GetDirectoryReference(forwardAddress).LookupAsync(grainId, hopCount + 1);
// update the cache
result.Addresses = result.Addresses.Where(t => IsValidSilo(t.Silo)).ToList();
if (log.IsVerbose2) log.Verbose2("FullLookup remote {0}={1}", grainId, result.Addresses.ToStrings());
var entries = result.Addresses.Select(t => Tuple.Create(t.Silo, t.Activation)).ToList();
if (entries.Count > 0)
DirectoryCache.AddOrUpdate(grainId, entries, result.VersionTag);
return result;
}
}
public async Task DeleteGrainAsync(GrainId grainId, int hopCount)
{
// see if the owner is somewhere else (returns null if we are owner)
var forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync");
// on all silos other than first, we insert a retry delay and recheck owner before forwarding
if (hopCount > 0 && forwardAddress != null)
{
await Task.Delay(RETRY_DELAY);
forwardAddress = this.CheckIfShouldForward(grainId, hopCount, "DeleteGrainAsync(recheck)");
}
if (forwardAddress == null)
{
// we are the owner
var registrar = this.registrarManager.GetRegistrarForGrain(grainId);
if (registrar.IsSynchronous)
registrar.Delete(grainId);
else
await registrar.DeleteAsync(grainId);
}
else
{
// otherwise, notify the owner
DirectoryCache.Remove(grainId);
await GetDirectoryReference(forwardAddress).DeleteGrainAsync(grainId, hopCount + 1);
}
}
public void InvalidateCacheEntry(ActivationAddress activationAddress, bool invalidateDirectoryAlso = false)
{
int version;
IReadOnlyList<Tuple<SiloAddress, ActivationId>> list;
var grainId = activationAddress.Grain;
var activationId = activationAddress.Activation;
// look up grainId activations
if (DirectoryCache.LookUp(grainId, out list, out version))
{
RemoveActivations(DirectoryCache, grainId, list, version, t => t.Item2.Equals(activationId));
}
// for multi-cluster registration, the local directory may cache remote activations
// and we need to remove them here, on the fast path, to avoid forwarding the message
// to the wrong destination again
if (invalidateDirectoryAlso && CalculateTargetSilo(grainId).Equals(MyAddress))
{
var registrar = this.registrarManager.GetRegistrarForGrain(grainId);
registrar.InvalidateCache(activationAddress);
}
}
/// <summary>
/// For testing purposes only.
/// Returns the silo that this silo thinks is the primary owner of directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public SiloAddress GetPrimaryForGrain(GrainId grain)
{
return CalculateTargetSilo(grain);
}
/// <summary>
/// For testing purposes only.
/// Returns the silos that this silo thinks hold copies of the directory information for
/// the provided grain ID.
/// </summary>
/// <param name="grain"></param>
/// <returns></returns>
public List<SiloAddress> GetSilosHoldingDirectoryInformationForGrain(GrainId grain)
{
var primary = CalculateTargetSilo(grain);
return FindPredecessors(primary, 1);
}
/// <summary>
/// For testing purposes only.
/// Returns the directory information held by the local silo for the provided grain ID.
/// The result will be null if no information is held.
/// </summary>
/// <param name="grain"></param>
/// <param name="isPrimary"></param>
/// <returns></returns>
public List<ActivationAddress> GetLocalDataForGrain(GrainId grain, out bool isPrimary)
{
var primary = CalculateTargetSilo(grain);
List<ActivationAddress> backupData = HandoffManager.GetHandedOffInfo(grain);
if (MyAddress.Equals(primary))
{
log.Assert(ErrorCode.DirectoryBothPrimaryAndBackupForGrain, backupData == null,
"Silo contains both primary and backup directory data for grain " + grain);
isPrimary = true;
return GetLocalDirectoryData(grain).Addresses;
}
isPrimary = false;
return backupData;
}
#endregion
public override string ToString()
{
var sb = new StringBuilder();
long localLookupsDelta;
long localLookupsCurrent = localLookups.GetCurrentValueAndDelta(out localLookupsDelta);
long localLookupsSucceededDelta;
long localLookupsSucceededCurrent = localSuccesses.GetCurrentValueAndDelta(out localLookupsSucceededDelta);
long fullLookupsDelta;
long fullLookupsCurrent = fullLookups.GetCurrentValueAndDelta(out fullLookupsDelta);
long directoryPartitionSize = directoryPartitionCount.GetCurrentValue();
sb.AppendLine("Local Grain Directory:");
sb.AppendFormat(" Local partition: {0} entries", directoryPartitionSize).AppendLine();
sb.AppendLine(" Since last call:");
sb.AppendFormat(" Local lookups: {0}", localLookupsDelta).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededDelta).AppendLine();
if (localLookupsDelta > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededDelta) / localLookupsDelta).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsDelta).AppendLine();
sb.AppendLine(" Since start:");
sb.AppendFormat(" Local lookups: {0}", localLookupsCurrent).AppendLine();
sb.AppendFormat(" Local found: {0}", localLookupsSucceededCurrent).AppendLine();
if (localLookupsCurrent > 0)
sb.AppendFormat(" Hit rate: {0:F1}%", (100.0 * localLookupsSucceededCurrent) / localLookupsCurrent).AppendLine();
sb.AppendFormat(" Full lookups: {0}", fullLookupsCurrent).AppendLine();
sb.Append(DirectoryCache.ToString());
return sb.ToString();
}
private long RingDistanceToSuccessor()
{
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
return distance;
}
private string RingDistanceToSuccessor_2()
{
const long ringSize = int.MaxValue * 2L;
long distance;
List<SiloAddress> successorList = FindSuccessors(MyAddress, 1);
if (successorList == null || successorList.Count == 0)
{
distance = 0;
}
else
{
SiloAddress successor = successorList.First();
distance = successor == null ? 0 : CalcRingDistance(MyAddress, successor);
}
double averageRingSpace = membershipRingList.Count == 0 ? 0 : (1.0 / (double)membershipRingList.Count);
return string.Format("RingDistance={0:X}, %Ring Space {1:0.00000}%, Average %Ring Space {2:0.00000}%",
distance, ((double)distance / (double)ringSize) * 100.0, averageRingSpace * 100.0);
}
private static long CalcRingDistance(SiloAddress silo1, SiloAddress silo2)
{
const long ringSize = int.MaxValue * 2L;
long hash1 = silo1.GetConsistentHashCode();
long hash2 = silo2.GetConsistentHashCode();
if (hash2 > hash1) return hash2 - hash1;
if (hash2 < hash1) return ringSize - (hash1 - hash2);
return 0;
}
public string RingStatusToString()
{
var sb = new StringBuilder();
sb.AppendFormat("Silo address is {0}, silo consistent hash is {1:X}.", MyAddress, MyAddress.GetConsistentHashCode()).AppendLine();
sb.AppendLine("Ring is:");
lock (membershipCache)
{
foreach (var silo in membershipRingList)
sb.AppendFormat(" Silo {0}, consistent hash is {1:X}", silo, silo.GetConsistentHashCode()).AppendLine();
}
sb.AppendFormat("My predecessors: {0}", FindPredecessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- ")).AppendLine();
sb.AppendFormat("My successors: {0}", FindSuccessors(MyAddress, 1).ToStrings(addr => String.Format("{0}/{1:X}---", addr, addr.GetConsistentHashCode()), " -- "));
return sb.ToString();
}
internal IRemoteGrainDirectory GetDirectoryReference(SiloAddress silo)
{
return this.grainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo);
}
private bool IsSiloNextInTheRing(SiloAddress siloAddr, int hash, bool excludeMySelf)
{
return siloAddr.GetConsistentHashCode() <= hash && (!excludeMySelf || !siloAddr.Equals(MyAddress));
}
private static void RemoveActivations(IGrainDirectoryCache<IReadOnlyList<Tuple<SiloAddress, ActivationId>>> directoryCache, GrainId key, IReadOnlyList<Tuple<SiloAddress, ActivationId>> activations, int version, Func<Tuple<SiloAddress, ActivationId>, bool> doRemove)
{
int removeCount = activations.Count(doRemove);
if (removeCount == 0)
{
return; // nothing to remove, done here
}
if (activations.Count > removeCount) // still some left, update activation list. Note: Most of the time there should be only one activation
{
var newList = new List<Tuple<SiloAddress, ActivationId>>(activations.Count - removeCount);
newList.AddRange(activations.Where(t => !doRemove(t)));
directoryCache.AddOrUpdate(key, newList, version);
}
else // no activations left, remove from cache
{
directoryCache.Remove(key);
}
}
public bool IsSiloInCluster(SiloAddress silo)
{
lock (membershipCache)
{
return membershipCache.Contains(silo);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using Orleans.Serialization;
namespace Orleans.Runtime
{
internal class IncomingMessageBuffer
{
private const int Kb = 1024;
private const int DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE = 1024 * Kb; // 1mg
private const int GROW_MAX_BLOCK_SIZE = 1024 * Kb; // 1mg
private static readonly ArraySegment<byte>[] EmptyBuffers = {new ArraySegment<byte>(new byte[0]), };
private readonly List<ArraySegment<byte>> readBuffer;
private readonly int maxSustainedBufferSize;
private int currentBufferSize;
private readonly byte[] lengthBuffer;
private int headerLength;
private int bodyLength;
private int receiveOffset;
private int decodeOffset;
private readonly bool supportForwarding;
private Logger Log;
private readonly SerializationManager serializationManager;
private readonly DeserializationContext deserializationContext;
internal const int DEFAULT_RECEIVE_BUFFER_SIZE = 128 * Kb; // 128k
public IncomingMessageBuffer(
Logger logger,
SerializationManager serializationManager,
bool supportForwarding = false,
int receiveBufferSize = DEFAULT_RECEIVE_BUFFER_SIZE,
int maxSustainedReceiveBufferSize = DEFAULT_MAX_SUSTAINED_RECEIVE_BUFFER_SIZE)
{
Log = logger;
this.serializationManager = serializationManager;
this.supportForwarding = supportForwarding;
currentBufferSize = receiveBufferSize;
maxSustainedBufferSize = maxSustainedReceiveBufferSize;
lengthBuffer = new byte[Message.LENGTH_HEADER_SIZE];
readBuffer = BufferPool.GlobalPool.GetMultiBuffer(currentBufferSize);
receiveOffset = 0;
decodeOffset = 0;
headerLength = 0;
bodyLength = 0;
deserializationContext = new DeserializationContext(this.serializationManager)
{
StreamReader = new BinaryTokenStreamReader(EmptyBuffers)
};
}
public List<ArraySegment<byte>> BuildReceiveBuffer()
{
// Opportunistic reset to start of buffer
if (decodeOffset == receiveOffset)
{
decodeOffset = 0;
receiveOffset = 0;
}
return ByteArrayBuilder.BuildSegmentList(readBuffer, receiveOffset);
}
// Copies receive buffer into read buffer for futher processing
public void UpdateReceivedData(byte[] receiveBuffer, int bytesRead)
{
var newReceiveOffset = receiveOffset + bytesRead;
while (newReceiveOffset > currentBufferSize)
{
GrowBuffer();
}
int receiveBufferOffset = 0;
var lengthSoFar = 0;
foreach (var segment in readBuffer)
{
var bytesStillToSkip = receiveOffset - lengthSoFar;
lengthSoFar += segment.Count;
if (segment.Count <= bytesStillToSkip)
{
continue;
}
if(bytesStillToSkip > 0) // This is the first buffer
{
var bytesToCopy = Math.Min(segment.Count - bytesStillToSkip, bytesRead - receiveBufferOffset);
Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, bytesStillToSkip, bytesToCopy);
receiveBufferOffset += bytesToCopy;
}
else
{
var bytesToCopy = Math.Min(segment.Count, bytesRead - receiveBufferOffset);
Buffer.BlockCopy(receiveBuffer, receiveBufferOffset, segment.Array, 0, bytesToCopy);
receiveBufferOffset += Math.Min(bytesToCopy, segment.Count);
}
if (receiveBufferOffset == bytesRead)
{
break;
}
}
receiveOffset += bytesRead;
}
public void UpdateReceivedData(int bytesRead)
{
receiveOffset += bytesRead;
}
public void Reset()
{
receiveOffset = 0;
decodeOffset = 0;
headerLength = 0;
bodyLength = 0;
}
public bool TryDecodeMessage(out Message msg)
{
msg = null;
// Is there enough read into the buffer to continue (at least read the lengths?)
if (receiveOffset - decodeOffset < CalculateKnownMessageSize())
return false;
// parse lengths if needed
if (headerLength == 0 || bodyLength == 0)
{
// get length segments
List<ArraySegment<byte>> lenghts = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, decodeOffset, Message.LENGTH_HEADER_SIZE);
// copy length segment to buffer
int lengthBufferoffset = 0;
foreach (ArraySegment<byte> seg in lenghts)
{
Buffer.BlockCopy(seg.Array, seg.Offset, lengthBuffer, lengthBufferoffset, seg.Count);
lengthBufferoffset += seg.Count;
}
// read lengths
headerLength = BitConverter.ToInt32(lengthBuffer, 0);
bodyLength = BitConverter.ToInt32(lengthBuffer, 4);
}
// If message is too big for current buffer size, grow
while (decodeOffset + CalculateKnownMessageSize() > currentBufferSize)
{
GrowBuffer();
}
// Is there enough read into the buffer to read full message
if (receiveOffset - decodeOffset < CalculateKnownMessageSize())
return false;
// decode header
int headerOffset = decodeOffset + Message.LENGTH_HEADER_SIZE;
List<ArraySegment<byte>> header = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, headerOffset, headerLength);
// decode body
int bodyOffset = headerOffset + headerLength;
List<ArraySegment<byte>> body = ByteArrayBuilder.BuildSegmentListWithLengthLimit(readBuffer, bodyOffset, bodyLength);
// build message
this.deserializationContext.Reset();
this.deserializationContext.StreamReader.Reset(header);
msg = new Message
{
Headers = SerializationManager.DeserializeMessageHeaders(this.deserializationContext)
};
try
{
if (this.supportForwarding)
{
// If forwarding is supported, then deserialization will be deferred until the body value is needed.
// Need to maintain ownership of buffer, so we need to duplicate the body buffer.
msg.SetBodyBytes(this.DuplicateBuffer(body));
}
else
{
// Attempt to deserialize the body immediately.
msg.DeserializeBodyObject(this.serializationManager, body);
}
}
finally
{
MessagingStatisticsGroup.OnMessageReceive(msg, headerLength, bodyLength);
if (headerLength + bodyLength > this.serializationManager.LargeObjectSizeThreshold)
{
Log.Info(
ErrorCode.Messaging_LargeMsg_Incoming,
"Receiving large message Size={0} HeaderLength={1} BodyLength={2}. Msg={3}",
headerLength + bodyLength,
headerLength,
bodyLength,
msg.ToString());
if (Log.IsVerbose3) Log.Verbose3("Received large message {0}", msg.ToLongString());
}
// update parse receiveOffset and clear lengths
decodeOffset = bodyOffset + bodyLength;
headerLength = 0;
bodyLength = 0;
AdjustBuffer();
}
return true;
}
/// <summary>
/// This call cleans up the buffer state to make it optimal for next read.
/// The leading chunks, used by any processed messages, are removed from the front
/// of the buffer and added to the back. Decode and receiver offsets are adjusted accordingly.
/// If the buffer was grown over the max sustained buffer size (to read a large message) it is shrunken.
/// </summary>
private void AdjustBuffer()
{
// drop buffers consumed by messages and adjust offsets
// TODO: This can be optimized further. Linked lists?
int consumedBytes = 0;
while (readBuffer.Count != 0)
{
ArraySegment<byte> seg = readBuffer[0];
if (seg.Count <= decodeOffset - consumedBytes)
{
consumedBytes += seg.Count;
readBuffer.Remove(seg);
BufferPool.GlobalPool.Release(seg.Array);
}
else
{
break;
}
}
decodeOffset -= consumedBytes;
receiveOffset -= consumedBytes;
// backfill any consumed buffers, to preserve buffer size.
if (consumedBytes != 0)
{
int backfillBytes = consumedBytes;
// If buffer is larger than max sustained size, backfill only up to max sustained buffer size.
if (currentBufferSize > maxSustainedBufferSize)
{
backfillBytes = Math.Max(consumedBytes + maxSustainedBufferSize - currentBufferSize, 0);
currentBufferSize -= consumedBytes;
currentBufferSize += backfillBytes;
}
if (backfillBytes > 0)
{
readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(backfillBytes));
}
}
}
private int CalculateKnownMessageSize()
{
return headerLength + bodyLength + Message.LENGTH_HEADER_SIZE;
}
private List<ArraySegment<byte>> DuplicateBuffer(List<ArraySegment<byte>> body)
{
var dupBody = new List<ArraySegment<byte>>(body.Count);
foreach (ArraySegment<byte> seg in body)
{
var dupSeg = new ArraySegment<byte>(BufferPool.GlobalPool.GetBuffer(), seg.Offset, seg.Count);
Buffer.BlockCopy(seg.Array, seg.Offset, dupSeg.Array, dupSeg.Offset, seg.Count);
dupBody.Add(dupSeg);
}
return dupBody;
}
private void GrowBuffer()
{
//TODO: Add configurable max message size for safety
//TODO: Review networking layer and add max size checks to all dictionaries, arrays, or other variable sized containers.
// double buffer size up to max grow block size, then only grow it in those intervals
int growBlockSize = Math.Min(currentBufferSize, GROW_MAX_BLOCK_SIZE);
readBuffer.AddRange(BufferPool.GlobalPool.GetMultiBuffer(growBlockSize));
currentBufferSize += growBlockSize;
}
}
}
| |
/****************************************************************************
Copyright (c) 2010-2011 cocos2d-x.org
http://www.cocos2d-x.org
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.
****************************************************************************/
// root name of xml
using System;
using CocosSharp;
using System.IO;
#if !WINDOWS && !MACOS && !LINUX && !NETFX_CORE
using System.IO.IsolatedStorage;
#endif
#if NETFX_CORE
using Microsoft.Xna.Framework.Storage;
#endif
using System.Collections.Generic;
using System.Text;
using System.Xml;
// Note: Something to use here http://msdn.microsoft.com/en-us/library/hh582102.aspx
namespace CocosSharp
{
public class CCUserDefault
{
static CCUserDefault UserDefault = null;
static string USERDEFAULT_ROOT_NAME = "userDefaultRoot";
static string XML_FILE_NAME = "UserDefault.xml";
#if !WINDOWS && !MACOS && !LINUX && !NETFX_CORE
IsolatedStorageFile myIsolatedStorage;
#elif NETFX_CORE
StorageContainer myIsolatedStorage;
StorageDevice myDevice;
#endif
Dictionary<string, string> values = new Dictionary<string, string>();
#region Properties
public static CCUserDefault SharedUserDefault
{
get {
if (UserDefault == null)
{
UserDefault = new CCUserDefault();
}
return UserDefault;
}
}
#endregion Properties
#if NETFX_CORE
private StorageDevice CheckStorageDevice() {
if(myDevice != null) {
return(myDevice);
}
IAsyncResult result = StorageDevice.BeginShowSelector(null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
myDevice = StorageDevice.EndShowSelector(result);
if(myDevice != null) {
result =
myDevice.BeginOpenContainer("Save Your Game...", null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
myIsolatedStorage = myDevice.EndOpenContainer(result);
// Close the wait handle.
result.AsyncWaitHandle.Dispose();
}
return(myDevice);
}
#endif
#region Constructors
CCUserDefault()
{
#if NETFX_CORE
if(myIsolatedStorage == null) {
CheckStorageDevice();
}
if(myIsolatedStorage != null)
{
// only create xml file once if it doesnt exist
if ((!IsXMLFileExist()))
{
CreateXMLFile();
}
using (Stream s = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.OpenOrCreate))
{
ParseXMLFile(s);
}
}
#elif WINDOWS || MACOS || LINUX
// only create xml file once if it doesnt exist
if ((!IsXMLFileExist())) {
CreateXMLFile();
}
using (FileStream fileStream = new FileInfo(XML_FILE_NAME).OpenRead()){
ParseXMLFile(fileStream);
}
#else
myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
// only create xml file once if it doesnt exist
if ((!IsXMLFileExist())) {
CreateXMLFile();
}
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.Open, FileAccess.Read)) {
ParseXMLFile(fileStream);
}
#endif
}
#endregion Constructors
public void PurgeSharedUserDefault()
{
UserDefault = null;
}
bool ParseXMLFile(Stream xmlFile)
{
values.Clear();
string key = "";
// Create an XmlReader
using (XmlReader reader = XmlReader.Create(xmlFile)) {
// Parse the file and display each of the nodes.
while (reader.Read()) {
switch (reader.NodeType) {
case XmlNodeType.Element:
key = reader.Name;
break;
case XmlNodeType.Text:
values.Add(key, reader.Value);
break;
case XmlNodeType.XmlDeclaration:
case XmlNodeType.ProcessingInstruction:
break;
case XmlNodeType.Comment:
break;
case XmlNodeType.EndElement:
break;
}
}
}
return true;
}
string GetValueForKey(string key)
{
string value = null;
if (! values.TryGetValue(key, out value)) {
value = null;
}
return value;
}
void SetValueForKey(string key, string value)
{
values[key] = value;
}
public bool GetBoolForKey(string key, bool defaultValue=false)
{
string value = GetValueForKey(key);
bool ret = defaultValue;
if (value != null)
{
ret = bool.Parse(value);
}
return ret;
}
public int GetIntegerForKey(string key, int defaultValue=0)
{
string value = GetValueForKey(key);
int ret = defaultValue;
if (value != null)
{
ret = CCUtils.CCParseInt(value);
}
return ret;
}
public float GetFloatForKey(string key, float defaultValue)
{
float ret = (float)GetDoubleForKey(key, (double)defaultValue);
return ret;
}
public double GetDoubleForKey(string key, double defaultValue)
{
string value = GetValueForKey(key);
double ret = defaultValue;
if (value != null)
{
ret = double.Parse(value);
}
return ret;
}
public string GetStringForKey(string key, string defaultValue)
{
string value = GetValueForKey(key);
string ret = defaultValue;
if (value != null)
{
ret = value;
}
return ret;
}
public void SetBoolForKey(string key, bool value)
{
// check key
if (key == null) {
return;
}
// save bool value as string
SetStringForKey(key, value.ToString());
}
public void SetIntegerForKey(string key, int value)
{
// check key
if (key == null)
{
return;
}
// convert to string
SetValueForKey(key, value.ToString());
}
public void SetFloatForKey(string key, float value)
{
SetDoubleForKey(key, value);
}
public void SetDoubleForKey(string key, double value)
{
// check key
if (key == null)
{
return;
}
// convert to string
SetValueForKey(key, value.ToString());
}
public void SetStringForKey(string key, string value)
{
// check key
if (key == null)
{
return;
}
// convert to string
SetValueForKey(key, value.ToString());
}
bool IsXMLFileExist()
{
bool bRet = false;
#if NETFX_CORE
// use the StorageContainer to determine if the file exists.
if (myIsolatedStorage.FileExists(XML_FILE_NAME))
{
bRet = true;
}
#elif WINDOWS || LINUX || MACOS
if (new FileInfo(XML_FILE_NAME).Exists)
{
bRet = true;
}
#else
if (myIsolatedStorage.FileExists(XML_FILE_NAME))
{
bRet = true;
}
#endif
return bRet;
}
bool CreateXMLFile()
{
bool bRet = false;
#if NETFX_CORE
using (StreamWriter writeFile = new StreamWriter(myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.OpenOrCreate)))
#elif WINDOWS || LINUX || MACOS
using (StreamWriter writeFile = new StreamWriter(XML_FILE_NAME))
#else
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(XML_FILE_NAME, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
#endif
{
string someTextData = "<?xml version=\"1.0\" encoding=\"utf-8\"?><userDefaultRoot>";
writeFile.WriteLine(someTextData);
// Do not write anything here. This just creates the temporary xml save file.
writeFile.WriteLine("</userDefaultRoot>");
}
return bRet;
}
public void Flush()
{
#if NETFX_CORE
using (Stream stream = myIsolatedStorage.OpenFile(XML_FILE_NAME, FileMode.OpenOrCreate))
#elif WINDOWS || LINUX || MACOS
using (StreamWriter stream = new StreamWriter(XML_FILE_NAME))
#else
using (StreamWriter stream = new StreamWriter(new IsolatedStorageFileStream(XML_FILE_NAME, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
#endif
{
//create xml doc
XmlWriterSettings ws = new XmlWriterSettings();
ws.Encoding = Encoding.UTF8;
ws.Indent = true;
using (XmlWriter writer = XmlWriter.Create(stream, ws))
{
writer.WriteStartDocument();
writer.WriteStartElement(USERDEFAULT_ROOT_NAME);
foreach (KeyValuePair<string, string> pair in values)
{
writer.WriteStartElement(pair.Key);
writer.WriteString(pair.Value);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndDocument();
}
}
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// 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 NUnit.Framework.Api;
using NUnit.TestData.FixtureSetUpTearDownData;
using NUnit.TestUtilities;
using NUnit.TestData.TestFixtureData;
using IgnoredFixture = NUnit.TestData.TestFixtureData.IgnoredFixture;
namespace NUnit.Framework.Internal
{
/// <summary>
/// Tests of the NUnitTestFixture class
/// </summary>
[TestFixture]
public class TestFixtureTests
{
private static void CanConstructFrom(Type fixtureType)
{
CanConstructFrom(fixtureType, fixtureType.Name);
}
private static void CanConstructFrom(Type fixtureType, string expectedName)
{
TestSuite fixture = TestBuilder.MakeFixture(fixtureType);
Assert.AreEqual(expectedName, fixture.Name);
Assert.AreEqual(fixtureType.FullName, fixture.FullName);
}
[Test]
public void ConstructFromType()
{
CanConstructFrom(typeof(FixtureWithTestFixtureAttribute));
}
[Test]
public void ConstructFromNestedType()
{
CanConstructFrom(typeof(OuterClass.NestedTestFixture), "OuterClass+NestedTestFixture");
}
[Test]
public void ConstructFromDoublyNestedType()
{
CanConstructFrom(typeof(OuterClass.NestedTestFixture.DoublyNestedTestFixture),
"OuterClass+NestedTestFixture+DoublyNestedTestFixture");
}
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTest()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTest));
}
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCase()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCase));
}
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTestCaseSource()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTestCaseSource));
}
#if !NUNITLITE
[Test]
public void ConstructFromTypeWithoutTestFixtureAttributeContainingTheory()
{
CanConstructFrom(typeof(FixtureWithoutTestFixtureAttributeContainingTheory));
}
#endif
[Test]
public void CannotRunConstructorWithArgsNotSupplied()
{
TestAssert.IsNotRunnable(typeof(NoDefaultCtorFixture));
}
[Test]
public void CanRunConstructorWithArgsSupplied()
{
TestAssert.IsRunnable(typeof(FixtureWithArgsSupplied), ResultState.Success);
}
[Test]
public void CannotRunBadConstructor()
{
TestAssert.IsNotRunnable(typeof(BadCtorFixture));
}
[Test]
public void CanRunMultipleSetUp()
{
TestAssert.IsRunnable(typeof(MultipleSetUpAttributes), ResultState.Success);
}
[Test]
public void CanRunMultipleTearDown()
{
TestAssert.IsRunnable(typeof(MultipleTearDownAttributes), ResultState.Success);
}
[Test]
public void CannotRunIgnoredFixture()
{
TestSuite suite = TestBuilder.MakeFixture( typeof( IgnoredFixture ) );
Assert.AreEqual( RunState.Ignored, suite.RunState );
Assert.AreEqual( "testing ignore a fixture", suite.Properties.Get(PropertyNames.SkipReason) );
}
// [Test]
// public void CannotRunAbstractFixture()
// {
// TestAssert.IsNotRunnable(typeof(AbstractTestFixture));
// }
[Test]
public void CanRunFixtureDerivedFromAbstractTestFixture()
{
TestAssert.IsRunnable(typeof(DerivedFromAbstractTestFixture), ResultState.Success);
}
[Test]
public void CanRunFixtureDerivedFromAbstractDerivedTestFixture()
{
TestAssert.IsRunnable(typeof(DerivedFromAbstractDerivedTestFixture), ResultState.Success);
}
// [Test]
// public void CannotRunAbstractDerivedFixture()
// {
// TestAssert.IsNotRunnable(typeof(AbstractDerivedTestFixture));
// }
[Test]
public void FixtureInheritingTwoTestFixtureAttributesIsLoadedOnlyOnce()
{
TestSuite suite = TestBuilder.MakeFixture(typeof(DoubleDerivedClassWithTwoInheritedAttributes));
Assert.That(suite, Is.TypeOf(typeof(TestFixture)));
Assert.That(suite.Tests.Count, Is.EqualTo(0));
}
[Test]
public void CanRunMultipleTestFixtureSetUp()
{
TestAssert.IsRunnable(typeof(MultipleFixtureSetUpAttributes), ResultState.Success);
}
[Test]
public void CanRunMultipleTestFixtureTearDown()
{
TestAssert.IsRunnable(typeof(MultipleFixtureTearDownAttributes), ResultState.Success);
}
[Test]
public void CanRunTestFixtureWithNoTests()
{
TestAssert.IsRunnable(typeof(FixtureWithNoTests), ResultState.Success);
}
#if CLR_2_0 || CLR_4_0
[Test]
public void ConstructFromStaticTypeWithoutTestFixtureAttribute()
{
CanConstructFrom(typeof(StaticFixtureWithoutTestFixtureAttribute));
}
[Test]
public void CanRunStaticFixture()
{
TestAssert.IsRunnable(typeof(StaticFixtureWithoutTestFixtureAttribute), ResultState.Success);
}
#if !NETCF
[Test, Platform(Exclude = "NETCF", Reason = "NYI")]
public void CanRunGenericFixtureWithProperArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(
typeof(NUnit.TestData.TestFixtureData.GenericFixtureWithProperArgsProvided<>));
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite is ParameterizedFixtureSuite);
Assert.That(suite.Tests.Count, Is.EqualTo(2));
}
// [Test]
// public void CannotRunGenericFixtureWithNoTestFixtureAttribute()
// {
// TestSuite suite = TestBuilder.MakeFixture(
// GetTestDataType("NUnit.TestData.TestFixtureData.GenericFixtureWithNoTestFixtureAttribute`1"));
//
// Assert.That(suite.RunState, Is.EqualTo(RunState.NotRunnable));
// Assert.That(suite.Properties.Get(PropertyNames.SkipReason),
// Is.StringStarting("Fixture type contains generic parameters"));
// }
[Test, Platform(Exclude = "NETCF", Reason = "NYI")]
public void CannotRunGenericFixtureWithNoArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(
typeof(NUnit.TestData.TestFixtureData.GenericFixtureWithNoArgsProvided<>));
Test fixture = (Test)suite.Tests[0];
Assert.That(fixture.RunState, Is.EqualTo(RunState.NotRunnable));
Assert.That((string)fixture.Properties.Get(PropertyNames.SkipReason), Is.StringStarting("Fixture type contains generic parameters"));
}
[Test, Platform(Exclude = "NETCF", Reason = "NYI")]
public void CannotRunGenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(
typeof(NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithNoArgsProvided<>));
TestAssert.IsNotRunnable((Test)suite.Tests[0]);
}
[Test, Platform(Exclude = "NETCF", Reason = "NYI")]
public void CanRunGenericFixtureDerivedFromAbstractFixtureWithArgsProvided()
{
TestSuite suite = TestBuilder.MakeFixture(
typeof(NUnit.TestData.TestFixtureData.GenericFixtureDerivedFromAbstractFixtureWithArgsProvided<>));
Assert.That(suite.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(suite is ParameterizedFixtureSuite);
Assert.That(suite.Tests.Count, Is.EqualTo(2));
}
#endif
#endif
#region SetUp Signature
[Test]
public void CannotRunPrivateSetUp()
{
TestAssert.IsNotRunnable(typeof(PrivateSetUp));
}
#if !SILVERLIGHT
[Test]
public void CanRunProtectedSetUp()
{
TestAssert.IsRunnable(typeof(ProtectedSetUp), ResultState.Success);
}
#endif
/// <summary>
/// Determines whether this instance [can run static set up].
/// </summary>
[Test]
public void CanRunStaticSetUp()
{
TestAssert.IsRunnable(typeof(StaticSetUp), ResultState.Success);
}
[Test]
public void CannotRunSetupWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(SetUpWithReturnValue));
}
[Test]
public void CannotRunSetupWithParameters()
{
TestAssert.IsNotRunnable(typeof(SetUpWithParameters));
}
#endregion
#region TearDown Signature
[Test]
public void CannotRunPrivateTearDown()
{
TestAssert.IsNotRunnable(typeof(PrivateTearDown));
}
#if !SILVERLIGHT
[Test]
public void CanRunProtectedTearDown()
{
TestAssert.IsRunnable(typeof(ProtectedTearDown), ResultState.Success);
}
#endif
[Test]
public void CanRunStaticTearDown()
{
TestAssert.IsRunnable(typeof(StaticTearDown), ResultState.Success);
}
[Test]
public void CannotRunTearDownWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(TearDownWithReturnValue));
}
[Test]
public void CannotRunTearDownWithParameters()
{
TestAssert.IsNotRunnable(typeof(TearDownWithParameters));
}
#endregion
#region TestFixtureSetUp Signature
[Test]
public void CannotRunPrivateFixtureSetUp()
{
TestAssert.IsNotRunnable(typeof(PrivateFixtureSetUp));
}
#if !SILVERLIGHT
[Test]
public void CanRunProtectedFixtureSetUp()
{
TestAssert.IsRunnable(typeof(ProtectedFixtureSetUp), ResultState.Success);
}
#endif
[Test]
public void CanRunStaticFixtureSetUp()
{
TestAssert.IsRunnable(typeof(StaticFixtureSetUp), ResultState.Success);
}
[Test]
public void CannotRunFixtureSetupWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(FixtureSetUpWithReturnValue));
}
[Test]
public void CannotRunFixtureSetupWithParameters()
{
TestAssert.IsNotRunnable(typeof(FixtureSetUpWithParameters));
}
#endregion
#region TestFixtureTearDown Signature
[Test]
public void CannotRunPrivateFixtureTearDown()
{
TestAssert.IsNotRunnable(typeof(PrivateFixtureTearDown));
}
#if !SILVERLIGHT
[Test]
public void CanRunProtectedFixtureTearDown()
{
TestAssert.IsRunnable(typeof(ProtectedFixtureTearDown), ResultState.Success);
}
#endif
[Test]
public void CanRunStaticFixtureTearDown()
{
TestAssert.IsRunnable(typeof(StaticFixtureTearDown), ResultState.Success);
}
// [TestFixture]
// [Category("fixture category")]
// [Category("second")]
// private class HasCategories
// {
// [Test] public void OneTest()
// {}
// }
//
// [Test]
// public void LoadCategories()
// {
// TestSuite fixture = LoadFixture("NUnit.Core.Tests.TestFixtureBuilderTests+HasCategories");
// Assert.IsNotNull(fixture);
// Assert.AreEqual(2, fixture.Categories.Count);
// }
[Test]
public void CannotRunFixtureTearDownWithReturnValue()
{
TestAssert.IsNotRunnable(typeof(FixtureTearDownWithReturnValue));
}
[Test]
public void CannotRunFixtureTearDownWithParameters()
{
TestAssert.IsNotRunnable(typeof(FixtureTearDownWithParameters));
}
#endregion
}
}
| |
//
// System.Web.UI.ControlCollection.cs
//
// Authors:
// Duncan Mak (duncan@ximian.com)
// Gonzalo Paniagua Javier (gonzalo@novell.com)
//
// Copyright (c) 2002-2004 Novell, Inc. (http://www.novell.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.
//
using System;
using System.Collections;
namespace System.Web.UI {
public class ControlCollection : ICollection, IEnumerable
{
Control owner;
Control [] controls;
int version;
int count;
bool readOnly;
public ControlCollection (Control owner)
{
if (owner == null)
throw new ArgumentException ("owner");
this.owner = owner;
}
public int Count {
get { return count; }
}
public bool IsReadOnly {
get { return readOnly; }
}
public bool IsSynchronized {
get { return false; }
}
public virtual Control this [int index] {
get {
if (index < 0 || index >= count)
throw new ArgumentOutOfRangeException ("index");
return controls [index];
}
}
protected Control Owner {
get { return owner; }
}
public object SyncRoot {
get { return this; }
}
void EnsureControls ()
{
if (controls == null) {
controls = new Control [5];
} else if (controls.Length < count + 1) {
int n = controls.Length == 5 ? 3 : 2;
Control [] newControls = new Control [controls.Length * n];
Array.Copy (controls, 0, newControls, 0, controls.Length);
controls = newControls;
}
}
public virtual void Add (Control child)
{
if (child == null)
throw new ArgumentNullException ();
if (readOnly)
throw new HttpException ();
EnsureControls ();
version++;
controls [count++] = child;
owner.AddedControl (child, count - 1);
}
public virtual void AddAt (int index, Control child)
{
if (child == null) // maybe we should check for ! (child is Control)?
throw new ArgumentNullException ();
if (index < -1 || index > count)
throw new ArgumentOutOfRangeException ();
if (readOnly)
throw new HttpException ();
if (index == -1) {
Add (child);
return;
}
EnsureControls ();
version++;
Array.Copy (controls, index, controls, index + 1, count - index);
count++;
controls [index] = child;
owner.AddedControl (child, index);
}
public virtual void Clear ()
{
if (controls == null)
return;
version++;
for (int i = 0; i < count; i++)
owner.RemovedControl (controls [i]);
count = 0;
if (owner != null)
owner.ResetChildNames ();
}
public virtual bool Contains (Control c)
{
return (controls != null && Array.IndexOf (controls, c) != -1);
}
public void CopyTo (Array array, int index)
{
if (controls == null)
return;
controls.CopyTo (array, index);
}
public IEnumerator GetEnumerator ()
{
return new SimpleEnumerator (this);
}
public virtual int IndexOf (Control c)
{
if (controls == null)
return -1;
return Array.IndexOf (controls, c);
}
public virtual void Remove (Control value)
{
int idx = IndexOf (value);
if (idx == -1)
return;
RemoveAt (idx);
}
public virtual void RemoveAt (int index)
{
if (readOnly)
throw new HttpException ();
version++;
Control ctrl = controls [index];
count--;
if (count - index > 0)
Array.Copy (controls, index + 1, controls, index, count - index);
controls [count] = null;
owner.RemovedControl (ctrl);
}
internal void SetReadonly (bool readOnly)
{
this.readOnly = readOnly;
}
// Almost the same as in ArrayList
sealed class SimpleEnumerator : IEnumerator
{
ControlCollection coll;
int index;
int version;
object currentElement;
public SimpleEnumerator (ControlCollection coll)
{
this.coll = coll;
index = -1;
version = coll.version;
}
public bool MoveNext ()
{
if (version != coll.version)
throw new InvalidOperationException ("List has changed.");
if (index >= -1 && ++index < coll.Count) {
currentElement = coll [index];
return true;
} else {
index = -2;
return false;
}
}
public object Current {
get {
if (index < 0)
throw new InvalidOperationException (index == -1 ? "Enumerator not started" : "Enumerator ended");
return currentElement;
}
}
public void Reset ()
{
if (version != coll.version)
throw new InvalidOperationException ("List has changed.");
index = -1;
}
}
}
}
| |
#region License
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion
using System.Globalization;
using FakeItEasy;
using NUnit.Framework;
namespace Spring.Context.Support
{
[TestFixture]
public sealed class AbstractMessageSourceTests : AbstractMessageSource
{
[SetUp]
public void Init()
{
ResetMe();
}
[Test]
public void GetResolvableNullCodes()
{
var res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns(null);
Assert.Throws<NoSuchMessageException>(() => GetMessage(res, CultureInfo.CurrentCulture));
}
[Test]
public void GetResolvableDefaultsToParentMessageSource()
{
string MSGCODE = "nullCode";
object[] MSGARGS = new object[] { "arg1", "arg2" };
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetArguments()).Returns(MSGARGS);
A.CallTo(() => res.GetCodes()).Returns(new string[] {MSGCODE}).Once();
IMessageSource parentSource = A.Fake<IMessageSource>();
A.CallTo(() => parentSource.GetMessage(MSGCODE, null, CultureInfo.CurrentCulture, A<object[]>._)).Returns("MockMessageSource");
ParentMessageSource = parentSource;
Assert.AreEqual("MockMessageSource", GetMessage(res, CultureInfo.CurrentCulture), "My Message");
}
[Test]
public void GetMessageParentMessageSource()
{
object[] args = new object[] {"arguments"};
IMessageSource parentSource = A.Fake<IMessageSource>();
A.CallTo(() => parentSource.GetMessage("null", null, CultureInfo.CurrentCulture, A<object[]>._)).Returns("my parent message");
ParentMessageSource = parentSource;
Assert.AreEqual("my parent message", GetMessage("null", "message", CultureInfo.CurrentCulture, args[0]));
}
[Test]
public void GetMessageResolvableDefaultMessage()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns("MyDefaultMessage");
A.CallTo(() => res.GetCodes()).Returns(null);
A.CallTo(() => res.GetArguments()).Returns(null);
Assert.AreEqual("MyDefaultMessage", GetMessage(res, CultureInfo.CurrentCulture), "Default");
}
[Test]
public void GetMessageResolvableReturnsFirstCode()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns(null);
A.CallTo(() => res.GetCodes()).Returns(new string[] {"null"});
A.CallTo(() => res.GetArguments()).Returns(null);
UseCodeAsDefaultMessage = true;
Assert.AreEqual("null", GetMessage(res, CultureInfo.CurrentCulture), "Code");
}
[Test]
public void GetMessageResolvableNoValidMessage()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns(null);
A.CallTo(() => res.GetCodes()).Returns(null);
A.CallTo(() => res.GetArguments()).Returns(null);
Assert.Throws<NoSuchMessageException>(() => GetMessage(res, CultureInfo.CurrentCulture));
}
[Test]
public void GetMessageResolvableValidMessageAndCode()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetCodes()).Returns(new string[] {"code1"});
A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "arguments" });
Assert.AreEqual("my arguments", GetMessage(res, CultureInfo.CurrentCulture), "Resolve");
}
[Test]
public void GetMessageResolvableValidMessageAndCodeNullCulture()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1" });
A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "arguments" });
Assert.AreEqual("my arguments", GetMessage(res, null), "Resolve");
}
[Test]
public void GetMessageNullCode()
{
Assert.Throws<NoSuchMessageException>(() => GetMessage(null));
}
[Test]
public void GetMessageValidMessageAndCode()
{
Assert.AreEqual("my arguments", GetMessage("code1", new object[] {"my", "arguments"}), "Resolve");
}
[Test]
public void GetMessageValidMessageAndCodeNullCulture()
{
Assert.AreEqual("my arguments", GetMessage("code1", null, new object[] {"my", "arguments"}), "Resolve");
}
[Test]
public void GetMessageUseDefaultCode()
{
UseCodeAsDefaultMessage = true;
Assert.AreEqual("null", GetMessage("null", new object[] {"arguments"}), "message");
Assert.IsTrue(UseCodeAsDefaultMessage, "default");
}
[Test]
public void GetMessageNoValidMessage()
{
Assert.Throws<NoSuchMessageException>(() => GetMessage("null", new object[] {"arguments"}));
}
[Test]
public void GetMessageWithResolvableArguments()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.GetCodes()).Returns(new string[] { "code1" });
A.CallTo(() => res.GetArguments()).Returns(new object[] { "my", "resolvable" });
Assert.AreEqual("spring my resolvable", GetMessage("code2", CultureInfo.CurrentCulture, new object[] {"spring", res}), "Resolve");
}
[Test]
public void GetMessageResolvableValidMessageAndCodNullMessageFormat()
{
IMessageSourceResolvable res = A.Fake<IMessageSourceResolvable>();
A.CallTo(() => res.DefaultMessage).Returns("myDefaultMessage");
A.CallTo(() => res.GetCodes()).Returns(new string[] { "nullCode" });
A.CallTo(() => res.GetArguments()).Returns(null);
Assert.AreEqual("myDefaultMessage", GetMessage(res, null), "Resolve");
}
private void ResetMe()
{
ParentMessageSource = null;
UseCodeAsDefaultMessage = false;
}
protected override string ResolveMessage(string code, CultureInfo cultureInfo)
{
if (code.Equals("null"))
{
return null;
}
else if (code.Equals("nullCode"))
{
return null;
}
else
{
return "{0} {1}";
}
}
protected override object ResolveObject(string code, CultureInfo cultureInfo)
{
return null;
}
protected override void ApplyResourcesToObject(object value, string objectName, CultureInfo cultureInfo)
{
}
}
}
| |
// 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.Net.Sockets;
using System.Net.Test.Common;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Security.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public class CertificateValidationClientServer : IDisposable
{
private readonly X509Certificate2 _clientCertificate;
private readonly X509Certificate2Collection _clientCertificateCollection;
private readonly X509Certificate2 _serverCertificate;
private readonly X509Certificate2Collection _serverCertificateCollection;
private bool _clientCertificateRemovedByFilter;
public CertificateValidationClientServer()
{
_serverCertificateCollection = Configuration.Certificates.GetServerCertificateCollection();
_serverCertificate = Configuration.Certificates.GetServerCertificate();
_clientCertificateCollection = Configuration.Certificates.GetClientCertificateCollection();
_clientCertificate = Configuration.Certificates.GetClientCertificate();
}
public void Dispose()
{
_serverCertificate.Dispose();
_clientCertificate.Dispose();
foreach (X509Certificate2 cert in _serverCertificateCollection) cert.Dispose();
foreach (X509Certificate2 cert in _clientCertificateCollection) cert.Dispose();
}
[Theory]
[InlineData(false)]
[InlineData(true)]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "https://github.com/dotnet/corefx/issues/19379")]
public async Task CertificateValidationClientServer_EndToEnd_Ok(bool useClientSelectionCallback)
{
IPEndPoint endPoint = new IPEndPoint(IPAddress.IPv6Loopback, 0);
var server = new TcpListener(endPoint);
server.Start();
_clientCertificateRemovedByFilter = false;
if (PlatformDetection.IsWindows7 &&
!useClientSelectionCallback &&
!Capability.IsTrustedRootCertificateInstalled())
{
// https://technet.microsoft.com/en-us/library/hh831771.aspx#BKMK_Changes2012R2
// Starting with Windows 8, the "Management of trusted issuers for client authentication" has changed:
// The behavior to send the Trusted Issuers List by default is off.
//
// In Windows 7 the Trusted Issuers List is sent within the Server Hello TLS record. This list is built
// by the server using certificates from the Trusted Root Authorities certificate store.
// The client side will use the Trusted Issuers List, if not empty, to filter proposed certificates.
_clientCertificateRemovedByFilter = true;
}
using (var clientConnection = new TcpClient(AddressFamily.InterNetworkV6))
{
IPEndPoint serverEndPoint = (IPEndPoint)server.LocalEndpoint;
Task clientConnect = clientConnection.ConnectAsync(serverEndPoint.Address, serverEndPoint.Port);
Task<TcpClient> serverAccept = server.AcceptTcpClientAsync();
Assert.True(
Task.WaitAll(
new Task[] { clientConnect, serverAccept },
TestConfiguration.PassingTestTimeoutMilliseconds),
"Client/Server TCP Connect timed out.");
LocalCertificateSelectionCallback clientCertCallback = null;
if (useClientSelectionCallback)
{
clientCertCallback = ClientCertSelectionCallback;
}
using (TcpClient serverConnection = await serverAccept)
using (SslStream sslClientStream = new SslStream(
clientConnection.GetStream(),
false,
ClientSideRemoteServerCertificateValidation,
clientCertCallback))
using (SslStream sslServerStream = new SslStream(
serverConnection.GetStream(),
false,
ServerSideRemoteClientCertificateValidation))
{
string serverName = _serverCertificate.GetNameInfo(X509NameType.SimpleName, false);
var clientCerts = new X509CertificateCollection();
if (!useClientSelectionCallback)
{
clientCerts.Add(_clientCertificate);
}
Task clientAuthentication = sslClientStream.AuthenticateAsClientAsync(
serverName,
clientCerts,
SslProtocolSupport.DefaultSslProtocols,
false);
Task serverAuthentication = sslServerStream.AuthenticateAsServerAsync(
_serverCertificate,
true,
SslProtocolSupport.DefaultSslProtocols,
false);
Assert.True(
Task.WaitAll(
new Task[] { clientAuthentication, serverAuthentication },
TestConfiguration.PassingTestTimeoutMilliseconds),
"Client/Server Authentication timed out.");
if (!_clientCertificateRemovedByFilter)
{
Assert.True(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
Assert.True(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");
Assert.Equal(sslServerStream.RemoteCertificate.Subject, _clientCertificate.Subject);
}
else
{
Assert.False(sslClientStream.IsMutuallyAuthenticated, "sslClientStream.IsMutuallyAuthenticated");
Assert.False(sslServerStream.IsMutuallyAuthenticated, "sslServerStream.IsMutuallyAuthenticated");
Assert.Null(sslServerStream.RemoteCertificate);
}
Assert.Equal(sslClientStream.RemoteCertificate.Subject, _serverCertificate.Subject);
}
}
}
private X509Certificate ClientCertSelectionCallback(
object sender,
string targetHost,
X509CertificateCollection localCertificates,
X509Certificate remoteCertificate,
string[] acceptableIssuers)
{
return _clientCertificate;
}
private bool ServerSideRemoteClientCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None;
if (!Capability.IsTrustedRootCertificateInstalled())
{
if (!_clientCertificateRemovedByFilter)
{
expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;
}
else
{
expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateNotAvailable;
}
}
else
{
// Validate only if we're able to build a trusted chain.
CertificateChainValidation.Validate(_clientCertificateCollection, chain);
}
Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors);
if (!_clientCertificateRemovedByFilter)
{
Assert.Equal(_clientCertificate, certificate);
}
return true;
}
private bool ClientSideRemoteServerCertificateValidation(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
SslPolicyErrors expectedSslPolicyErrors = SslPolicyErrors.None;
if (!Capability.IsTrustedRootCertificateInstalled())
{
expectedSslPolicyErrors = SslPolicyErrors.RemoteCertificateChainErrors;
}
else
{
// Validate only if we're able to build a trusted chain.
CertificateChainValidation.Validate(_serverCertificateCollection, chain);
}
Assert.Equal(expectedSslPolicyErrors, sslPolicyErrors);
Assert.Equal(_serverCertificate, certificate);
return true;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Thrift.Transport;
using System.Globalization;
namespace Thrift.Protocol
{
/// <summary>
/// JSON protocol implementation for thrift.
///
/// This is a full-featured protocol supporting Write and Read.
///
/// Please see the C++ class header for a detailed description of the
/// protocol's wire format.
///
/// Adapted from the Java version.
/// </summary>
public class TJSONProtocol : TProtocol
{
/// <summary>
/// Factory for JSON protocol objects
/// </summary>
public class Factory : TProtocolFactory
{
public TProtocol GetProtocol(TTransport trans)
{
return new TJSONProtocol(trans);
}
}
private static byte[] COMMA = new byte[] { (byte)',' };
private static byte[] COLON = new byte[] { (byte)':' };
private static byte[] LBRACE = new byte[] { (byte)'{' };
private static byte[] RBRACE = new byte[] { (byte)'}' };
private static byte[] LBRACKET = new byte[] { (byte)'[' };
private static byte[] RBRACKET = new byte[] { (byte)']' };
private static byte[] QUOTE = new byte[] { (byte)'"' };
private static byte[] BACKSLASH = new byte[] { (byte)'\\' };
private static byte[] ZERO = new byte[] { (byte)'0' };
private byte[] ESCSEQ = new byte[] { (byte)'\\', (byte)'u', (byte)'0', (byte)'0' };
private const long VERSION = 1;
private byte[] JSON_CHAR_TABLE = {
0, 0, 0, 0, 0, 0, 0, 0,(byte)'b',(byte)'t',(byte)'n', 0,(byte)'f',(byte)'r', 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1,(byte)'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
private char[] ESCAPE_CHARS = "\"\\bfnrt".ToCharArray();
private byte[] ESCAPE_CHAR_VALS = {
(byte)'"', (byte)'\\', (byte)'\b', (byte)'\f', (byte)'\n', (byte)'\r', (byte)'\t',
};
private const int DEF_STRING_SIZE = 16;
private static byte[] NAME_BOOL = new byte[] { (byte)'t', (byte)'f' };
private static byte[] NAME_BYTE = new byte[] { (byte)'i', (byte)'8' };
private static byte[] NAME_I16 = new byte[] { (byte)'i', (byte)'1', (byte)'6' };
private static byte[] NAME_I32 = new byte[] { (byte)'i', (byte)'3', (byte)'2' };
private static byte[] NAME_I64 = new byte[] { (byte)'i', (byte)'6', (byte)'4' };
private static byte[] NAME_DOUBLE = new byte[] { (byte)'d', (byte)'b', (byte)'l' };
private static byte[] NAME_STRUCT = new byte[] { (byte)'r', (byte)'e', (byte)'c' };
private static byte[] NAME_STRING = new byte[] { (byte)'s', (byte)'t', (byte)'r' };
private static byte[] NAME_MAP = new byte[] { (byte)'m', (byte)'a', (byte)'p' };
private static byte[] NAME_LIST = new byte[] { (byte)'l', (byte)'s', (byte)'t' };
private static byte[] NAME_SET = new byte[] { (byte)'s', (byte)'e', (byte)'t' };
private static byte[] GetTypeNameForTypeID(TType typeID)
{
switch (typeID)
{
case TType.Bool:
return NAME_BOOL;
case TType.Byte:
return NAME_BYTE;
case TType.I16:
return NAME_I16;
case TType.I32:
return NAME_I32;
case TType.I64:
return NAME_I64;
case TType.Double:
return NAME_DOUBLE;
case TType.String:
return NAME_STRING;
case TType.Struct:
return NAME_STRUCT;
case TType.Map:
return NAME_MAP;
case TType.Set:
return NAME_SET;
case TType.List:
return NAME_LIST;
default:
throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
"Unrecognized type");
}
}
private static TType GetTypeIDForTypeName(byte[] name)
{
TType result = TType.Stop;
if (name.Length > 1)
{
switch (name[0])
{
case (byte)'d':
result = TType.Double;
break;
case (byte)'i':
switch (name[1])
{
case (byte)'8':
result = TType.Byte;
break;
case (byte)'1':
result = TType.I16;
break;
case (byte)'3':
result = TType.I32;
break;
case (byte)'6':
result = TType.I64;
break;
}
break;
case (byte)'l':
result = TType.List;
break;
case (byte)'m':
result = TType.Map;
break;
case (byte)'r':
result = TType.Struct;
break;
case (byte)'s':
if (name[1] == (byte)'t')
{
result = TType.String;
}
else if (name[1] == (byte)'e')
{
result = TType.Set;
}
break;
case (byte)'t':
result = TType.Bool;
break;
}
}
if (result == TType.Stop)
{
throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
"Unrecognized type");
}
return result;
}
///<summary>
/// Base class for tracking JSON contexts that may require
/// inserting/Reading additional JSON syntax characters
/// This base context does nothing.
///</summary>
protected class JSONBaseContext
{
protected TJSONProtocol proto;
public JSONBaseContext(TJSONProtocol proto)
{
this.proto = proto;
}
public virtual void Write() { }
public virtual void Read() { }
public virtual bool EscapeNumbers() { return false; }
}
///<summary>
/// Context for JSON lists. Will insert/Read commas before each item except
/// for the first one
///</summary>
protected class JSONListContext : JSONBaseContext
{
public JSONListContext(TJSONProtocol protocol)
: base(protocol)
{
}
private bool first = true;
public override void Write()
{
if (first)
{
first = false;
}
else
{
proto.trans.Write(COMMA);
}
}
public override void Read()
{
if (first)
{
first = false;
}
else
{
proto.ReadJSONSyntaxChar(COMMA);
}
}
}
///<summary>
/// Context for JSON records. Will insert/Read colons before the value portion
/// of each record pair, and commas before each key except the first. In
/// addition, will indicate that numbers in the key position need to be
/// escaped in quotes (since JSON keys must be strings).
///</summary>
protected class JSONPairContext : JSONBaseContext
{
public JSONPairContext(TJSONProtocol proto)
: base(proto)
{
}
private bool first = true;
private bool colon = true;
public override void Write()
{
if (first)
{
first = false;
colon = true;
}
else
{
proto.trans.Write(colon ? COLON : COMMA);
colon = !colon;
}
}
public override void Read()
{
if (first)
{
first = false;
colon = true;
}
else
{
proto.ReadJSONSyntaxChar(colon ? COLON : COMMA);
colon = !colon;
}
}
public override bool EscapeNumbers()
{
return colon;
}
}
///<summary>
/// Holds up to one byte from the transport
///</summary>
protected class LookaheadReader
{
protected TJSONProtocol proto;
public LookaheadReader(TJSONProtocol proto)
{
this.proto = proto;
}
private bool hasData;
private byte[] data = new byte[1];
///<summary>
/// Return and consume the next byte to be Read, either taking it from the
/// data buffer if present or getting it from the transport otherwise.
///</summary>
public byte Read()
{
if (hasData)
{
hasData = false;
}
else
{
proto.trans.ReadAll(data, 0, 1);
}
return data[0];
}
///<summary>
/// Return the next byte to be Read without consuming, filling the data
/// buffer if it has not been filled alReady.
///</summary>
public byte Peek()
{
if (!hasData)
{
proto.trans.ReadAll(data, 0, 1);
}
hasData = true;
return data[0];
}
}
// Default encoding
protected Encoding utf8Encoding = UTF8Encoding.UTF8;
// Stack of nested contexts that we may be in
protected Stack<JSONBaseContext> contextStack = new Stack<JSONBaseContext>();
// Current context that we are in
protected JSONBaseContext context;
// Reader that manages a 1-byte buffer
protected LookaheadReader reader;
///<summary>
/// Push a new JSON context onto the stack.
///</summary>
protected void PushContext(JSONBaseContext c)
{
contextStack.Push(context);
context = c;
}
///<summary>
/// Pop the last JSON context off the stack
///</summary>
protected void PopContext()
{
context = contextStack.Pop();
}
///<summary>
/// TJSONProtocol Constructor
///</summary>
public TJSONProtocol(TTransport trans)
: base(trans)
{
context = new JSONBaseContext(this);
reader = new LookaheadReader(this);
}
// Temporary buffer used by several methods
private byte[] tempBuffer = new byte[4];
///<summary>
/// Read a byte that must match b[0]; otherwise an exception is thrown.
/// Marked protected to avoid synthetic accessor in JSONListContext.Read
/// and JSONPairContext.Read
///</summary>
protected void ReadJSONSyntaxChar(byte[] b)
{
byte ch = reader.Read();
if (ch != b[0])
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Unexpected character:" + (char)ch);
}
}
///<summary>
/// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its
/// corresponding hex value
///</summary>
private static byte HexVal(byte ch)
{
if ((ch >= '0') && (ch <= '9'))
{
return (byte)((char)ch - '0');
}
else if ((ch >= 'a') && (ch <= 'f'))
{
return (byte)((char)ch - 'a');
}
else
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected hex character");
}
}
///<summary>
/// Convert a byte containing a hex value to its corresponding hex character
///</summary>
private static byte HexChar(byte val)
{
val &= 0x0F;
if (val < 10)
{
return (byte)((char)val + '0');
}
else
{
return (byte)((char)val + 'a');
}
}
///<summary>
/// Write the bytes in array buf as a JSON characters, escaping as needed
///</summary>
private void WriteJSONString(byte[] b)
{
context.Write();
trans.Write(QUOTE);
int len = b.Length;
for (int i = 0; i < len; i++)
{
if ((b[i] & 0x00FF) >= 0x30)
{
if (b[i] == BACKSLASH[0])
{
trans.Write(BACKSLASH);
trans.Write(BACKSLASH);
}
else
{
trans.Write(b, i, 1);
}
}
else
{
tempBuffer[0] = JSON_CHAR_TABLE[b[i]];
if (tempBuffer[0] == 1)
{
trans.Write(b, i, 1);
}
else if (tempBuffer[0] > 1)
{
trans.Write(BACKSLASH);
trans.Write(tempBuffer, 0, 1);
}
else
{
trans.Write(ESCSEQ);
tempBuffer[0] = HexChar((byte)(b[i] >> 4));
tempBuffer[1] = HexChar(b[i]);
trans.Write(tempBuffer, 0, 2);
}
}
}
trans.Write(QUOTE);
}
///<summary>
/// Write out number as a JSON value. If the context dictates so, it will be
/// wrapped in quotes to output as a JSON string.
///</summary>
private void WriteJSONInteger(long num)
{
context.Write();
String str = num.ToString();
bool escapeNum = context.EscapeNumbers();
if (escapeNum)
trans.Write(QUOTE);
trans.Write(utf8Encoding.GetBytes(str));
if (escapeNum)
trans.Write(QUOTE);
}
///<summary>
/// Write out a double as a JSON value. If it is NaN or infinity or if the
/// context dictates escaping, Write out as JSON string.
///</summary>
private void WriteJSONDouble(double num)
{
context.Write();
String str = num.ToString(CultureInfo.InvariantCulture);
bool special = false;
switch (str[0])
{
case 'N': // NaN
case 'I': // Infinity
special = true;
break;
case '-':
if (str[1] == 'I')
{ // -Infinity
special = true;
}
break;
}
bool escapeNum = special || context.EscapeNumbers();
if (escapeNum)
trans.Write(QUOTE);
trans.Write(utf8Encoding.GetBytes(str));
if (escapeNum)
trans.Write(QUOTE);
}
///<summary>
/// Write out contents of byte array b as a JSON string with base-64 encoded
/// data
///</summary>
private void WriteJSONBase64(byte[] b)
{
context.Write();
trans.Write(QUOTE);
int len = b.Length;
int off = 0;
while (len >= 3)
{
// Encode 3 bytes at a time
TBase64Utils.encode(b, off, 3, tempBuffer, 0);
trans.Write(tempBuffer, 0, 4);
off += 3;
len -= 3;
}
if (len > 0)
{
// Encode remainder
TBase64Utils.encode(b, off, len, tempBuffer, 0);
trans.Write(tempBuffer, 0, len + 1);
}
trans.Write(QUOTE);
}
private void WriteJSONObjectStart()
{
context.Write();
trans.Write(LBRACE);
PushContext(new JSONPairContext(this));
}
private void WriteJSONObjectEnd()
{
PopContext();
trans.Write(RBRACE);
}
private void WriteJSONArrayStart()
{
context.Write();
trans.Write(LBRACKET);
PushContext(new JSONListContext(this));
}
private void WriteJSONArrayEnd()
{
PopContext();
trans.Write(RBRACKET);
}
public override void WriteMessageBegin(TMessage message)
{
WriteJSONArrayStart();
WriteJSONInteger(VERSION);
byte[] b = utf8Encoding.GetBytes(message.Name);
WriteJSONString(b);
WriteJSONInteger((long)message.Type);
WriteJSONInteger(message.SeqID);
}
public override void WriteMessageEnd()
{
WriteJSONArrayEnd();
}
public override void WriteStructBegin(TStruct str)
{
WriteJSONObjectStart();
}
public override void WriteStructEnd()
{
WriteJSONObjectEnd();
}
public override void WriteFieldBegin(TField field)
{
WriteJSONInteger(field.ID);
WriteJSONObjectStart();
WriteJSONString(GetTypeNameForTypeID(field.Type));
}
public override void WriteFieldEnd()
{
WriteJSONObjectEnd();
}
public override void WriteFieldStop() { }
public override void WriteMapBegin(TMap map)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(map.KeyType));
WriteJSONString(GetTypeNameForTypeID(map.ValueType));
WriteJSONInteger(map.Count);
WriteJSONObjectStart();
}
public override void WriteMapEnd()
{
WriteJSONObjectEnd();
WriteJSONArrayEnd();
}
public override void WriteListBegin(TList list)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(list.ElementType));
WriteJSONInteger(list.Count);
}
public override void WriteListEnd()
{
WriteJSONArrayEnd();
}
public override void WriteSetBegin(TSet set)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(set.ElementType));
WriteJSONInteger(set.Count);
}
public override void WriteSetEnd()
{
WriteJSONArrayEnd();
}
public override void WriteBool(bool b)
{
WriteJSONInteger(b ? (long)1 : (long)0);
}
public override void WriteByte(byte b)
{
WriteJSONInteger((long)b);
}
public override void WriteI16(short i16)
{
WriteJSONInteger((long)i16);
}
public override void WriteI32(int i32)
{
WriteJSONInteger((long)i32);
}
public override void WriteI64(long i64)
{
WriteJSONInteger(i64);
}
public override void WriteDouble(double dub)
{
WriteJSONDouble(dub);
}
public override void WriteString(String str)
{
byte[] b = utf8Encoding.GetBytes(str);
WriteJSONString(b);
}
public override void WriteBinary(byte[] bin)
{
WriteJSONBase64(bin);
}
/**
* Reading methods.
*/
///<summary>
/// Read in a JSON string, unescaping as appropriate.. Skip Reading from the
/// context if skipContext is true.
///</summary>
private byte[] ReadJSONString(bool skipContext)
{
MemoryStream buffer = new MemoryStream();
if (!skipContext)
{
context.Read();
}
ReadJSONSyntaxChar(QUOTE);
while (true)
{
byte ch = reader.Read();
if (ch == QUOTE[0])
{
break;
}
if (ch == ESCSEQ[0])
{
ch = reader.Read();
if (ch == ESCSEQ[1])
{
ReadJSONSyntaxChar(ZERO);
ReadJSONSyntaxChar(ZERO);
trans.ReadAll(tempBuffer, 0, 2);
ch = (byte)((HexVal((byte)tempBuffer[0]) << 4) + HexVal(tempBuffer[1]));
}
else
{
int off = Array.IndexOf(ESCAPE_CHARS, (char)ch);
if (off == -1)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected control char");
}
ch = ESCAPE_CHAR_VALS[off];
}
}
buffer.Write(new byte[] { (byte)ch }, 0, 1);
}
return buffer.ToArray();
}
///<summary>
/// Return true if the given byte could be a valid part of a JSON number.
///</summary>
private bool IsJSONNumeric(byte b)
{
switch (b)
{
case (byte)'+':
case (byte)'-':
case (byte)'.':
case (byte)'0':
case (byte)'1':
case (byte)'2':
case (byte)'3':
case (byte)'4':
case (byte)'5':
case (byte)'6':
case (byte)'7':
case (byte)'8':
case (byte)'9':
case (byte)'E':
case (byte)'e':
return true;
}
return false;
}
///<summary>
/// Read in a sequence of characters that are all valid in JSON numbers. Does
/// not do a complete regex check to validate that this is actually a number.
////</summary>
private String ReadJSONNumericChars()
{
StringBuilder strbld = new StringBuilder();
while (true)
{
byte ch = reader.Peek();
if (!IsJSONNumeric(ch))
{
break;
}
strbld.Append((char)reader.Read());
}
return strbld.ToString();
}
///<summary>
/// Read in a JSON number. If the context dictates, Read in enclosing quotes.
///</summary>
private long ReadJSONInteger()
{
context.Read();
if (context.EscapeNumbers())
{
ReadJSONSyntaxChar(QUOTE);
}
String str = ReadJSONNumericChars();
if (context.EscapeNumbers())
{
ReadJSONSyntaxChar(QUOTE);
}
try
{
return Int64.Parse(str);
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Bad data encounted in numeric data");
}
}
///<summary>
/// Read in a JSON double value. Throw if the value is not wrapped in quotes
/// when expected or if wrapped in quotes when not expected.
///</summary>
private double ReadJSONDouble()
{
context.Read();
if (reader.Peek() == QUOTE[0])
{
byte[] arr = ReadJSONString(true);
double dub = Double.Parse(utf8Encoding.GetString(arr,0,arr.Length), CultureInfo.InvariantCulture);
if (!context.EscapeNumbers() && !Double.IsNaN(dub) &&
!Double.IsInfinity(dub))
{
// Throw exception -- we should not be in a string in this case
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Numeric data unexpectedly quoted");
}
return dub;
}
else
{
if (context.EscapeNumbers())
{
// This will throw - we should have had a quote if escapeNum == true
ReadJSONSyntaxChar(QUOTE);
}
try
{
return Double.Parse(ReadJSONNumericChars());
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Bad data encounted in numeric data");
}
}
}
//<summary>
/// Read in a JSON string containing base-64 encoded data and decode it.
///</summary>
private byte[] ReadJSONBase64()
{
byte[] b = ReadJSONString(false);
int len = b.Length;
int off = 0;
int size = 0;
while (len >= 4)
{
// Decode 4 bytes at a time
TBase64Utils.decode(b, off, 4, b, size); // NB: decoded in place
off += 4;
len -= 4;
size += 3;
}
// Don't decode if we hit the end or got a single leftover byte (invalid
// base64 but legal for skip of regular string type)
if (len > 1)
{
// Decode remainder
TBase64Utils.decode(b, off, len, b, size); // NB: decoded in place
size += len - 1;
}
// Sadly we must copy the byte[] (any way around this?)
byte[] result = new byte[size];
Array.Copy(b, 0, result, 0, size);
return result;
}
private void ReadJSONObjectStart()
{
context.Read();
ReadJSONSyntaxChar(LBRACE);
PushContext(new JSONPairContext(this));
}
private void ReadJSONObjectEnd()
{
ReadJSONSyntaxChar(RBRACE);
PopContext();
}
private void ReadJSONArrayStart()
{
context.Read();
ReadJSONSyntaxChar(LBRACKET);
PushContext(new JSONListContext(this));
}
private void ReadJSONArrayEnd()
{
ReadJSONSyntaxChar(RBRACKET);
PopContext();
}
public override TMessage ReadMessageBegin()
{
TMessage message = new TMessage();
ReadJSONArrayStart();
if (ReadJSONInteger() != VERSION)
{
throw new TProtocolException(TProtocolException.BAD_VERSION,
"Message contained bad version.");
}
var buf = ReadJSONString(false);
message.Name = utf8Encoding.GetString(buf,0,buf.Length);
message.Type = (TMessageType)ReadJSONInteger();
message.SeqID = (int)ReadJSONInteger();
return message;
}
public override void ReadMessageEnd()
{
ReadJSONArrayEnd();
}
public override TStruct ReadStructBegin()
{
ReadJSONObjectStart();
return new TStruct();
}
public override void ReadStructEnd()
{
ReadJSONObjectEnd();
}
public override TField ReadFieldBegin()
{
TField field = new TField();
byte ch = reader.Peek();
if (ch == RBRACE[0])
{
field.Type = TType.Stop;
}
else
{
field.ID = (short)ReadJSONInteger();
ReadJSONObjectStart();
field.Type = GetTypeIDForTypeName(ReadJSONString(false));
}
return field;
}
public override void ReadFieldEnd()
{
ReadJSONObjectEnd();
}
public override TMap ReadMapBegin()
{
TMap map = new TMap();
ReadJSONArrayStart();
map.KeyType = GetTypeIDForTypeName(ReadJSONString(false));
map.ValueType = GetTypeIDForTypeName(ReadJSONString(false));
map.Count = (int)ReadJSONInteger();
ReadJSONObjectStart();
return map;
}
public override void ReadMapEnd()
{
ReadJSONObjectEnd();
ReadJSONArrayEnd();
}
public override TList ReadListBegin()
{
TList list = new TList();
ReadJSONArrayStart();
list.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
list.Count = (int)ReadJSONInteger();
return list;
}
public override void ReadListEnd()
{
ReadJSONArrayEnd();
}
public override TSet ReadSetBegin()
{
TSet set = new TSet();
ReadJSONArrayStart();
set.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
set.Count = (int)ReadJSONInteger();
return set;
}
public override void ReadSetEnd()
{
ReadJSONArrayEnd();
}
public override bool ReadBool()
{
return (ReadJSONInteger() == 0 ? false : true);
}
public override byte ReadByte()
{
return (byte)ReadJSONInteger();
}
public override short ReadI16()
{
return (short)ReadJSONInteger();
}
public override int ReadI32()
{
return (int)ReadJSONInteger();
}
public override long ReadI64()
{
return (long)ReadJSONInteger();
}
public override double ReadDouble()
{
return ReadJSONDouble();
}
public override String ReadString()
{
var buf = ReadJSONString(false);
return utf8Encoding.GetString(buf,0,buf.Length);
}
public override byte[] ReadBinary()
{
return ReadJSONBase64();
}
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.MultiplayerModels;
using PlayFab.Internal;
using PlayFab.Json;
using PlayFab.Public;
namespace PlayFab
{
/// <summary>
/// API methods for managing multiplayer servers.
/// </summary>
public static partial class PlayFabMultiplayerAPI
{
static PlayFabMultiplayerAPI() {}
/// <summary>
/// Clear the Client SessionToken which allows this Client to call API calls requiring login.
/// A new/fresh login will be required after calling this.
/// </summary>
public static void ForgetAllCredentials()
{
PlayFabHttp.ForgetAllCredentials();
}
/// <summary>
/// Creates a multiplayer server build with a custom container.
/// </summary>
public static void CreateBuildWithCustomContainer(CreateBuildWithCustomContainerRequest request, Action<CreateBuildWithCustomContainerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateBuildWithCustomContainer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Creates a multiplayer server build with a managed container.
/// </summary>
public static void CreateBuildWithManagedContainer(CreateBuildWithManagedContainerRequest request, Action<CreateBuildWithManagedContainerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateBuildWithManagedContainer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Creates a remote user to log on to a VM for a multiplayer server build.
/// </summary>
public static void CreateRemoteUser(CreateRemoteUserRequest request, Action<CreateRemoteUserResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/CreateRemoteUser", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a multiplayer server game asset for a title.
/// </summary>
public static void DeleteAsset(DeleteAssetRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteAsset", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a multiplayer server build.
/// </summary>
public static void DeleteBuild(DeleteBuildRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteBuild", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a multiplayer server game certificate.
/// </summary>
public static void DeleteCertificate(DeleteCertificateRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteCertificate", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Deletes a remote user to log on to a VM for a multiplayer server build.
/// </summary>
public static void DeleteRemoteUser(DeleteRemoteUserRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/DeleteRemoteUser", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Enables the multiplayer server feature for a title.
/// </summary>
public static void EnableMultiplayerServersForTitle(EnableMultiplayerServersForTitleRequest request, Action<EnableMultiplayerServersForTitleResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/EnableMultiplayerServersForTitle", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets the URL to upload assets to.
/// </summary>
public static void GetAssetUploadUrl(GetAssetUploadUrlRequest request, Action<GetAssetUploadUrlResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetAssetUploadUrl", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets a multiplayer server build.
/// </summary>
public static void GetBuild(GetBuildRequest request, Action<GetBuildResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetBuild", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets the credentials to the container registry.
/// </summary>
public static void GetContainerRegistryCredentials(GetContainerRegistryCredentialsRequest request, Action<GetContainerRegistryCredentialsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetContainerRegistryCredentials", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets multiplayer server session details for a build.
/// </summary>
public static void GetMultiplayerServerDetails(GetMultiplayerServerDetailsRequest request, Action<GetMultiplayerServerDetailsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetMultiplayerServerDetails", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets a remote login endpoint to a VM that is hosting a multiplayer server build.
/// </summary>
public static void GetRemoteLoginEndpoint(GetRemoteLoginEndpointRequest request, Action<GetRemoteLoginEndpointResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetRemoteLoginEndpoint", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Gets the status of whether a title is enabled for the multiplayer server feature.
/// </summary>
public static void GetTitleEnabledForMultiplayerServersStatus(GetTitleEnabledForMultiplayerServersStatusRequest request, Action<GetTitleEnabledForMultiplayerServersStatusResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/GetTitleEnabledForMultiplayerServersStatus", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists archived multiplayer server sessions for a build.
/// </summary>
public static void ListArchivedMultiplayerServers(ListMultiplayerServersRequest request, Action<ListMultiplayerServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListArchivedMultiplayerServers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists multiplayer server game assets for a title.
/// </summary>
public static void ListAssetSummaries(ListAssetSummariesRequest request, Action<ListAssetSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListAssetSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists summarized details of all multiplayer server builds for a title.
/// </summary>
public static void ListBuildSummaries(ListBuildSummariesRequest request, Action<ListBuildSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListBuildSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists multiplayer server game certificates for a title.
/// </summary>
public static void ListCertificateSummaries(ListCertificateSummariesRequest request, Action<ListCertificateSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListCertificateSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists custom container images for a title.
/// </summary>
public static void ListContainerImages(ListContainerImagesRequest request, Action<ListContainerImagesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListContainerImages", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists the tags for a custom container image.
/// </summary>
public static void ListContainerImageTags(ListContainerImageTagsRequest request, Action<ListContainerImageTagsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListContainerImageTags", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists multiplayer server sessions for a build.
/// </summary>
public static void ListMultiplayerServers(ListMultiplayerServersRequest request, Action<ListMultiplayerServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListMultiplayerServers", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists quality of service servers.
/// </summary>
public static void ListQosServers(ListQosServersRequest request, Action<ListQosServersResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListQosServers", request, AuthType.None, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Lists virtual machines for a title.
/// </summary>
public static void ListVirtualMachineSummaries(ListVirtualMachineSummariesRequest request, Action<ListVirtualMachineSummariesResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ListVirtualMachineSummaries", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Request a multiplayer server session. Accepts tokens for title and if game client accesss is enabled, allows game client
/// to request a server with player entity token.
/// </summary>
public static void RequestMultiplayerServer(RequestMultiplayerServerRequest request, Action<RequestMultiplayerServerResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/RequestMultiplayerServer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Rolls over the credentials to the container registry.
/// </summary>
public static void RolloverContainerRegistryCredentials(RolloverContainerRegistryCredentialsRequest request, Action<RolloverContainerRegistryCredentialsResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/RolloverContainerRegistryCredentials", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Shuts down a multiplayer server session.
/// </summary>
public static void ShutdownMultiplayerServer(ShutdownMultiplayerServerRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/ShutdownMultiplayerServer", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Updates a multiplayer server build's regions.
/// </summary>
public static void UpdateBuildRegions(UpdateBuildRegionsRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/UpdateBuildRegions", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
/// <summary>
/// Uploads a multiplayer server game certificate.
/// </summary>
public static void UploadCertificate(UploadCertificateRequest request, Action<EmptyResponse> resultCallback, Action<PlayFabError> errorCallback, object customData = null, Dictionary<string, string> extraHeaders = null)
{
PlayFabHttp.MakeApiCall("/MultiplayerServer/UploadCertificate", request, AuthType.EntityToken, resultCallback, errorCallback, customData, extraHeaders);
}
}
}
#endif
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: ErrorLog.cs 644 2009-06-01 18:09:02Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Web;
using System.Collections.Generic;
#endregion
/// <summary>
/// Represents an error log capable of storing and retrieving errors
/// generated in an ASP.NET Web application.
/// </summary>
public abstract class ErrorLog
{
private string _appName;
private bool _appNameInitialized;
private static readonly object _contextKey = new object();
/// <summary>
/// Logs an error in log for the application.
/// </summary>
public abstract string Log(Error error);
/// <summary>
/// When overridden in a subclass, begins an asynchronous version
/// of <see cref="Log"/>.
/// </summary>
public virtual IAsyncResult BeginLog(Error error, AsyncCallback asyncCallback, object asyncState)
{
return BeginSyncImpl(asyncCallback, asyncState, new LogHandler(Log), error);
}
/// <summary>
/// When overridden in a subclass, ends an asynchronous version
/// of <see cref="Log"/>.
/// </summary>
public virtual string EndLog(IAsyncResult asyncResult)
{
return (string) EndSyncImpl(asyncResult);
}
private delegate string LogHandler(Error error);
/// <summary>
/// Retrieves a single application error from log given its
/// identifier, or null if it does not exist.
/// </summary>
public abstract ErrorLogEntry GetError(string id);
/// <summary>
/// When overridden in a subclass, begins an asynchronous version
/// of <see cref="GetError"/>.
/// </summary>
public virtual IAsyncResult BeginGetError(string id, AsyncCallback asyncCallback, object asyncState)
{
return BeginSyncImpl(asyncCallback, asyncState, new GetErrorHandler(GetError), id);
}
/// <summary>
/// When overridden in a subclass, ends an asynchronous version
/// of <see cref="GetError"/>.
/// </summary>
public virtual ErrorLogEntry EndGetError(IAsyncResult asyncResult)
{
return (ErrorLogEntry) EndSyncImpl(asyncResult);
}
private delegate ErrorLogEntry GetErrorHandler(string id);
/// <summary>
/// Retrieves a page of application errors from the log in
/// descending order of logged time.
/// </summary>
public abstract int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList);
/// <summary>
/// When overridden in a subclass, begins an asynchronous version
/// of <see cref="GetErrors"/>.
/// </summary>
public virtual IAsyncResult BeginGetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList, AsyncCallback asyncCallback, object asyncState)
{
return BeginSyncImpl(asyncCallback, asyncState, new GetErrorsHandler(GetErrors), pageIndex, pageSize, errorEntryList);
}
/// <summary>
/// When overridden in a subclass, ends an asynchronous version
/// of <see cref="GetErrors"/>.
/// </summary>
public virtual int EndGetErrors(IAsyncResult asyncResult)
{
return (int) EndSyncImpl(asyncResult);
}
private delegate int GetErrorsHandler(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList);
/// <summary>
/// Get the name of this log.
/// </summary>
public virtual string Name
{
get { return GetType().Name; }
}
/// <summary>
/// Gets the name of the application to which the log is scoped.
/// </summary>
public string ApplicationName
{
get { return _appName ?? string.Empty; }
set
{
if (_appNameInitialized)
throw new InvalidOperationException("The application name cannot be reset once initialized.");
_appName = value;
_appNameInitialized = (value ?? string.Empty).Length > 0;
}
}
/// <summary>
/// Gets the default error log implementation specified in the
/// configuration file, or the in-memory log implemention if
/// none is configured.
/// </summary>
public static ErrorLog GetDefault(HttpContext context)
{
ErrorLog log;
if (context != null)
{
log = (ErrorLog) context.Items[_contextKey];
if (log != null)
return log;
}
//
// Determine the default store type from the configuration and
// create an instance of it.
//
// If no object got created (probably because the right
// configuration settings are missing) then default to
// the in-memory log implementation.
//
log = (ErrorLog) SimpleServiceProviderFactory.CreateFromConfigSection(Configuration.GroupSlash + "errorLog")
?? new MemoryErrorLog();
if (context != null)
{
//
// Infer the application name from the context if it has not
// been initialized so far.
//
if (log.ApplicationName.Length == 0)
log.ApplicationName = InferApplicationName(context);
//
// Save into the context if context is there so retrieval is
// quick next time.
//
context.Items[_contextKey] = log;
}
return log;
}
private static string InferApplicationName(HttpContext context)
{
Debug.Assert(context != null);
//
// Setup the application name (ASP.NET 2.0 or later).
//
string appName = null;
if (context.Request != null)
{
//
// ASP.NET 2.0 returns a different and more cryptic value
// for HttpRuntime.AppDomainAppId comared to previous
// versions. Also HttpRuntime.AppDomainAppId is not available
// in partial trust environments. However, the APPL_MD_PATH
// server variable yields the same value as
// HttpRuntime.AppDomainAppId did previously so we try to
// get to it over here for compatibility reasons (otherwise
// folks upgrading to this version of ELMAH could find their
// error log empty due to change in application name.
//
appName = context.Request.ServerVariables["APPL_MD_PATH"];
}
if (string.IsNullOrEmpty(appName))
{
//
// Still no luck? Try HttpRuntime.AppDomainAppVirtualPath,
// which is available even under partial trust.
//
appName = HttpRuntime.AppDomainAppVirtualPath;
}
return Mask.EmptyString(appName, "/");
}
//
// The following two methods are helpers that provide boilerplate
// implementations for implementing asnychronous BeginXXXX and
// EndXXXX methods over a default synchronous implementation.
//
private static IAsyncResult BeginSyncImpl(AsyncCallback asyncCallback, object asyncState, Delegate syncImpl, params object[] args)
{
Debug.Assert(syncImpl != null);
SynchronousAsyncResult asyncResult;
var syncMethodName = syncImpl.Method.Name;
try
{
asyncResult = SynchronousAsyncResult.OnSuccess(syncMethodName, asyncState,
syncImpl.DynamicInvoke(args));
}
catch (Exception e)
{
asyncResult = SynchronousAsyncResult.OnFailure(syncMethodName, asyncState, e);
}
if (asyncCallback != null)
asyncCallback(asyncResult);
return asyncResult;
}
private static object EndSyncImpl(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException("asyncResult");
var syncResult = asyncResult as SynchronousAsyncResult;
if (syncResult == null)
throw new ArgumentException("IAsyncResult object did not come from the corresponding async method on this type.", "asyncResult");
//
// IMPORTANT! The End method on SynchronousAsyncResult will
// throw an exception if that's what Log did when
// BeginLog called it. The unforunate side effect of this is
// the stack trace information for the exception is lost and
// reset to this point. There seems to be a basic failure in the
// framework to accommodate for this case more generally. One
// could handle this through a custom exception that wraps the
// original exception, but this assumes that an invocation will
// only throw an exception of that custom type.
//
return syncResult.End();
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.Linq;
using Moq;
using Prism.Ioc;
using Prism.Regions;
using Prism.Wpf.Tests.Mocks;
using Xunit;
namespace Prism.Wpf.Tests.Regions
{
public class RegionFixture
{
[Fact]
public void WhenRegionConstructed_SortComparisonIsDefault()
{
IRegion region = new Region();
Assert.NotNull(region.SortComparison);
Assert.Equal(region.SortComparison, Region.DefaultSortComparison);
}
[Fact]
public void CanAddContentToRegion()
{
IRegion region = new Region();
Assert.Empty(region.Views.Cast<object>());
region.Add(new object());
Assert.Single(region.Views.Cast<object>());
}
[Fact]
public void CanRemoveContentFromRegion()
{
IRegion region = new Region();
object view = new object();
region.Add(view);
region.Remove(view);
Assert.Empty(region.Views.Cast<object>());
}
[Fact]
public void RemoveInexistentViewThrows()
{
var ex = Assert.Throws<ArgumentException>(() =>
{
IRegion region = new Region();
object view = new object();
region.Remove(view);
Assert.Empty(region.Views.Cast<object>());
});
}
[Fact]
public void RegionExposesCollectionOfContainedViews()
{
IRegion region = new Region();
object view = new object();
region.Add(view);
var views = region.Views;
Assert.NotNull(views);
Assert.Single(views.Cast<object>());
Assert.Same(view, views.Cast<object>().ElementAt(0));
}
[Fact]
public void CanAddAndRetrieveNamedViewInstance()
{
IRegion region = new Region();
object myView = new object();
region.Add(myView, "MyView");
object returnedView = region.GetView("MyView");
Assert.NotNull(returnedView);
Assert.Same(returnedView, myView);
}
[Fact]
public void AddingDuplicateNamedViewThrows()
{
var ex = Assert.Throws<InvalidOperationException>(() =>
{
IRegion region = new Region();
region.Add(new object(), "MyView");
region.Add(new object(), "MyView");
});
}
[Fact]
public void AddNamedViewIsAlsoListedInViewsCollection()
{
IRegion region = new Region();
object myView = new object();
region.Add(myView, "MyView");
Assert.Single(region.Views.Cast<object>());
Assert.Same(myView, region.Views.Cast<object>().ElementAt(0));
}
[Fact]
public void GetViewReturnsNullWhenViewDoesNotExistInRegion()
{
IRegion region = new Region();
Assert.Null(region.GetView("InexistentView"));
}
[Fact]
public void GetViewWithNullOrEmptyStringThrows()
{
var ex = Assert.Throws<ArgumentException>(() =>
{
IRegion region = new Region();
region.GetView(string.Empty);
});
}
[Fact]
public void AddNamedViewWithNullOrEmptyStringNameThrows()
{
var ex = Assert.Throws<ArgumentException>(() =>
{
IRegion region = new Region();
region.Add(new object(), string.Empty);
});
}
[Fact]
public void GetViewReturnsNullAfterRemovingViewFromRegion()
{
IRegion region = new Region();
object myView = new object();
region.Add(myView, "MyView");
region.Remove(myView);
Assert.Null(region.GetView("MyView"));
}
[Fact]
public void AddViewPassesSameScopeByDefaultToView()
{
var regionManager = new MockRegionManager();
IRegion region = new Region();
region.RegionManager = regionManager;
var myView = new MockDependencyObject();
region.Add(myView);
Assert.Same(regionManager, myView.GetValue(RegionManager.RegionManagerProperty));
}
[Fact]
public void AddViewPassesSameScopeByDefaultToNamedView()
{
var regionManager = new MockRegionManager();
IRegion region = new Region();
region.RegionManager = regionManager;
var myView = new MockDependencyObject();
region.Add(myView, "MyView");
Assert.Same(regionManager, myView.GetValue(RegionManager.RegionManagerProperty));
}
[Fact]
public void AddViewPassesDiferentScopeWhenAdding()
{
var regionManager = new MockRegionManager();
IRegion region = new Region();
region.RegionManager = regionManager;
var myView = new MockDependencyObject();
region.Add(myView, "MyView", true);
Assert.NotSame(regionManager, myView.GetValue(RegionManager.RegionManagerProperty));
}
[Fact]
public void CreatingNewScopesAsksTheRegionManagerForNewInstance()
{
var regionManager = new MockRegionManager();
IRegion region = new Region();
region.RegionManager = regionManager;
var myView = new object();
region.Add(myView, "MyView", true);
Assert.True(regionManager.CreateRegionManagerCalled);
}
[Fact]
public void AddViewReturnsExistingRegionManager()
{
var regionManager = new MockRegionManager();
IRegion region = new Region();
region.RegionManager = regionManager;
var myView = new object();
var returnedRegionManager = region.Add(myView, "MyView", false);
Assert.Same(regionManager, returnedRegionManager);
}
[Fact]
public void AddViewReturnsNewRegionManager()
{
var regionManager = new MockRegionManager();
IRegion region = new Region();
region.RegionManager = regionManager;
var myView = new object();
var returnedRegionManager = region.Add(myView, "MyView", true);
Assert.NotSame(regionManager, returnedRegionManager);
}
[Fact]
public void AddingNonDependencyObjectToRegionDoesNotThrow()
{
IRegion region = new Region();
object model = new object();
region.Add(model);
Assert.Single(region.Views.Cast<object>());
}
[Fact]
public void ActivateNonAddedViewThrows()
{
var ex = Assert.Throws<ArgumentException>(() =>
{
IRegion region = new Region();
object nonAddedView = new object();
region.Activate(nonAddedView);
});
}
[Fact]
public void DeactivateNonAddedViewThrows()
{
var ex = Assert.Throws<ArgumentException>(() =>
{
IRegion region = new Region();
object nonAddedView = new object();
region.Deactivate(nonAddedView);
});
}
[Fact]
public void ActivateNullViewThrows()
{
var ex = Assert.Throws<ArgumentNullException>(() =>
{
IRegion region = new Region();
region.Activate(null);
});
}
[Fact]
public void AddViewRaisesCollectionViewEvent()
{
bool viewAddedCalled = false;
IRegion region = new Region();
region.Views.CollectionChanged += (sender, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Add)
viewAddedCalled = true;
};
object model = new object();
Assert.False(viewAddedCalled);
region.Add(model);
Assert.True(viewAddedCalled);
}
[Fact]
public void ViewAddedEventPassesTheViewAddedInTheEventArgs()
{
object viewAdded = null;
IRegion region = new Region();
region.Views.CollectionChanged += (sender, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
viewAdded = e.NewItems[0];
}
};
object model = new object();
Assert.Null(viewAdded);
region.Add(model);
Assert.NotNull(viewAdded);
Assert.Same(model, viewAdded);
}
[Fact]
public void RemoveViewFiresViewRemovedEvent()
{
bool viewRemoved = false;
IRegion region = new Region();
object model = new object();
region.Views.CollectionChanged += (sender, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Remove)
viewRemoved = true;
};
region.Add(model);
Assert.False(viewRemoved);
region.Remove(model);
Assert.True(viewRemoved);
}
[Fact]
public void ViewRemovedEventPassesTheViewRemovedInTheEventArgs()
{
object removedView = null;
IRegion region = new Region();
region.Views.CollectionChanged += (sender, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Remove)
removedView = e.OldItems[0];
};
object model = new object();
region.Add(model);
Assert.Null(removedView);
region.Remove(model);
Assert.Same(model, removedView);
}
[Fact]
public void ShowViewFiresViewShowedEvent()
{
bool viewActivated = false;
IRegion region = new Region();
object model = new object();
region.ActiveViews.CollectionChanged += (o, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems.Contains(model))
viewActivated = true;
};
region.Add(model);
Assert.False(viewActivated);
region.Activate(model);
Assert.True(viewActivated);
}
[Fact]
public void AddingSameViewTwiceThrows()
{
object view = new object();
IRegion region = new Region();
region.Add(view);
try
{
region.Add(view);
//Assert.Fail();
}
catch (InvalidOperationException ex)
{
Assert.Equal("View already exists in region.", ex.Message);
}
catch
{
//Assert.Fail();
}
}
[Fact]
public void RemovingViewAlsoRemovesItFromActiveViews()
{
IRegion region = new Region();
object model = new object();
region.Add(model);
region.Activate(model);
Assert.True(region.ActiveViews.Contains(model));
region.Remove(model);
Assert.False(region.ActiveViews.Contains(model));
}
[Fact]
public void ShouldGetNotificationWhenContextChanges()
{
IRegion region = new Region();
bool contextChanged = false;
region.PropertyChanged += (s, args) => { if (args.PropertyName == "Context") contextChanged = true; };
region.Context = "MyNewContext";
Assert.True(contextChanged);
}
[Fact]
public void ChangingNameOnceItIsSetThrows()
{
var ex = Assert.Throws<InvalidOperationException>(() =>
{
var region = new Region
{
Name = "MyRegion"
};
region.Name = "ChangedRegionName";
});
}
private class MockRegionManager : IRegionManager
{
public bool CreateRegionManagerCalled;
public IRegionManager CreateRegionManager()
{
CreateRegionManagerCalled = true;
return new MockRegionManager();
}
public IRegionManager AddToRegion(string regionName, object view)
{
throw new NotImplementedException();
}
public IRegionManager RegisterViewWithRegion(string regionName, Type viewType)
{
throw new NotImplementedException();
}
public IRegionManager RegisterViewWithRegion(string regionName, Func<object> getContentDelegate)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, Uri source, Action<NavigationResult> navigationCallback)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, Uri source)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, string source, Action<NavigationResult> navigationCallback)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, string source)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, Uri target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, string target, Action<NavigationResult> navigationCallback, NavigationParameters navigationParameters)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, Uri target, NavigationParameters navigationParameters)
{
throw new NotImplementedException();
}
public void RequestNavigate(string regionName, string target, NavigationParameters navigationParameters)
{
throw new NotImplementedException();
}
public IRegionCollection Regions
{
get { throw new NotImplementedException(); }
}
public IRegion AttachNewRegion(object regionTarget, string regionName)
{
throw new NotImplementedException();
}
public bool Navigate(Uri source)
{
throw new NotImplementedException();
}
public IRegionManager AddToRegion(string regionName, string viewName)
{
throw new NotImplementedException();
}
public IRegionManager RegisterViewWithRegion(string regionName, string viewName)
{
throw new NotImplementedException();
}
}
[Fact]
public void NavigateDelegatesToIRegionNavigationService()
{
try
{
// Prepare
IRegion region = new Region();
object view = new object();
region.Add(view);
Uri uri = new Uri(view.GetType().Name, UriKind.Relative);
Action<NavigationResult> navigationCallback = nr => { };
NavigationParameters navigationParameters = new NavigationParameters();
Mock<IRegionNavigationService> mockRegionNavigationService = new Mock<IRegionNavigationService>();
mockRegionNavigationService.Setup(x => x.RequestNavigate(uri, navigationCallback, navigationParameters)).Verifiable();
var containerMock = new Mock<IContainerExtension>();
containerMock.Setup(x => x.Resolve(typeof(IRegionNavigationService))).Returns(mockRegionNavigationService.Object);
ContainerLocator.ResetContainer();
ContainerLocator.SetContainerExtension(() => containerMock.Object);
// Act
region.RequestNavigate(uri, navigationCallback, navigationParameters);
// Verify
mockRegionNavigationService.VerifyAll();
}
finally
{
ContainerLocator.ResetContainer();
}
}
[Fact]
public void WhenViewsWithSortHintsAdded_RegionSortsViews()
{
IRegion region = new Region();
object view1 = new ViewOrder1();
object view2 = new ViewOrder2();
object view3 = new ViewOrder3();
region.Add(view1);
region.Add(view2);
region.Add(view3);
Assert.Equal(3, region.Views.Count());
Assert.Same(view2, region.Views.ElementAt(0));
Assert.Same(view3, region.Views.ElementAt(1));
Assert.Same(view1, region.Views.ElementAt(2));
}
[StaFact]
public void WhenViewHasBeenRemovedAndRegionManagerPropertyCleared_ThenItCanBeAddedAgainToARegion()
{
IRegion region = new Region { RegionManager = new MockRegionManager() };
var view = new MockFrameworkElement();
var scopedRegionManager = region.Add(view, null, true);
Assert.Equal(view, region.Views.First());
region.Remove(view);
view.ClearValue(RegionManager.RegionManagerProperty);
Assert.Empty(region.Views.Cast<object>());
var newScopedRegion = region.Add(view, null, true);
Assert.Equal(view, region.Views.First());
Assert.Same(newScopedRegion, view.GetValue(RegionManager.RegionManagerProperty));
}
[ViewSortHint("C")]
private class ViewOrder1 { };
[ViewSortHint("A")]
private class ViewOrder2 { };
[ViewSortHint("B")]
private class ViewOrder3 { };
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
using GSF.ASN1.Types;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Choice(Name = "VariableSpecification")]
public class VariableSpecification : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(VariableSpecification));
private Address address_;
private bool address_selected;
private NullObject invalidated_;
private bool invalidated_selected;
private ObjectName name_;
private bool name_selected;
private ScatteredAccessDescription scatteredAccessDescription_;
private bool scatteredAccessDescription_selected;
private VariableDescriptionSequenceType variableDescription_;
private bool variableDescription_selected;
[ASN1Element(Name = "name", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public ObjectName Name
{
get
{
return name_;
}
set
{
selectName(value);
}
}
[ASN1Element(Name = "address", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public Address Address
{
get
{
return address_;
}
set
{
selectAddress(value);
}
}
[ASN1Element(Name = "variableDescription", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public VariableDescriptionSequenceType VariableDescription
{
get
{
return variableDescription_;
}
set
{
selectVariableDescription(value);
}
}
[ASN1Element(Name = "scatteredAccessDescription", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public ScatteredAccessDescription ScatteredAccessDescription
{
get
{
return scatteredAccessDescription_;
}
set
{
selectScatteredAccessDescription(value);
}
}
[ASN1Null(Name = "invalidated")]
[ASN1Element(Name = "invalidated", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public NullObject Invalidated
{
get
{
return invalidated_;
}
set
{
selectInvalidated(value);
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isNameSelected()
{
return name_selected;
}
public void selectName(ObjectName val)
{
name_ = val;
name_selected = true;
address_selected = false;
variableDescription_selected = false;
scatteredAccessDescription_selected = false;
invalidated_selected = false;
}
public bool isAddressSelected()
{
return address_selected;
}
public void selectAddress(Address val)
{
address_ = val;
address_selected = true;
name_selected = false;
variableDescription_selected = false;
scatteredAccessDescription_selected = false;
invalidated_selected = false;
}
public bool isVariableDescriptionSelected()
{
return variableDescription_selected;
}
public void selectVariableDescription(VariableDescriptionSequenceType val)
{
variableDescription_ = val;
variableDescription_selected = true;
name_selected = false;
address_selected = false;
scatteredAccessDescription_selected = false;
invalidated_selected = false;
}
public bool isScatteredAccessDescriptionSelected()
{
return scatteredAccessDescription_selected;
}
public void selectScatteredAccessDescription(ScatteredAccessDescription val)
{
scatteredAccessDescription_ = val;
scatteredAccessDescription_selected = true;
name_selected = false;
address_selected = false;
variableDescription_selected = false;
invalidated_selected = false;
}
public bool isInvalidatedSelected()
{
return invalidated_selected;
}
public void selectInvalidated()
{
selectInvalidated(new NullObject());
}
public void selectInvalidated(NullObject val)
{
invalidated_ = val;
invalidated_selected = true;
name_selected = false;
address_selected = false;
variableDescription_selected = false;
scatteredAccessDescription_selected = false;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "variableDescription", IsSet = false)]
public class VariableDescriptionSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(VariableDescriptionSequenceType));
private Address address_;
private TypeSpecification typeSpecification_;
[ASN1Element(Name = "address", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public Address Address
{
get
{
return address_;
}
set
{
address_ = value;
}
}
[ASN1Element(Name = "typeSpecification", IsOptional = false, HasTag = false, HasDefaultValue = false)]
public TypeSpecification TypeSpecification
{
get
{
return typeSpecification_;
}
set
{
typeSpecification_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.TextManager.Interop;
namespace Microsoft.VisualStudio.Project
{
internal static class NativeMethods
{
// IIDS
public static readonly Guid IID_IUnknown = new Guid("{00000000-0000-0000-C000-000000000046}");
public const int
CLSCTX_INPROC_SERVER = 0x1;
public const int
S_FALSE = 0x00000001,
S_OK = 0x00000000,
IDOK = 1,
IDCANCEL = 2,
IDABORT = 3,
IDRETRY = 4,
IDIGNORE = 5,
IDYES = 6,
IDNO = 7,
IDCLOSE = 8,
IDHELP = 9,
IDTRYAGAIN = 10,
IDCONTINUE = 11,
OLECMDERR_E_NOTSUPPORTED = unchecked((int)0x80040100),
OLECMDERR_E_UNKNOWNGROUP = unchecked((int)0x80040104),
UNDO_E_CLIENTABORT = unchecked((int)0x80044001),
E_OUTOFMEMORY = unchecked((int)0x8007000E),
E_INVALIDARG = unchecked((int)0x80070057),
E_FAIL = unchecked((int)0x80004005),
E_NOINTERFACE = unchecked((int)0x80004002),
E_POINTER = unchecked((int)0x80004003),
E_NOTIMPL = unchecked((int)0x80004001),
E_UNEXPECTED = unchecked((int)0x8000FFFF),
E_HANDLE = unchecked((int)0x80070006),
E_ABORT = unchecked((int)0x80004004),
E_ACCESSDENIED = unchecked((int)0x80070005),
E_PENDING = unchecked((int)0x8000000A);
public const int
OLECLOSE_SAVEIFDIRTY = 0,
OLECLOSE_NOSAVE = 1,
OLECLOSE_PROMPTSAVE = 2;
public const int
OLEIVERB_PRIMARY = 0,
OLEIVERB_SHOW = -1,
OLEIVERB_OPEN = -2,
OLEIVERB_HIDE = -3,
OLEIVERB_UIACTIVATE = -4,
OLEIVERB_INPLACEACTIVATE = -5,
OLEIVERB_DISCARDUNDOSTATE = -6,
OLEIVERB_PROPERTIES = -7;
public const int
OFN_READONLY = unchecked((int)0x00000001),
OFN_OVERWRITEPROMPT = unchecked((int)0x00000002),
OFN_HIDEREADONLY = unchecked((int)0x00000004),
OFN_NOCHANGEDIR = unchecked((int)0x00000008),
OFN_SHOWHELP = unchecked((int)0x00000010),
OFN_ENABLEHOOK = unchecked((int)0x00000020),
OFN_ENABLETEMPLATE = unchecked((int)0x00000040),
OFN_ENABLETEMPLATEHANDLE = unchecked((int)0x00000080),
OFN_NOVALIDATE = unchecked((int)0x00000100),
OFN_ALLOWMULTISELECT = unchecked((int)0x00000200),
OFN_EXTENSIONDIFFERENT = unchecked((int)0x00000400),
OFN_PATHMUSTEXIST = unchecked((int)0x00000800),
OFN_FILEMUSTEXIST = unchecked((int)0x00001000),
OFN_CREATEPROMPT = unchecked((int)0x00002000),
OFN_SHAREAWARE = unchecked((int)0x00004000),
OFN_NOREADONLYRETURN = unchecked((int)0x00008000),
OFN_NOTESTFILECREATE = unchecked((int)0x00010000),
OFN_NONETWORKBUTTON = unchecked((int)0x00020000),
OFN_NOLONGNAMES = unchecked((int)0x00040000),
OFN_EXPLORER = unchecked((int)0x00080000),
OFN_NODEREFERENCELINKS = unchecked((int)0x00100000),
OFN_LONGNAMES = unchecked((int)0x00200000),
OFN_ENABLEINCLUDENOTIFY = unchecked((int)0x00400000),
OFN_ENABLESIZING = unchecked((int)0x00800000),
OFN_USESHELLITEM = unchecked((int)0x01000000),
OFN_DONTADDTORECENT = unchecked((int)0x02000000),
OFN_FORCESHOWHIDDEN = unchecked((int)0x10000000);
// for READONLYSTATUS
public const int
ROSTATUS_NotReadOnly = 0x0,
ROSTATUS_ReadOnly = 0x1,
ROSTATUS_Unknown = unchecked((int)0xFFFFFFFF);
public const int
IEI_DoNotLoadDocData = 0x10000000;
public const int
CB_SETDROPPEDWIDTH = 0x0160,
GWL_STYLE = (-16),
GWL_EXSTYLE = (-20),
DWL_MSGRESULT = 0,
SW_SHOWNORMAL = 1,
HTMENU = 5,
WS_POPUP = unchecked((int)0x80000000),
WS_CHILD = 0x40000000,
WS_MINIMIZE = 0x20000000,
WS_VISIBLE = 0x10000000,
WS_DISABLED = 0x08000000,
WS_CLIPSIBLINGS = 0x04000000,
WS_CLIPCHILDREN = 0x02000000,
WS_MAXIMIZE = 0x01000000,
WS_CAPTION = 0x00C00000,
WS_BORDER = 0x00800000,
WS_DLGFRAME = 0x00400000,
WS_VSCROLL = 0x00200000,
WS_HSCROLL = 0x00100000,
WS_SYSMENU = 0x00080000,
WS_THICKFRAME = 0x00040000,
WS_TABSTOP = 0x00010000,
WS_MINIMIZEBOX = 0x00020000,
WS_MAXIMIZEBOX = 0x00010000,
WS_EX_DLGMODALFRAME = 0x00000001,
WS_EX_MDICHILD = 0x00000040,
WS_EX_TOOLWINDOW = 0x00000080,
WS_EX_CLIENTEDGE = 0x00000200,
WS_EX_CONTEXTHELP = 0x00000400,
WS_EX_RIGHT = 0x00001000,
WS_EX_LEFT = 0x00000000,
WS_EX_RTLREADING = 0x00002000,
WS_EX_LEFTSCROLLBAR = 0x00004000,
WS_EX_CONTROLPARENT = 0x00010000,
WS_EX_STATICEDGE = 0x00020000,
WS_EX_APPWINDOW = 0x00040000,
WS_EX_LAYERED = 0x00080000,
WS_EX_TOPMOST = 0x00000008,
WS_EX_NOPARENTNOTIFY = 0x00000004,
LVM_SETEXTENDEDLISTVIEWSTYLE = (0x1000 + 54),
LVS_EX_LABELTIP = 0x00004000,
// winuser.h
WH_JOURNALPLAYBACK = 1,
WH_GETMESSAGE = 3,
WH_MOUSE = 7,
WSF_VISIBLE = 0x0001,
WM_NULL = 0x0000,
WM_CREATE = 0x0001,
WM_DELETEITEM = 0x002D,
WM_DESTROY = 0x0002,
WM_MOVE = 0x0003,
WM_SIZE = 0x0005,
WM_ACTIVATE = 0x0006,
WA_INACTIVE = 0,
WA_ACTIVE = 1,
WA_CLICKACTIVE = 2,
WM_SETFOCUS = 0x0007,
WM_KILLFOCUS = 0x0008,
WM_ENABLE = 0x000A,
WM_SETREDRAW = 0x000B,
WM_SETTEXT = 0x000C,
WM_GETTEXT = 0x000D,
WM_GETTEXTLENGTH = 0x000E,
WM_PAINT = 0x000F,
WM_CLOSE = 0x0010,
WM_QUERYENDSESSION = 0x0011,
WM_QUIT = 0x0012,
WM_QUERYOPEN = 0x0013,
WM_ERASEBKGND = 0x0014,
WM_SYSCOLORCHANGE = 0x0015,
WM_ENDSESSION = 0x0016,
WM_SHOWWINDOW = 0x0018,
WM_WININICHANGE = 0x001A,
WM_SETTINGCHANGE = 0x001A,
WM_DEVMODECHANGE = 0x001B,
WM_ACTIVATEAPP = 0x001C,
WM_FONTCHANGE = 0x001D,
WM_TIMECHANGE = 0x001E,
WM_CANCELMODE = 0x001F,
WM_SETCURSOR = 0x0020,
WM_MOUSEACTIVATE = 0x0021,
WM_CHILDACTIVATE = 0x0022,
WM_QUEUESYNC = 0x0023,
WM_GETMINMAXINFO = 0x0024,
WM_PAINTICON = 0x0026,
WM_ICONERASEBKGND = 0x0027,
WM_NEXTDLGCTL = 0x0028,
WM_SPOOLERSTATUS = 0x002A,
WM_DRAWITEM = 0x002B,
WM_MEASUREITEM = 0x002C,
WM_VKEYTOITEM = 0x002E,
WM_CHARTOITEM = 0x002F,
WM_SETFONT = 0x0030,
WM_GETFONT = 0x0031,
WM_SETHOTKEY = 0x0032,
WM_GETHOTKEY = 0x0033,
WM_QUERYDRAGICON = 0x0037,
WM_COMPAREITEM = 0x0039,
WM_GETOBJECT = 0x003D,
WM_COMPACTING = 0x0041,
WM_COMMNOTIFY = 0x0044,
WM_WINDOWPOSCHANGING = 0x0046,
WM_WINDOWPOSCHANGED = 0x0047,
WM_POWER = 0x0048,
WM_COPYDATA = 0x004A,
WM_CANCELJOURNAL = 0x004B,
WM_NOTIFY = 0x004E,
WM_INPUTLANGCHANGEREQUEST = 0x0050,
WM_INPUTLANGCHANGE = 0x0051,
WM_TCARD = 0x0052,
WM_HELP = 0x0053,
WM_USERCHANGED = 0x0054,
WM_NOTIFYFORMAT = 0x0055,
WM_CONTEXTMENU = 0x007B,
WM_STYLECHANGING = 0x007C,
WM_STYLECHANGED = 0x007D,
WM_DISPLAYCHANGE = 0x007E,
WM_GETICON = 0x007F,
WM_SETICON = 0x0080,
WM_NCCREATE = 0x0081,
WM_NCDESTROY = 0x0082,
WM_NCCALCSIZE = 0x0083,
WM_NCHITTEST = 0x0084,
WM_NCPAINT = 0x0085,
WM_NCACTIVATE = 0x0086,
WM_GETDLGCODE = 0x0087,
WM_NCMOUSEMOVE = 0x00A0,
WM_NCLBUTTONDOWN = 0x00A1,
WM_NCLBUTTONUP = 0x00A2,
WM_NCLBUTTONDBLCLK = 0x00A3,
WM_NCRBUTTONDOWN = 0x00A4,
WM_NCRBUTTONUP = 0x00A5,
WM_NCRBUTTONDBLCLK = 0x00A6,
WM_NCMBUTTONDOWN = 0x00A7,
WM_NCMBUTTONUP = 0x00A8,
WM_NCMBUTTONDBLCLK = 0x00A9,
WM_NCXBUTTONDOWN = 0x00AB,
WM_NCXBUTTONUP = 0x00AC,
WM_NCXBUTTONDBLCLK = 0x00AD,
WM_KEYFIRST = 0x0100,
WM_KEYDOWN = 0x0100,
WM_KEYUP = 0x0101,
WM_CHAR = 0x0102,
WM_DEADCHAR = 0x0103,
WM_CTLCOLOR = 0x0019,
WM_SYSKEYDOWN = 0x0104,
WM_SYSKEYUP = 0x0105,
WM_SYSCHAR = 0x0106,
WM_SYSDEADCHAR = 0x0107,
WM_KEYLAST = 0x0108,
WM_IME_STARTCOMPOSITION = 0x010D,
WM_IME_ENDCOMPOSITION = 0x010E,
WM_IME_COMPOSITION = 0x010F,
WM_IME_KEYLAST = 0x010F,
WM_INITDIALOG = 0x0110,
WM_COMMAND = 0x0111,
WM_SYSCOMMAND = 0x0112,
WM_TIMER = 0x0113,
WM_HSCROLL = 0x0114,
WM_VSCROLL = 0x0115,
WM_INITMENU = 0x0116,
WM_INITMENUPOPUP = 0x0117,
WM_MENUSELECT = 0x011F,
WM_MENUCHAR = 0x0120,
WM_ENTERIDLE = 0x0121,
WM_CHANGEUISTATE = 0x0127,
WM_UPDATEUISTATE = 0x0128,
WM_QUERYUISTATE = 0x0129,
WM_CTLCOLORMSGBOX = 0x0132,
WM_CTLCOLOREDIT = 0x0133,
WM_CTLCOLORLISTBOX = 0x0134,
WM_CTLCOLORBTN = 0x0135,
WM_CTLCOLORDLG = 0x0136,
WM_CTLCOLORSCROLLBAR = 0x0137,
WM_CTLCOLORSTATIC = 0x0138,
WM_MOUSEFIRST = 0x0200,
WM_MOUSEMOVE = 0x0200,
WM_LBUTTONDOWN = 0x0201,
WM_LBUTTONUP = 0x0202,
WM_LBUTTONDBLCLK = 0x0203,
WM_RBUTTONDOWN = 0x0204,
WM_RBUTTONUP = 0x0205,
WM_RBUTTONDBLCLK = 0x0206,
WM_MBUTTONDOWN = 0x0207,
WM_MBUTTONUP = 0x0208,
WM_MBUTTONDBLCLK = 0x0209,
WM_XBUTTONDOWN = 0x020B,
WM_XBUTTONUP = 0x020C,
WM_XBUTTONDBLCLK = 0x020D,
WM_MOUSEWHEEL = 0x020A,
WM_MOUSELAST = 0x020A,
WM_PARENTNOTIFY = 0x0210,
WM_ENTERMENULOOP = 0x0211,
WM_EXITMENULOOP = 0x0212,
WM_NEXTMENU = 0x0213,
WM_SIZING = 0x0214,
WM_CAPTURECHANGED = 0x0215,
WM_MOVING = 0x0216,
WM_POWERBROADCAST = 0x0218,
WM_DEVICECHANGE = 0x0219,
WM_IME_SETCONTEXT = 0x0281,
WM_IME_NOTIFY = 0x0282,
WM_IME_CONTROL = 0x0283,
WM_IME_COMPOSITIONFULL = 0x0284,
WM_IME_SELECT = 0x0285,
WM_IME_CHAR = 0x0286,
WM_IME_KEYDOWN = 0x0290,
WM_IME_KEYUP = 0x0291,
WM_MDICREATE = 0x0220,
WM_MDIDESTROY = 0x0221,
WM_MDIACTIVATE = 0x0222,
WM_MDIRESTORE = 0x0223,
WM_MDINEXT = 0x0224,
WM_MDIMAXIMIZE = 0x0225,
WM_MDITILE = 0x0226,
WM_MDICASCADE = 0x0227,
WM_MDIICONARRANGE = 0x0228,
WM_MDIGETACTIVE = 0x0229,
WM_MDISETMENU = 0x0230,
WM_ENTERSIZEMOVE = 0x0231,
WM_EXITSIZEMOVE = 0x0232,
WM_DROPFILES = 0x0233,
WM_MDIREFRESHMENU = 0x0234,
WM_MOUSEHOVER = 0x02A1,
WM_MOUSELEAVE = 0x02A3,
WM_CUT = 0x0300,
WM_COPY = 0x0301,
WM_PASTE = 0x0302,
WM_CLEAR = 0x0303,
WM_UNDO = 0x0304,
WM_RENDERFORMAT = 0x0305,
WM_RENDERALLFORMATS = 0x0306,
WM_DESTROYCLIPBOARD = 0x0307,
WM_DRAWCLIPBOARD = 0x0308,
WM_PAINTCLIPBOARD = 0x0309,
WM_VSCROLLCLIPBOARD = 0x030A,
WM_SIZECLIPBOARD = 0x030B,
WM_ASKCBFORMATNAME = 0x030C,
WM_CHANGECBCHAIN = 0x030D,
WM_HSCROLLCLIPBOARD = 0x030E,
WM_QUERYNEWPALETTE = 0x030F,
WM_PALETTEISCHANGING = 0x0310,
WM_PALETTECHANGED = 0x0311,
WM_HOTKEY = 0x0312,
WM_PRINT = 0x0317,
WM_PRINTCLIENT = 0x0318,
WM_HANDHELDFIRST = 0x0358,
WM_HANDHELDLAST = 0x035F,
WM_AFXFIRST = 0x0360,
WM_AFXLAST = 0x037F,
WM_PENWINFIRST = 0x0380,
WM_PENWINLAST = 0x038F,
WM_APP = unchecked((int)0x8000),
WM_USER = 0x0400,
WM_REFLECT =
WM_USER + 0x1C00,
WS_OVERLAPPED = 0x00000000,
WPF_SETMINPOSITION = 0x0001,
WM_CHOOSEFONT_GETLOGFONT = (0x0400 + 1),
WHEEL_DELTA = 120,
DWLP_MSGRESULT = 0,
PSNRET_NOERROR = 0,
PSNRET_INVALID = 1,
PSNRET_INVALID_NOCHANGEPAGE = 2;
public const int
PSN_APPLY = ((0 - 200) - 2),
PSN_KILLACTIVE = ((0 - 200) - 1),
PSN_RESET = ((0 - 200) - 3),
PSN_SETACTIVE = ((0 - 200) - 0);
public const int
GMEM_MOVEABLE = 0x0002,
GMEM_ZEROINIT = 0x0040,
GMEM_DDESHARE = 0x2000;
public const int
SWP_NOACTIVATE = 0x0010,
SWP_NOZORDER = 0x0004,
SWP_NOSIZE = 0x0001,
SWP_NOMOVE = 0x0002,
SWP_FRAMECHANGED = 0x0020;
public const int
TVM_SETINSERTMARK = (0x1100 + 26),
TVM_GETEDITCONTROL = (0x1100 + 15);
public const int
FILE_ATTRIBUTE_READONLY = 0x00000001;
public const int
PSP_DEFAULT = 0x00000000,
PSP_DLGINDIRECT = 0x00000001,
PSP_USEHICON = 0x00000002,
PSP_USEICONID = 0x00000004,
PSP_USETITLE = 0x00000008,
PSP_RTLREADING = 0x00000010,
PSP_HASHELP = 0x00000020,
PSP_USEREFPARENT = 0x00000040,
PSP_USECALLBACK = 0x00000080,
PSP_PREMATURE = 0x00000400,
PSP_HIDEHEADER = 0x00000800,
PSP_USEHEADERTITLE = 0x00001000,
PSP_USEHEADERSUBTITLE = 0x00002000;
public const int
PSH_DEFAULT = 0x00000000,
PSH_PROPTITLE = 0x00000001,
PSH_USEHICON = 0x00000002,
PSH_USEICONID = 0x00000004,
PSH_PROPSHEETPAGE = 0x00000008,
PSH_WIZARDHASFINISH = 0x00000010,
PSH_WIZARD = 0x00000020,
PSH_USEPSTARTPAGE = 0x00000040,
PSH_NOAPPLYNOW = 0x00000080,
PSH_USECALLBACK = 0x00000100,
PSH_HASHELP = 0x00000200,
PSH_MODELESS = 0x00000400,
PSH_RTLREADING = 0x00000800,
PSH_WIZARDCONTEXTHELP = 0x00001000,
PSH_WATERMARK = 0x00008000,
PSH_USEHBMWATERMARK = 0x00010000, // user pass in a hbmWatermark instead of pszbmWatermark
PSH_USEHPLWATERMARK = 0x00020000, //
PSH_STRETCHWATERMARK = 0x00040000, // stretchwatermark also applies for the header
PSH_HEADER = 0x00080000,
PSH_USEHBMHEADER = 0x00100000,
PSH_USEPAGELANG = 0x00200000, // use frame dialog template matched to page
PSH_WIZARD_LITE = 0x00400000,
PSH_NOCONTEXTHELP = 0x02000000;
public const int
PSBTN_BACK = 0,
PSBTN_NEXT = 1,
PSBTN_FINISH = 2,
PSBTN_OK = 3,
PSBTN_APPLYNOW = 4,
PSBTN_CANCEL = 5,
PSBTN_HELP = 6,
PSBTN_MAX = 6;
public const int
TRANSPARENT = 1,
OPAQUE = 2,
FW_BOLD = 700;
[StructLayout(LayoutKind.Sequential)]
public struct NMHDR
{
public IntPtr hwndFrom;
public int idFrom;
public int code;
}
/// <devdoc>
/// Helper class for setting the text parameters to OLECMDTEXT structures.
/// </devdoc>
public static class OLECMDTEXT
{
/// <summary>
/// Flags for the OLE command text
/// </summary>
public enum OLECMDTEXTF
{
/// <summary>No flag</summary>
OLECMDTEXTF_NONE = 0,
/// <summary>The name of the command is required.</summary>
OLECMDTEXTF_NAME = 1,
/// <summary>A description of the status is required.</summary>
OLECMDTEXTF_STATUS = 2
}
}
/// <devdoc>
/// OLECMDF enums for IOleCommandTarget
/// </devdoc>
public enum tagOLECMDF
{
OLECMDF_SUPPORTED = 1,
OLECMDF_ENABLED = 2,
OLECMDF_LATCHED = 4,
OLECMDF_NINCHED = 8,
OLECMDF_INVISIBLE = 16
}
/// <devdoc>
/// This method takes a file URL and converts it to an absolute path. The trick here is that
/// if there is a '#' in the path, everything after this is treated as a fragment. So
/// we need to append the fragment to the end of the path.
/// </devdoc>
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
public static string GetAbsolutePath(string fileName)
{
System.Diagnostics.Debug.Assert(fileName != null && fileName.Length > 0, "Cannot get absolute path, fileName is not valid");
Uri uri = new Uri(fileName);
return uri.LocalPath + uri.Fragment;
}
/// <devdoc>
/// Please use this "approved" method to compare file names.
/// </devdoc>
public static bool IsSamePath(string file1, string file2)
{
if(file1 == null || file1.Length == 0)
{
return (file2 == null || file2.Length == 0);
}
Uri uri1 = null;
Uri uri2 = null;
try
{
if(!Uri.TryCreate(file1, UriKind.Absolute, out uri1) || !Uri.TryCreate(file2, UriKind.Absolute, out uri2))
{
return false;
}
if(uri1 != null && uri1.IsFile && uri2 != null && uri2.IsFile)
{
return 0 == String.Compare(uri1.LocalPath, uri2.LocalPath, StringComparison.OrdinalIgnoreCase);
}
return file1 == file2;
}
catch(UriFormatException e)
{
Trace.WriteLine("Exception " + e.Message);
}
return false;
}
[ComImport(), Guid("9BDA66AE-CA28-4e22-AA27-8A7218A0E3FA"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IEventHandler
{
// converts the underlying codefunction into an event handler for the given event
// if the given event is NULL, then the function will handle no events
[PreserveSig]
int AddHandler(string bstrEventName);
[PreserveSig]
int RemoveHandler(string bstrEventName);
IVsEnumBSTR GetHandledEvents();
bool HandlesEvent(string bstrEventName);
}
[ComImport(), Guid("A55CCBCC-7031-432d-B30A-A68DE7BDAD75"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IParameterKind
{
void SetParameterPassingMode(PARAMETER_PASSING_MODE ParamPassingMode);
void SetParameterArrayDimensions(int uDimensions);
int GetParameterArrayCount();
int GetParameterArrayDimensions(int uIndex);
int GetParameterPassingMode();
}
public enum PARAMETER_PASSING_MODE
{
cmParameterTypeIn = 1,
cmParameterTypeOut = 2,
cmParameterTypeInOut = 3
}
[
ComImport, ComVisible(true), Guid("3E596484-D2E4-461a-A876-254C4F097EBB"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)
]
public interface IMethodXML
{
// Generate XML describing the contents of this function's body.
void GetXML(ref string pbstrXML);
// Parse the incoming XML with respect to the CodeModel XML schema and
// use the result to regenerate the body of the function.
/// <include file='doc\NativeMethods.uex' path='docs/doc[@for="IMethodXML.SetXML"]/*' />
[PreserveSig]
int SetXML(string pszXML);
// This is really a textpoint
[PreserveSig]
int GetBodyPoint([MarshalAs(UnmanagedType.Interface)]out object bodyPoint);
}
[ComImport(), Guid("EA1A87AD-7BC5-4349-B3BE-CADC301F17A3"), InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
public interface IVBFileCodeModelEvents
{
[PreserveSig]
int StartEdit();
[PreserveSig]
int EndEdit();
}
///--------------------------------------------------------------------------
/// ICodeClassBase:
///--------------------------------------------------------------------------
[GuidAttribute("23BBD58A-7C59-449b-A93C-43E59EFC080C")]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport()]
public interface ICodeClassBase
{
[PreserveSig()]
int GetBaseName(out string pBaseName);
}
public const ushort CF_HDROP = 15; // winuser.h
public const uint MK_CONTROL = 0x0008; //winuser.h
public const uint MK_SHIFT = 0x0004;
public const int MAX_PATH = 260; // windef.h
/// <summary>
/// Specifies options for a bitmap image associated with a task item.
/// </summary>
public enum VSTASKBITMAP
{
BMP_COMPILE = -1,
BMP_SQUIGGLE = -2,
BMP_COMMENT = -3,
BMP_SHORTCUT = -4,
BMP_USER = -5
};
public const int ILD_NORMAL = 0x0000,
ILD_TRANSPARENT = 0x0001,
ILD_MASK = 0x0010,
ILD_ROP = 0x0040;
/// <summary>
/// Defines the values that are not supported by the System.Environment.SpecialFolder enumeration
/// </summary>
[ComVisible(true)]
public enum ExtendedSpecialFolder
{
/// <summary>
/// Identical to CSIDL_COMMON_STARTUP
/// </summary>
CommonStartup = 0x0018,
/// <summary>
/// Identical to CSIDL_WINDOWS
/// </summary>
Windows = 0x0024,
}
// APIS
/// <summary>
/// Changes the parent window of the specified child window.
/// </summary>
/// <param name="hWnd">Handle to the child window.</param>
/// <param name="hWndParent">Handle to the new parent window. If this parameter is NULL, the desktop window becomes the new parent window.</param>
/// <returns>A handle to the previous parent window indicates success. NULL indicates failure.</returns>
[DllImport("User32", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern IntPtr SetParent(IntPtr hWnd, IntPtr hWndParent);
[DllImport("user32.dll", ExactSpelling = true, CharSet = CharSet.Auto)]
public static extern bool DestroyIcon(IntPtr handle);
[DllImport("user32.dll", EntryPoint = "IsDialogMessageA", SetLastError = true, CharSet = CharSet.Ansi, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]
public static extern bool IsDialogMessageA(IntPtr hDlg, ref MSG msg);
/// <summary>
/// Indicates whether the file type is binary or not
/// </summary>
/// <param name="lpApplicationName">Full path to the file to check</param>
/// <param name="lpBinaryType">If file isbianry the bitness of the app is indicated by lpBinaryType value.</param>
/// <returns>True if the file is binary false otherwise</returns>
[DllImport("kernel32.dll")]
public static extern bool GetBinaryType([MarshalAs(UnmanagedType.LPWStr)]string lpApplicationName, out uint lpBinaryType);
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.Xml;
namespace System.Management.Automation
{
/// <summary>
/// Class ProviderHelpInfo keeps track of help information to be returned by
/// command help provider.
/// </summary>
internal sealed class ProviderHelpInfo : HelpInfo
{
/// <summary>
/// Constructor for HelpProvider.
/// </summary>
private ProviderHelpInfo(XmlNode xmlNode)
{
MamlNode mamlNode = new MamlNode(xmlNode);
_fullHelpObject = mamlNode.PSObject;
this.Errors = mamlNode.Errors;
_fullHelpObject.TypeNames.Clear();
_fullHelpObject.TypeNames.Add("ProviderHelpInfo");
_fullHelpObject.TypeNames.Add("HelpInfo");
}
#region Basic Help Properties / Methods
/// <summary>
/// Name of the provider for which this provider help info is for.
/// </summary>
/// <value>Name of the provider</value>
internal override string Name
{
get
{
if (_fullHelpObject == null)
return string.Empty;
if (_fullHelpObject.Properties["Name"] == null)
return string.Empty;
if (_fullHelpObject.Properties["Name"].Value == null)
return string.Empty;
string name = _fullHelpObject.Properties["Name"].Value.ToString();
if (name == null)
return string.Empty;
return name.Trim();
}
}
/// <summary>
/// Synopsis in the provider help info.
/// </summary>
/// <value>Synopsis in the provider help info</value>
internal override string Synopsis
{
get
{
if (_fullHelpObject == null)
return string.Empty;
if (_fullHelpObject.Properties["Synopsis"] == null)
return string.Empty;
if (_fullHelpObject.Properties["Synopsis"].Value == null)
return string.Empty;
string synopsis = _fullHelpObject.Properties["Synopsis"].Value.ToString();
if (synopsis == null)
return string.Empty;
return synopsis.Trim();
}
}
/// <summary>
/// Detailed description in the provider help info.
/// </summary>
/// <value>Detailed description in the provider help info</value>
internal string DetailedDescription
{
get
{
if (this.FullHelp == null)
return string.Empty;
if (this.FullHelp.Properties["DetailedDescription"] == null ||
this.FullHelp.Properties["DetailedDescription"].Value == null)
{
return string.Empty;
}
IList descriptionItems = FullHelp.Properties["DetailedDescription"].Value as IList;
if (descriptionItems == null || descriptionItems.Count == 0)
{
return string.Empty;
}
// I think every provider description should atleast have 400 characters...
// so starting with this assumption..I did an average of all the help content
// available at the time of writing this code and came up with this number.
Text.StringBuilder result = new Text.StringBuilder(400);
foreach (object descriptionItem in descriptionItems)
{
PSObject descriptionObject = PSObject.AsPSObject(descriptionItem);
if ((descriptionObject == null) ||
(descriptionObject.Properties["Text"] == null) ||
(descriptionObject.Properties["Text"].Value == null))
{
continue;
}
string text = descriptionObject.Properties["Text"].Value.ToString();
result.Append(text);
result.Append(Environment.NewLine);
}
return result.ToString().Trim();
}
}
/// <summary>
/// Help category for this provider help info, which is constantly HelpCategory.Provider.
/// </summary>
/// <value>Help category for this provider help info</value>
internal override HelpCategory HelpCategory
{
get
{
return HelpCategory.Provider;
}
}
private readonly PSObject _fullHelpObject;
/// <summary>
/// Full help object for this provider help info.
/// </summary>
/// <value>Full help object for this provider help info</value>
internal override PSObject FullHelp
{
get
{
return _fullHelpObject;
}
}
/// <summary>
/// Returns true if help content in help info matches the
/// pattern contained in <paramref name="pattern"/>.
/// The underlying code will usually run pattern.IsMatch() on
/// content it wants to search.
/// Provider help info looks for pattern in Synopsis and
/// DetailedDescription.
/// </summary>
/// <param name="pattern"></param>
/// <returns></returns>
internal override bool MatchPatternInContent(WildcardPattern pattern)
{
Diagnostics.Assert(pattern != null, "pattern cannot be null");
string synopsis = Synopsis;
string detailedDescription = DetailedDescription;
if (synopsis == null)
{
synopsis = string.Empty;
}
if (detailedDescription == null)
{
detailedDescription = string.Empty;
}
return pattern.IsMatch(synopsis) || pattern.IsMatch(detailedDescription);
}
#endregion
#if V2
#region Cmdlet Help and Dynamic Parameter Help
private Hashtable _cmdletHelps;
/// <summary>
/// Return the provider-specific cmdlet help based on input cmdletName.
/// </summary>
/// <param name="cmdletName">CmdletName on which to get provider-specific help.</param>
/// <returns>An mshObject that contains provider-specific commandlet help.</returns>
internal PSObject GetCmdletHelp(string cmdletName)
{
if (string.IsNullOrEmpty(cmdletName))
return null;
LoadCmdletHelps();
if (_cmdletHelps == null)
return null;
return (PSObject)_cmdletHelps[cmdletName];
}
/// <summary>
/// Load provider-specific commandlet helps from xmlNode stored in _fullHelpObject.
/// Result will be stored in a hashtable.
/// </summary>
private void LoadCmdletHelps()
{
if (_cmdletHelps != null)
return;
if (_fullHelpObject == null)
return;
_cmdletHelps = new Hashtable();
if (_fullHelpObject.Properties["Cmdlets"] == null)
return;
PSObject cmdlets = (PSObject)_fullHelpObject.Properties["Cmdlets"].Value;
if (cmdlets == null)
return;
if (cmdlets.Properties["Cmdlet"] == null ||
cmdlets.Properties["Cmdlet"].Value == null)
return;
if (cmdlets.Properties["Cmdlet"].Value.GetType().Equals(typeof(PSObject[])))
{
PSObject[] cmdletHelpItems = (PSObject[])cmdlets.Properties["Cmdlet"].Value;
for (int i = 0; i < cmdletHelpItems.Length; i++)
{
if (cmdletHelpItems[i].Properties["Name"] == null
|| cmdletHelpItems[i].Properties["Name"].Value == null)
return;
string name = ((PSObject)cmdletHelpItems[i].Properties["Name"].Value).ToString();
_cmdletHelps[name] = cmdletHelpItems[i];
}
}
else if (cmdlets.Properties["Cmdlet"].Value.GetType().Equals(typeof(PSObject[])))
{
PSObject cmdletHelpItem = (PSObject)cmdlets.Properties["Cmdlet"].Value;
string name = ((PSObject)cmdletHelpItem.Properties["Name"].Value).ToString();
_cmdletHelps[name] = cmdletHelpItem;
}
}
private Hashtable _dynamicParameterHelps;
/// <summary>
/// Return the provider-specific dynamic parameter help based on input parameter name.
/// </summary>
/// <param name="parameters">An array of parameters to retrieve help.</param>
/// <returns>An array of mshObject that contains the parameter help.</returns>
internal PSObject[] GetDynamicParameterHelp(string[] parameters)
{
if (parameters == null || parameters.Length == 0)
return null;
LoadDynamicParameterHelps();
if (_dynamicParameterHelps == null)
return null;
ArrayList result = new ArrayList();
for (int i = 0; i < parameters.Length; i++)
{
PSObject entry = (PSObject)_dynamicParameterHelps[parameters[i].ToLower()];
if (entry != null)
result.Add(entry);
}
return (PSObject[])result.ToArray(typeof(PSObject));
}
/// <summary>
/// Load provider-specific dynamic parameter helps from xmlNode stored in _fullHelpObject.
/// Result will be stored in a hashtable.
/// </summary>
private void LoadDynamicParameterHelps()
{
if (_dynamicParameterHelps != null)
return;
if (_fullHelpObject == null)
return;
_dynamicParameterHelps = new Hashtable();
if (_fullHelpObject.Properties["DynamicParameters"] == null)
return;
PSObject dynamicParameters = (PSObject)_fullHelpObject.Properties["DynamicParameters"].Value;
if (dynamicParameters == null)
return;
if (dynamicParameters.Properties["DynamicParameter"] == null
|| dynamicParameters.Properties["DynamicParameter"].Value == null)
return;
if (dynamicParameters.Properties["DynamicParameter"].Value.GetType().Equals(typeof(PSObject[])))
{
PSObject[] dynamicParameterHelpItems = (PSObject[])dynamicParameters.Properties["DynamicParameter"].Value;
for (int i = 0; i < dynamicParameterHelpItems.Length; i++)
{
if (dynamicParameterHelpItems[i].Properties["Name"] == null
|| dynamicParameterHelpItems[i].Properties["Name"].Value == null)
return;
string name = ((PSObject)dynamicParameterHelpItems[i].Properties["Name"].Value).ToString();
_dynamicParameterHelps[name] = dynamicParameterHelpItems[i];
}
}
else if (dynamicParameters.Properties["DynamicParameter"].Value.GetType().Equals(typeof(PSObject[])))
{
PSObject dynamicParameterHelpItem = (PSObject)dynamicParameters.Properties["DynamicParameter"].Value;
string name = ((PSObject)dynamicParameterHelpItem.Properties["Name"].Value).ToString();
_dynamicParameterHelps[name] = dynamicParameterHelpItem;
}
}
#endregion
#endif
#region Load Help
/// <summary>
/// Create providerHelpInfo from an xmlNode.
/// </summary>
/// <param name="xmlNode">Xml node that contains the provider help info.</param>
/// <returns>The providerHelpInfo object created.</returns>
internal static ProviderHelpInfo Load(XmlNode xmlNode)
{
ProviderHelpInfo providerHelpInfo = new ProviderHelpInfo(xmlNode);
if (string.IsNullOrEmpty(providerHelpInfo.Name))
return null;
providerHelpInfo.AddCommonHelpProperties();
return providerHelpInfo;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using BTDB.Buffer;
namespace BTDB.KVDBLayer.BTree
{
class BTreeLeafComp : IBTreeLeafNode, IBTreeNode
{
internal readonly long TransactionId;
byte[] _keyBytes;
struct Member
{
internal ushort KeyOffset;
internal ushort KeyLength;
internal uint ValueFileId;
internal uint ValueOfs;
internal int ValueSize; // Negative length means compressed
}
Member[] _keyvalues;
internal const long MaxTotalLen = ushort.MaxValue;
internal const int MaxMembers = 30;
BTreeLeafComp(long transactionId, int length)
{
TransactionId = transactionId;
_keyvalues = new Member[length];
}
internal BTreeLeafComp(long transactionId, BTreeLeafMember[] newKeyValues)
{
Debug.Assert(newKeyValues.Length > 0 && newKeyValues.Length <= MaxMembers);
TransactionId = transactionId;
_keyBytes = new byte[newKeyValues.Sum(m => m.Key.Length)];
_keyvalues = new Member[newKeyValues.Length];
ushort ofs = 0;
for (var i = 0; i < newKeyValues.Length; i++)
{
_keyvalues[i] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort) newKeyValues[i].Key.Length,
ValueFileId = newKeyValues[i].ValueFileId,
ValueOfs = newKeyValues[i].ValueOfs,
ValueSize = newKeyValues[i].ValueSize
};
Array.Copy(newKeyValues[i].Key, 0, _keyBytes, ofs, _keyvalues[i].KeyLength);
ofs += _keyvalues[i].KeyLength;
}
}
BTreeLeafComp(long transactionId, byte[] newKeyBytes, Member[] newKeyValues)
{
TransactionId = transactionId;
_keyBytes = newKeyBytes;
_keyvalues = newKeyValues;
}
internal static IBTreeNode CreateFirst(CreateOrUpdateCtx ctx)
{
Debug.Assert(ctx.WholeKeyLen <= MaxTotalLen);
var result = new BTreeLeafComp(ctx.TransactionId, 1);
result._keyBytes = ctx.WholeKey();
result._keyvalues[0] = new Member
{
KeyOffset = 0,
KeyLength = (ushort) result._keyBytes.Length,
ValueFileId = ctx.ValueFileId,
ValueOfs = ctx.ValueOfs,
ValueSize = ctx.ValueSize
};
return result;
}
int Find(byte[] prefix, ByteBuffer key)
{
var left = 0;
var right = _keyvalues.Length;
var keyBytes = _keyBytes;
while (left < right)
{
var middle = (left + right) / 2;
int currentKeyOfs = _keyvalues[middle].KeyOffset;
int currentKeyLen = _keyvalues[middle].KeyLength;
var result = BitArrayManipulation.CompareByteArray(prefix, 0, prefix.Length,
keyBytes, currentKeyOfs, Math.Min(currentKeyLen, prefix.Length));
if (result == 0)
{
result = BitArrayManipulation.CompareByteArray(key.Buffer, key.Offset, key.Length,
keyBytes, currentKeyOfs + prefix.Length, currentKeyLen - prefix.Length);
if (result == 0)
{
return middle * 2 + 1;
}
}
if (result < 0)
{
right = middle;
}
else
{
left = middle + 1;
}
}
return left * 2;
}
public void CreateOrUpdate(CreateOrUpdateCtx ctx)
{
var index = Find(ctx.KeyPrefix, ctx.Key);
if ((index & 1) == 1)
{
index = index / 2;
ctx.Created = false;
ctx.KeyIndex = index;
var m = _keyvalues[index];
m.ValueFileId = ctx.ValueFileId;
m.ValueOfs = ctx.ValueOfs;
m.ValueSize = ctx.ValueSize;
var leaf = this;
if (ctx.TransactionId != TransactionId)
{
leaf = new BTreeLeafComp(ctx.TransactionId, _keyvalues.Length);
Array.Copy(_keyvalues, leaf._keyvalues, _keyvalues.Length);
leaf._keyBytes = _keyBytes;
ctx.Node1 = leaf;
ctx.Update = true;
}
leaf._keyvalues[index] = m;
ctx.Stack.Add(new NodeIdxPair {Node = leaf, Idx = index});
return;
}
if ((long) _keyBytes.Length + ctx.WholeKeyLen > MaxTotalLen)
{
var currentKeyValues = new BTreeLeafMember[_keyvalues.Length];
for (int i = 0; i < currentKeyValues.Length; i++)
{
var member = _keyvalues[i];
currentKeyValues[i] = new BTreeLeafMember
{
Key = ByteBuffer.NewAsync(_keyBytes, member.KeyOffset, member.KeyLength).ToByteArray(),
ValueFileId = member.ValueFileId,
ValueOfs = member.ValueOfs,
ValueSize = member.ValueSize
};
}
new BTreeLeaf(ctx.TransactionId - 1, currentKeyValues).CreateOrUpdate(ctx);
return;
}
index = index / 2;
ctx.Created = true;
ctx.KeyIndex = index;
var newKey = ctx.WholeKey();
if (_keyvalues.Length < MaxMembers)
{
var newKeyValues = new Member[_keyvalues.Length + 1];
var newKeyBytes = new byte[_keyBytes.Length + newKey.Length];
Array.Copy(_keyvalues, 0, newKeyValues, 0, index);
var ofs = (ushort) (index == 0
? 0
: newKeyValues[index - 1].KeyOffset + newKeyValues[index - 1].KeyLength);
newKeyValues[index] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort) newKey.Length,
ValueFileId = ctx.ValueFileId,
ValueOfs = ctx.ValueOfs,
ValueSize = ctx.ValueSize
};
Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs);
Array.Copy(newKey, 0, newKeyBytes, ofs, newKey.Length);
Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, _keyBytes.Length - ofs);
Array.Copy(_keyvalues, index, newKeyValues, index + 1, _keyvalues.Length - index);
RecalculateOffsets(newKeyValues);
var leaf = this;
if (ctx.TransactionId != TransactionId)
{
leaf = new BTreeLeafComp(ctx.TransactionId, newKeyBytes, newKeyValues);
ctx.Node1 = leaf;
ctx.Update = true;
}
else
{
_keyvalues = newKeyValues;
_keyBytes = newKeyBytes;
}
ctx.Stack.Add(new NodeIdxPair {Node = leaf, Idx = index});
return;
}
ctx.Split = true;
var keyCountLeft = (_keyvalues.Length + 1) / 2;
var keyCountRight = _keyvalues.Length + 1 - keyCountLeft;
var leftNode = new BTreeLeafComp(ctx.TransactionId, keyCountLeft);
var rightNode = new BTreeLeafComp(ctx.TransactionId, keyCountRight);
ctx.Node1 = leftNode;
ctx.Node2 = rightNode;
if (index < keyCountLeft)
{
Array.Copy(_keyvalues, 0, leftNode._keyvalues, 0, index);
var ofs = (ushort) (index == 0 ? 0 : _keyvalues[index - 1].KeyOffset + _keyvalues[index - 1].KeyLength);
leftNode._keyvalues[index] = new Member
{
KeyOffset = ofs,
KeyLength = (ushort) newKey.Length,
ValueFileId = ctx.ValueFileId,
ValueOfs = ctx.ValueOfs,
ValueSize = ctx.ValueSize
};
Array.Copy(_keyvalues, index, leftNode._keyvalues, index + 1, keyCountLeft - index - 1);
Array.Copy(_keyvalues, keyCountLeft - 1, rightNode._keyvalues, 0, keyCountRight);
var leftKeyBytesLen = _keyvalues[keyCountLeft - 1].KeyOffset + newKey.Length;
var newKeyBytes = new byte[leftKeyBytesLen];
Array.Copy(_keyBytes, 0, newKeyBytes, 0, ofs);
Array.Copy(newKey, 0, newKeyBytes, ofs, newKey.Length);
Array.Copy(_keyBytes, ofs, newKeyBytes, ofs + newKey.Length, leftKeyBytesLen - (ofs + newKey.Length));
leftNode._keyBytes = newKeyBytes;
newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen];
Array.Copy(_keyBytes, leftKeyBytesLen - newKey.Length, newKeyBytes, 0, newKeyBytes.Length);
rightNode._keyBytes = newKeyBytes;
ctx.Stack.Add(new NodeIdxPair {Node = leftNode, Idx = index});
ctx.SplitInRight = false;
RecalculateOffsets(leftNode._keyvalues);
}
else
{
Array.Copy(_keyvalues, 0, leftNode._keyvalues, 0, keyCountLeft);
var leftKeyBytesLen = _keyvalues[keyCountLeft].KeyOffset;
var newKeyBytes = new byte[leftKeyBytesLen];
Array.Copy(_keyBytes, 0, newKeyBytes, 0, leftKeyBytesLen);
leftNode._keyBytes = newKeyBytes;
newKeyBytes = new byte[_keyBytes.Length + newKey.Length - leftKeyBytesLen];
var ofs = (index == _keyvalues.Length ? _keyBytes.Length : _keyvalues[index].KeyOffset) -
leftKeyBytesLen;
Array.Copy(_keyBytes, leftKeyBytesLen, newKeyBytes, 0, ofs);
Array.Copy(newKey, 0, newKeyBytes, ofs, newKey.Length);
Array.Copy(_keyBytes, ofs + leftKeyBytesLen, newKeyBytes, ofs + newKey.Length,
_keyBytes.Length - ofs - leftKeyBytesLen);
rightNode._keyBytes = newKeyBytes;
Array.Copy(_keyvalues, keyCountLeft, rightNode._keyvalues, 0, index - keyCountLeft);
rightNode._keyvalues[index - keyCountLeft] = new Member
{
KeyOffset = 0,
KeyLength = (ushort) newKey.Length,
ValueFileId = ctx.ValueFileId,
ValueOfs = ctx.ValueOfs,
ValueSize = ctx.ValueSize
};
Array.Copy(_keyvalues, index, rightNode._keyvalues, index - keyCountLeft + 1,
keyCountLeft + keyCountRight - 1 - index);
ctx.Stack.Add(new NodeIdxPair {Node = rightNode, Idx = index - keyCountLeft});
ctx.SplitInRight = true;
}
RecalculateOffsets(rightNode._keyvalues);
}
public FindResult FindKey(List<NodeIdxPair> stack, out long keyIndex, byte[] prefix, ByteBuffer key)
{
var idx = Find(prefix, key);
FindResult result;
if ((idx & 1) == 1)
{
result = FindResult.Exact;
idx = idx / 2;
}
else
{
result = FindResult.Previous;
idx = idx / 2 - 1;
}
stack.Add(new NodeIdxPair {Node = this, Idx = idx});
keyIndex = idx;
return result;
}
static BTreeLeafMember NewMemberFromCtx(CreateOrUpdateCtx ctx)
{
return new BTreeLeafMember
{
Key = ctx.WholeKey(),
ValueFileId = ctx.ValueFileId,
ValueOfs = ctx.ValueOfs,
ValueSize = ctx.ValueSize
};
}
public long CalcKeyCount()
{
return _keyvalues.Length;
}
public byte[] GetLeftMostKey()
{
return ByteBuffer.NewAsync(_keyBytes, _keyvalues[0].KeyOffset, _keyvalues[0].KeyLength).ToByteArray();
}
public void FillStackByIndex(List<NodeIdxPair> stack, long keyIndex)
{
stack.Add(new NodeIdxPair {Node = this, Idx = (int) keyIndex});
}
public long FindLastWithPrefix(byte[] prefix)
{
var left = 0;
var right = _keyvalues.Length - 1;
var keyBytes = _keyBytes;
int result;
int currentKeyOfs;
int currentKeyLen;
while (left < right)
{
var middle = (left + right) / 2;
currentKeyOfs = _keyvalues[middle].KeyOffset;
currentKeyLen = _keyvalues[middle].KeyLength;
result = BitArrayManipulation.CompareByteArray(prefix, 0, prefix.Length,
keyBytes, currentKeyOfs, Math.Min(currentKeyLen, prefix.Length));
if (result < 0)
{
right = middle;
}
else
{
left = middle + 1;
}
}
currentKeyOfs = _keyvalues[left].KeyOffset;
currentKeyLen = _keyvalues[left].KeyLength;
result = BitArrayManipulation.CompareByteArray(prefix, 0, prefix.Length,
keyBytes, currentKeyOfs, Math.Min(currentKeyLen, prefix.Length));
if (result < 0) left--;
return left;
}
public bool NextIdxValid(int idx)
{
return idx + 1 < _keyvalues.Length;
}
public void FillStackByLeftMost(List<NodeIdxPair> stack, int idx)
{
// Nothing to do
}
public void FillStackByRightMost(List<NodeIdxPair> stack, int i)
{
// Nothing to do
}
public int GetLastChildrenIdx()
{
return _keyvalues.Length - 1;
}
public IBTreeNode EraseRange(long transactionId, long firstKeyIndex, long lastKeyIndex)
{
var newKeyValues = new Member[_keyvalues.Length + firstKeyIndex - lastKeyIndex - 1];
var newKeyBytes = new byte[_keyBytes.Length + _keyvalues[firstKeyIndex].KeyOffset -
_keyvalues[lastKeyIndex].KeyOffset - _keyvalues[lastKeyIndex].KeyLength];
Array.Copy(_keyvalues, 0, newKeyValues, 0, (int) firstKeyIndex);
Array.Copy(_keyvalues, (int) lastKeyIndex + 1, newKeyValues, (int) firstKeyIndex,
newKeyValues.Length - (int) firstKeyIndex);
Array.Copy(_keyBytes, 0, newKeyBytes, 0, _keyvalues[firstKeyIndex].KeyOffset);
Array.Copy(_keyBytes, _keyvalues[lastKeyIndex].KeyOffset + _keyvalues[lastKeyIndex].KeyLength, newKeyBytes,
_keyvalues[firstKeyIndex].KeyOffset, newKeyBytes.Length - _keyvalues[firstKeyIndex].KeyOffset);
RecalculateOffsets(newKeyValues);
if (TransactionId == transactionId)
{
_keyvalues = newKeyValues;
_keyBytes = newKeyBytes;
return this;
}
return new BTreeLeafComp(transactionId, newKeyBytes, newKeyValues);
}
static void RecalculateOffsets(Member[] keyvalues)
{
ushort ofs = 0;
for (var i = 0; i < keyvalues.Length; i++)
{
keyvalues[i].KeyOffset = ofs;
ofs += keyvalues[i].KeyLength;
}
}
public void Iterate(ValuesIterateAction action)
{
var kv = _keyvalues;
foreach (var member in kv)
{
if (member.ValueFileId == 0) continue;
action(member.ValueFileId, member.ValueOfs, member.ValueSize);
}
}
public IBTreeNode ReplaceValues(ReplaceValuesCtx ctx)
{
var result = this;
var keyValues = _keyvalues;
var map = ctx._newPositionMap;
for (var i = 0; i < keyValues.Length; i++)
{
ref var ii = ref keyValues[i];
if (map.TryGetValue(((ulong) ii.ValueFileId << 32) | ii.ValueOfs, out var newOffset))
{
if (result.TransactionId != ctx._transactionId)
{
var newKeyValues = new Member[keyValues.Length];
Array.Copy(keyValues, newKeyValues, newKeyValues.Length);
result = new BTreeLeafComp(ctx._transactionId, _keyBytes, newKeyValues);
keyValues = newKeyValues;
}
keyValues[i].ValueFileId = (uint) (newOffset >> 32);
keyValues[i].ValueOfs = (uint) newOffset;
}
}
return result;
}
public ByteBuffer GetKey(int idx)
{
return ByteBuffer.NewAsync(_keyBytes, _keyvalues[idx].KeyOffset, _keyvalues[idx].KeyLength);
}
public BTreeValue GetMemberValue(int idx)
{
var kv = _keyvalues[idx];
return new BTreeValue
{
ValueFileId = kv.ValueFileId,
ValueOfs = kv.ValueOfs,
ValueSize = kv.ValueSize
};
}
public void SetMemberValue(int idx, BTreeValue value)
{
var kv = _keyvalues[idx];
kv.ValueFileId = value.ValueFileId;
kv.ValueOfs = value.ValueOfs;
kv.ValueSize = value.ValueSize;
_keyvalues[idx] = kv;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using NUnit.Framework;
using ServiceStack.Common;
using ServiceStack.Common.Utils;
using ServiceStack.Html;
using ServiceStack.Markdown;
using ServiceStack.Razor;
using ServiceStack.ServiceHost.Tests.Formats;
using ServiceStack.ServiceInterface.Testing;
using ServiceStack.Text;
using ServiceStack.VirtualPath;
namespace ServiceStack.ServiceHost.Tests.Formats_Razor
{
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Link> Links { get; set; }
}
public class Link
{
public Link()
{
this.Labels = new List<string>();
}
public string Name { get; set; }
public string Href { get; set; }
public List<string> Labels { get; set; }
}
public class CustomViewBase<T> : ViewPage<T>
{
public CustomMarkdownHelper Ext = new CustomMarkdownHelper();
public ExternalProductHelper Prod = new ExternalProductHelper();
public MvcHtmlString Table(dynamic obj)
{
Person model = obj;
var sb = new StringBuilder();
sb.AppendFormat("<table><caption>{0}'s Links</caption>", model.FirstName);
sb.AppendLine("<thead><tr><th>Name</th><th>Link</th></tr></thead>");
sb.AppendLine("<tbody>");
foreach (var link in model.Links)
{
sb.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", link.Name, link.Href);
}
sb.AppendLine("</tbody>");
sb.AppendLine("</table>");
return MvcHtmlString.Create(sb.ToString());
}
private static string[] MenuItems = new[] { "About Us", "Blog", "Links", "Contact" };
public MvcHtmlString Menu(string selectedId)
{
var sb = new StringBuilder();
sb.Append("<ul>\n");
foreach (var menuItem in MenuItems)
{
var cls = menuItem == selectedId ? " class='selected'" : "";
sb.AppendFormat("<li><a href='{0}'{1}>{0}</a></li>\n", menuItem, cls);
}
sb.Append("</ul>\n");
return MvcHtmlString.Create(sb.ToString());
}
public string Lower(string name)
{
return name == null ? null : name.ToLower();
}
public string Upper(string name)
{
return name == null ? null : name.ToUpper();
}
public string Combine(string separator, params string[] parts)
{
return string.Join(separator, parts);
}
}
public class CustomMarkdownHelper
{
public static CustomMarkdownHelper Instance = new CustomMarkdownHelper();
public MvcHtmlString InlineBlock(string content, string id)
{
return MvcHtmlString.Create(
"<div id=\"" + id + "\"><div class=\"inner inline-block\">" + content + "</div></div>");
}
}
[TestFixture]
public class RazorTemplateTests : RazorTestBase
{
string staticTemplatePath;
string staticTemplateContent;
string dynamicPagePath;
string dynamicPageContent;
string dynamicListPagePath;
string dynamicListPageContent;
Person templateArgs;
Person person = new Person {
FirstName = "Demis",
LastName = "Bellot",
Links = new List<Link>
{
new Link { Name = "ServiceStack", Href = "http://www.servicestack.net", Labels = {"REST","JSON","XML"} },
new Link { Name = "AjaxStack", Href = "http://www.ajaxstack.com", Labels = {"HTML5", "AJAX", "SPA"} },
},
};
[TestFixtureSetUp]
public void TestFixtureSetUp()
{
staticTemplatePath = "Views/Shared/_Layout.cshtml";
staticTemplateContent = File.ReadAllText("~/{0}".Fmt(staticTemplatePath).MapProjectPath());
dynamicPagePath = "Views/Template/DynamicTpl.cshtml";
dynamicPageContent = File.ReadAllText("~/{0}".Fmt(dynamicPagePath).MapProjectPath());
dynamicListPagePath = "Views/Template/DynamicListTpl.cshtml".MapProjectPath();
dynamicListPageContent = File.ReadAllText("~/{0}".Fmt(dynamicListPagePath).MapProjectPath());
templateArgs = person;
}
[SetUp]
public void OnBeforeEachTest()
{
base.RazorFormat = new RazorFormat {
VirtualPathProvider = new InMemoryVirtualPathProvider(new BasicAppHost()),
TemplateProvider = { CompileInParallelWithNoOfThreads = 0 },
};
RazorFormat.Init();
}
[Test]
public void Can_Render_RazorTemplate()
{
const string mockContents = "[Replaced with Template]";
RazorFormat.AddFileAndTemplate(staticTemplatePath, staticTemplateContent);
var page = AddViewPage("MockPage", "/path/to/page", mockContents, staticTemplatePath);
var expectedHtml = staticTemplateContent.ReplaceFirst(RazorFormat.TemplatePlaceHolder, mockContents);
var templateOutput = page.RenderToString(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_RazorPage()
{
RazorFormat.AddFileAndTemplate(staticTemplatePath, staticTemplateContent);
var dynamicPage = AddViewPage("DynamicTpl", dynamicPagePath, dynamicPageContent, staticTemplatePath);
var expectedHtml = dynamicPageContent
.Replace("@Model.FirstName", person.FirstName)
.Replace("@Model.LastName", person.LastName);
expectedHtml = staticTemplateContent.Replace(RazorFormat.TemplatePlaceHolder, expectedHtml);
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_RazorPage_with_foreach()
{
RazorFormat.AddFileAndTemplate(staticTemplatePath, staticTemplateContent);
var dynamicPage = AddViewPage("DynamicListTpl", dynamicListPagePath, dynamicListPageContent, staticTemplatePath);
var expectedHtml = dynamicListPageContent
.Replace("@Model.FirstName", person.FirstName)
.Replace("@Model.LastName", person.LastName);
var foreachLinks = " <li>ServiceStack - http://www.servicestack.net</li>\r\n"
+ " <li>AjaxStack - http://www.ajaxstack.com</li>";
expectedHtml = expectedHtml.ReplaceForeach(foreachLinks);
expectedHtml = staticTemplateContent.Replace(RazorFormat.TemplatePlaceHolder, expectedHtml);
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_RazorPage_with_IF_statement()
{
var template = @"<h1>Dynamic If Markdown Template</h1>
<p>Hello @Model.FirstName,</p>
<ul>
@if (Model.FirstName == ""Bellot"") {
<li>@Model.FirstName</li>
}
@if (Model.LastName == ""Bellot"") {
<li>@Model.LastName</li>
}
</ul>
<h3>heading 3</h3>";
var expectedHtml = @"<h1>Dynamic If Markdown Template</h1>
<p>Hello Demis,</p>
<ul>
<li>Bellot</li>
</ul>
<h3>heading 3</h3>";
var dynamicPage = AddViewPage("DynamicIfTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_RazorPage_with_Nested_Statements()
{
var template = @"<h1>@Model.FirstName Dynamic Nested Markdown Template</h1>
<h1>heading 1</h1>
<ul>
@foreach (var link in Model.Links) {
@if (link.Name == ""AjaxStack"") {
<li>@link.Name - @link.Href</li>
}
}
</ul>
@if (Model.Links.Count == 2) {
<h2>Haz 2 links</h2>
<ul>
@foreach (var link in Model.Links) {
<li>@link.Name - @link.Href</li>
@foreach (var label in link.Labels) {
<li>@label</li>
}
}
</ul>
}
<h3>heading 3</h3>";
var expectedHtml = @"<h1>Demis Dynamic Nested Markdown Template</h1>
<h1>heading 1</h1>
<ul>
<li>AjaxStack - http://www.ajaxstack.com</li>
</ul>
<h2>Haz 2 links</h2>
<ul>
<li>ServiceStack - http://www.servicestack.net</li>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
<li>AjaxStack - http://www.ajaxstack.com</li>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
<h3>heading 3</h3>";
var dynamicPage = AddViewPage("DynamicNestedTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs);
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_Razor_with_StaticMethods()
{
var headerTemplate = @"<h2>Header Links!</h2>
<ul>
<li><a href=""http://google.com"">Google</a></li>
<li><a href=""http://bing.com"">Bing</a></li>
</ul>".NormalizeNewLines();
var template = @"<h2>Welcome to Razor!</h2>
@Html.Partial(""HeaderLinks"", Model)
<p>Hello @Upper(Model.LastName), @Model.FirstName</p>
<h3>Breadcrumbs</h3>
@Combine("" / "", Model.FirstName, Model.LastName)
<h3>Menus</h3>
<ul>
@foreach (var link in Model.Links) {
<li>@link.Name - @link.Href
<ul>
@foreach (var label in link.Labels) {
<li>@label</li>
}
</ul>
</li>
}
</ul>
<h3>HTML Table</h3>
@Table(Model)".NormalizeNewLines();
var expectedHtml = @"<h2>Welcome to Razor!</h2>
<h2>Header Links!</h2>
<ul>
<li><a href=""http://google.com"">Google</a></li>
<li><a href=""http://bing.com"">Bing</a></li>
</ul>
<p>Hello BELLOT, Demis</p>
<h3>Breadcrumbs</h3>
Demis / Bellot
<h3>Menus</h3>
<ul>
<li>ServiceStack - http://www.servicestack.net
<ul>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
</ul>
</li>
<li>AjaxStack - http://www.ajaxstack.com
<ul>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
</li>
</ul>
<h3>HTML Table</h3>
<table><caption>Demis's Links</caption><thead><tr><th>Name</th><th>Link</th></tr></thead>
<tbody>
<tr><td>ServiceStack</td><td>http://www.servicestack.net</td></tr><tr><td>AjaxStack</td><td>http://www.ajaxstack.com</td></tr></tbody>
</table>
".NormalizeNewLines();
RazorFormat.TemplateService.TemplateBaseType = typeof(CustomViewBase<>);
AddViewPage("HeaderLinks", "/path/to/page", headerTemplate);
var dynamicPage = AddViewPage("DynamicIfTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs).NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_inherit_from_Generic_RazorViewPage_from_model_directive()
{
var template = @"@model ServiceStack.ServiceHost.Tests.Formats_Razor.Person
<h1>Generic View Page</h1>
<h2>Form fields</h2>
@Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName)
";
var expectedHtml = @"<h1>Generic View Page</h1>
<h2>Form fields</h2>
<label for=""FirstName"">FirstName</label> <input name=""FirstName"" type=""text"" value=""Demis"" />
".NormalizeNewLines();
var dynamicPage = AddViewPage("DynamicModelTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs).NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_inherit_from_CustomViewPage_using_inherits_directive()
{
var template = @"@inherits ServiceStack.ServiceHost.Tests.Formats_Razor.CustomViewBase<ServiceStack.ServiceHost.Tests.Formats_Razor.Person>
<h1>Generic View Page</h1>
<h2>Form fields</h2>
@Html.LabelFor(m => m.FirstName) @Html.TextBoxFor(m => m.FirstName)
<h2>Person Table</h2>
@Table(Model)";
var expectedHtml = @"<h1>Generic View Page</h1>
<h2>Form fields</h2>
<label for=""FirstName"">FirstName</label> <input name=""FirstName"" type=""text"" value=""Demis"" />
<h2>Person Table</h2>
<table><caption>Demis's Links</caption><thead><tr><th>Name</th><th>Link</th></tr></thead>
<tbody>
<tr><td>ServiceStack</td><td>http://www.servicestack.net</td></tr><tr><td>AjaxStack</td><td>http://www.ajaxstack.com</td></tr></tbody>
</table>
".NormalizeNewLines();
var dynamicPage = AddViewPage("DynamicModelTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs).NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_RazorPage_with_external_helper()
{
var template = @"<h1>View Page with Custom Helper</h1>
<h2>External Helper</h2>
<img src='path/to/img' class='inline-block' />
@Ext.InlineBlock(Model.FirstName, ""first-name"")
";
var expectedHtml =
@"<h1>View Page with Custom Helper</h1>
<h2>External Helper</h2>
<img src='path/to/img' class='inline-block' />
<div id=""first-name""><div class=""inner inline-block"">Demis</div></div>
".NormalizeNewLines();
RazorFormat.TemplateService.TemplateBaseType = typeof(CustomViewBase<>);
var dynamicPage = AddViewPage("DynamicModelTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs).NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_RazorPage_with_variable_statements()
{
var template = @"<h2>Welcome to Razor!</h2>
@{ var lastName = Model.LastName; }
Hello @Upper(lastName), @Model.FirstName
<h3>Breadcrumbs</h3>
@Combine("" / "", Model.FirstName, lastName)
@{ var links = Model.Links; }
<h3>Menus</h3>
<ul>
@foreach (var link in links) {
<li>@link.Name - @link.Href
<ul>
@{ var labels = link.Labels; }
@foreach (var label in labels) {
<li>@label</li>
}
</ul>
</li>
}
</ul>";
var expectedHtml = @"<h2>Welcome to Razor!</h2>
Hello BELLOT, Demis
<h3>Breadcrumbs</h3>
Demis / Bellot
<h3>Menus</h3>
<ul>
<li>ServiceStack - http://www.servicestack.net
<ul>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
</ul>
</li>
<li>AjaxStack - http://www.ajaxstack.com
<ul>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
</li>
</ul>".NormalizeNewLines();
RazorFormat.TemplateService.TemplateBaseType = typeof(CustomViewBase<>);
var dynamicPage = AddViewPage("DynamicModelTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs).NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_RazorPage_with_comments()
{
var template = @"<h1>Dynamic If Markdown Template</h1>
<p>Hello @Model.FirstName,</p>
@if (Model.FirstName == ""Bellot"") {
<ul>
<li>@Model.FirstName</li>
</ul>
}
@*
@if (Model.LastName == ""Bellot"") {
* @Model.LastName
}
*@
@*
Plain text in a comment
*@
<h3>heading 3</h3>";
var expectedHtml = @"<h1>Dynamic If Markdown Template</h1>
<p>Hello Demis,</p>
<h3>heading 3</h3>".NormalizeNewLines();
var dynamicPage = AddViewPage("DynamicIfTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs).NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_capture_Section_statements_and_store_them_in_Sections()
{
var template = @"<h2>Welcome to Razor!</h2>
@{ var lastName = Model.LastName; }
@section Salutations {
<p>Hello @Upper(lastName), @Model.FirstName</p>
}
@section Breadcrumbs {
<h3>Breadcrumbs</h3>
<p>@Combine("" / "", Model.FirstName, lastName)</p>
}
@{ var links = Model.Links; }
@section Menus {
<h3>Menus</h3>
<ul>
@foreach (var link in links) {
<li>@link.Name - @link.Href
<ul>
@{ var labels = link.Labels; }
@foreach (var label in labels) {
<li>@label</li>
}
</ul>
</li>
}
</ul>
}
<h2>Captured Sections</h2>
<div id='breadcrumbs'>
@RenderSection(""Breadcrumbs"")
</div>
@RenderSection(""Menus"")
<h2>Salutations</h2>
@RenderSection(""Salutations"")";
var expectedHtml =
@"<h2>Welcome to Razor!</h2>
<h2>Captured Sections</h2>
<div id='breadcrumbs'>
<h3>Breadcrumbs</h3>
<p>Demis / Bellot</p>
</div>
<h3>Menus</h3>
<ul>
<li>ServiceStack - http://www.servicestack.net
<ul>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
</ul>
</li>
<li>AjaxStack - http://www.ajaxstack.com
<ul>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
</li>
</ul>
<h2>Salutations</h2>
<p>Hello BELLOT, Demis</p>
".NormalizeNewLines();
RazorFormat.TemplateService.TemplateBaseType = typeof(CustomViewBase<>);
var dynamicPage = AddViewPage("DynamicModelTpl", "/path/to/tpl", template);
var templateOutput = dynamicPage.RenderToHtml(templateArgs).NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
var razorTemplate = dynamicPage.GetRazorTemplate();
razorTemplate.Clear();
Action section;
razorTemplate.Sections.TryGetValue("Salutations", out section);
section();
Assert.That(razorTemplate.Result, Is.EqualTo("\r\n<p>Hello BELLOT, Demis</p>\r\n"));
}
[Test]
public void Can_Render_RazorTemplate_with_section_and_variable_placeholders()
{
var template = @"<h2>Welcome to Razor!</h2>
@{ var lastName = Model.LastName; }
<p>Hello @Upper(lastName), @Model.FirstName,</p>
@section Breadcrumbs {
<h3>Breadcrumbs</h3>
@Combine("" / "", Model.FirstName, lastName)
}
@section Menus {
<h3>Menus</h3>
<ul>
@foreach (var link in Model.Links) {
<li>@link.Name - @link.Href
<ul>
@{ var labels = link.Labels; }
@foreach (var label in labels) {
<li>@label</li>
}
</ul>
</li>
}
</ul>
}";
var websiteTemplatePath = "websiteTemplate.cshtml";
var websiteTemplate = @"<!doctype html>
<html lang=""en-us"">
<head>
<title>Bellot page</title>
</head>
<body>
<header>
@RenderSection(""Menus"")
</header>
<h1>Website Template</h1>
<div id=""content"">@RenderBody()</div>
<footer>
@RenderSection(""Breadcrumbs"")
</footer>
</body>
</html>";
var expectedHtml =
@"<!doctype html>
<html lang=""en-us"">
<head>
<title>Bellot page</title>
</head>
<body>
<header>
<h3>Menus</h3>
<ul>
<li>ServiceStack - http://www.servicestack.net
<ul>
<li>REST</li>
<li>JSON</li>
<li>XML</li>
</ul>
</li>
<li>AjaxStack - http://www.ajaxstack.com
<ul>
<li>HTML5</li>
<li>AJAX</li>
<li>SPA</li>
</ul>
</li>
</ul>
</header>
<h1>Website Template</h1>
<div id=""content""><h2>Welcome to Razor!</h2>
<p>Hello BELLOT, Demis,</p>
</div>
<footer>
<h3>Breadcrumbs</h3>
Demis / Bellot
</footer>
</body>
</html>".NormalizeNewLines();
RazorFormat.TemplateService.TemplateBaseType = typeof(CustomViewBase<>);
RazorFormat.AddFileAndTemplate(websiteTemplatePath, websiteTemplate);
AddViewPage("DynamicModelTpl", "/path/to/page-tpl", template, websiteTemplatePath);
var razorTemplate = RazorFormat.ExecuteTemplate(
person, "DynamicModelTpl", websiteTemplatePath);
var templateOutput = razorTemplate.Result.NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
[Test]
public void Can_Render_Static_RazorContentPage_that_populates_variable_and_displayed_on_website_template()
{
var websiteTemplate = @"<!doctype html>
<html lang=""en-us"">
<head>
<title>Static page</title>
</head>
<body>
<header>
@RenderSection(""Header"")
</header>
<div id='menus'>
@RenderSection(""Menu"")
</div>
<h1>Website Template</h1>
<div id=""content"">@RenderBody()</div>
</body>
</html>".NormalizeNewLines();
var template = @"<h1>Static Markdown Template</h1>
@section Menu {
@Menu(""Links"")
}
@section Header {
<h3>Static Page Title</h3>
}
<h3>heading 3</h3>
<p>paragraph</p>";
var expectedHtml = @"<!doctype html>
<html lang=""en-us"">
<head>
<title>Static page</title>
</head>
<body>
<header>
<h3>Static Page Title</h3>
</header>
<div id='menus'>
<ul>
<li><a href='About Us'>About Us</a></li>
<li><a href='Blog'>Blog</a></li>
<li><a href='Links' class='selected'>Links</a></li>
<li><a href='Contact'>Contact</a></li>
</ul>
</div>
<h1>Website Template</h1>
<div id=""content""><h1>Static Markdown Template</h1>
<h3>heading 3</h3>
<p>paragraph</p></div>
</body>
</html>".NormalizeNewLines();
RazorFormat.TemplateService.TemplateBaseType = typeof(CustomViewBase<>);
var websiteTemplatePath = "websiteTemplate.cshtml";
RazorFormat.AddFileAndTemplate(websiteTemplatePath, websiteTemplate);
var staticPage = new ViewPageRef(RazorFormat,
"pagetpl", "StaticTpl", template, RazorPageType.ContentPage) {
Service = RazorFormat.TemplateService,
Template = websiteTemplatePath,
};
RazorFormat.AddPage(staticPage);
RazorFormat.TemplateService.RegisterPage("pagetpl", "StaticTpl");
RazorFormat.TemplateProvider.CompileQueuedPages();
var templateOutput = RazorFormat.RenderStaticPage("pagetpl").NormalizeNewLines();
Console.WriteLine(templateOutput);
Assert.That(templateOutput, Is.EqualTo(expectedHtml));
}
}
}
| |
using System;
using System.Collections.Generic;
namespace CocosSharp
{
public delegate void CCFocusChangeDelegate(ICCFocusable prev, ICCFocusable current);
public class CCFocusManager
{
// Scrolling focus delay used to slow down automatic focus changes when the dpad is held.
public static float MenuScrollDelay = 50f;
static CCFocusManager instance = new CCFocusManager();
public event CCFocusChangeDelegate OnFocusChanged;
bool scrollingPrevious = false;
bool scrollingNext = false;
long timeOfLastFocus = 0L;
LinkedList<ICCFocusable> focusList = new LinkedList<ICCFocusable>();
LinkedListNode<ICCFocusable> current = null;
#region Properties
public static CCFocusManager Instance
{
get { return instance; }
}
// When false, the focus will not traverse on the keyboard or dpad events.
public bool Enabled { get; set; }
// Returns the item with the current focus. This test will create a copy
// of the master item list.
public ICCFocusable ItemWithFocus
{
get { return (current != null ? current.Value : null); }
}
#endregion Properties
#region Constructors
private CCFocusManager()
{
}
#endregion Constructors
// Removes the given focusable node
public void Remove(params ICCFocusable[] focusItems)
{
foreach (ICCFocusable f in focusItems)
{
focusList.Remove(f);
}
}
// Adds the given node to the list of focus nodes. If the node has the focus, then it is
// given the current focused item status. If there is already a focused item and the
// given node has focus, the focus is disabled.
public void Add(params ICCFocusable[] focusItems)
{
foreach (ICCFocusable f in focusItems)
{
LinkedListNode<ICCFocusable> i = focusList.AddLast(f);
if (f.HasFocus)
{
if (current == null)
{
current = i;
}
else
{
f.HasFocus = false;
}
}
}
}
// Scroll to the next item in the focus list.
public void FocusNextItem()
{
if (current == null && focusList.Count > 0)
{
current = focusList.First;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(null, current.Value);
}
}
else if (current != null)
{
ICCFocusable lostItem = current.Value;
// Search for the next node.
LinkedListNode<ICCFocusable> nextItem = null;
for (LinkedListNode<ICCFocusable> p = current.Next; p != null; p = p.Next)
{
if (p.Value.CanReceiveFocus)
{
nextItem = p;
}
}
if (nextItem != null)
{
current = nextItem;
}
else
{
current = focusList.First;
}
lostItem.HasFocus = false;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(lostItem, current.Value);
}
}
else
{
current = null;
}
}
// Scroll to the previous item in the focus list.
public void FocusPreviousItem()
{
if (ItemWithFocus == null && focusList.Count > 0)
{
current = focusList.Last;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(null, current.Value);
}
}
else if (current != null)
{
ICCFocusable lostItem = current.Value;
LinkedListNode<ICCFocusable> nextItem = null;
for (LinkedListNode<ICCFocusable> p = current.Previous; p != null; p = p.Previous)
{
if (p.Value.CanReceiveFocus)
{
nextItem = p;
}
}
if (current.Previous != null)
{
current = current.Previous;
}
else
{
current = focusList.Last;
}
lostItem.HasFocus = false;
current.Value.HasFocus = true;
if (OnFocusChanged != null)
{
OnFocusChanged(lostItem, current.Value);
}
}
else
{
current = null;
}
}
void SharedApplication_GamePadDPadUpdate(CCGamePadButtonStatus leftButton, CCGamePadButtonStatus upButton,
CCGamePadButtonStatus rightButton, CCGamePadButtonStatus downButton, Microsoft.Xna.Framework.PlayerIndex player)
{
if (!Enabled)
{
return;
}
if (leftButton == CCGamePadButtonStatus.Released || upButton == CCGamePadButtonStatus.Released || rightButton == CCGamePadButtonStatus.Released || downButton == CCGamePadButtonStatus.Released)
{
scrollingPrevious = false;
timeOfLastFocus = 0L;
}
// Left and right d-pad shuffle through the menus
else if (leftButton == CCGamePadButtonStatus.Pressed || upButton == CCGamePadButtonStatus.Pressed)
{
if (scrollingPrevious)
{
TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - timeOfLastFocus);
if (ts.TotalMilliseconds > MenuScrollDelay)
{
FocusPreviousItem();
}
}
else
{
scrollingPrevious = true;
timeOfLastFocus = DateTime.UtcNow.Ticks;
}
}
else if (rightButton == CCGamePadButtonStatus.Pressed || downButton == CCGamePadButtonStatus.Pressed)
{
if (scrollingNext)
{
TimeSpan ts = new TimeSpan(DateTime.UtcNow.Ticks - timeOfLastFocus);
if (ts.TotalMilliseconds > MenuScrollDelay)
{
FocusNextItem();
}
}
else
{
scrollingNext = true;
timeOfLastFocus = DateTime.UtcNow.Ticks;
}
}
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.com
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Collections;
using System.IO;
#if !SILVERLIGHT
using log4net;
#endif
using FluorineFx.Util;
using FluorineFx.Messaging.Api;
using FluorineFx.Messaging.Api.Messaging;
using FluorineFx.Messaging.Api.Stream;
using FluorineFx.Messaging.Rtmp.Event;
using FluorineFx.Messaging.Rtmp.Stream;
using FluorineFx.Messaging.Rtmp.Stream.Messages;
//using FluorineFx.Messaging.Rtmp.IO;
using FluorineFx.Messaging.Messages;
namespace FluorineFx.Messaging.Rtmp.Stream.Consumer
{
/// <summary>
/// RTMP connection consumer.
/// </summary>
class ConnectionConsumer : IPushableConsumer, IPipeConnectionListener
{
#if !SILVERLIGHT
private static ILog log = LogManager.GetLogger(typeof(ConnectionConsumer));
#endif
/// <summary>
/// Connection object.
/// </summary>
private RtmpConnection _connection;
/// <summary>
/// Video channel.
/// </summary>
private RtmpChannel _video;
/// <summary>
/// Audio channel.
/// </summary>
private RtmpChannel _audio;
/// <summary>
/// Data channel.
/// </summary>
private RtmpChannel _data;
/// <summary>
/// Chunk size. Packets are sent chunk-by-chunk.
/// </summary>
private int _chunkSize = 1024; //TODO: Not sure of the best value here
/// <summary>
/// Whether or not the chunk size has been sent. This seems to be required for h264.
/// </summary>
private bool _chunkSizeSent;
/// <summary>
/// Modifies time stamps on messages as needed.
/// </summary>
private TimeStamper _timeStamper;
public ConnectionConsumer(RtmpConnection connection, int videoChannel, int audioChannel, int dataChannel)
{
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug(string.Format("Channel ids - video: {0} audio: {1} data: {2}", videoChannel, audioChannel, dataChannel));
#endif
_connection = connection;
_video = connection.GetChannel(videoChannel);
_audio = connection.GetChannel(audioChannel);
_data = connection.GetChannel(dataChannel);
_timeStamper = new TimeStamper();
}
#region IPushableConsumer Members
public void PushMessage(IPipe pipe, IMessage message)
{
if (message is ResetMessage)
{
_timeStamper.Reset();
}
else if (message is StatusMessage)
{
StatusMessage statusMsg = message as StatusMessage;
_data.SendStatus(statusMsg.body as StatusASO);
}
else if (message is RtmpMessage)
{
// Make sure chunk size has been sent
if (!_chunkSizeSent)
SendChunkSize();
RtmpMessage rtmpMsg = message as RtmpMessage;
IRtmpEvent msg = rtmpMsg.body;
int eventTime = msg.Timestamp;
#if !SILVERLIGHT
if(log.IsDebugEnabled)
log.Debug(string.Format("Message timestamp: {0}", eventTime));
#endif
if (eventTime < 0)
{
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug(string.Format("Message has negative timestamp: {0}", eventTime));
#endif
return;
}
byte dataType = msg.DataType;
// Create a new header for the consumer
RtmpHeader header = _timeStamper.GetTimeStamp(dataType, eventTime);
switch (msg.DataType)
{
case Constants.TypeStreamMetadata:
Notify notify = new Notify((msg as Notify).Data);
notify.Header = header;
notify.Timestamp = header.Timer;
_data.Write(notify);
break;
case Constants.TypeFlexStreamEnd:
// TODO: okay to send this also to AMF0 clients?
FlexStreamSend send = new FlexStreamSend((msg as Notify).Data);
send.Header = header;
send.Timestamp = header.Timer;
_data.Write(send);
break;
case Constants.TypeVideoData:
VideoData videoData = new VideoData((msg as VideoData).Data);
videoData.Header = header;
videoData.Timestamp = header.Timer;
_video.Write(videoData);
break;
case Constants.TypeAudioData:
AudioData audioData = new AudioData((msg as AudioData).Data);
audioData.Header = header;
audioData.Timestamp = header.Timer;
_audio.Write(audioData);
break;
case Constants.TypePing:
Ping ping = new Ping((msg as Ping).PingType, (msg as Ping).Value2, (msg as Ping).Value3, (msg as Ping).Value4);
ping.Header = header;
_connection.Ping(ping);
break;
case Constants.TypeBytesRead:
BytesRead bytesRead = new BytesRead((msg as BytesRead).Bytes);
bytesRead.Header = header;
bytesRead.Timestamp = header.Timer;
_connection.GetChannel((byte)2).Write(bytesRead);
break;
default:
_data.Write(msg);
break;
}
}
}
#endregion
#region IMessageComponent Members
public void OnOOBControlMessage(IMessageComponent source, IPipe pipe, OOBControlMessage oobCtrlMsg)
{
if (!"ConnectionConsumer".Equals(oobCtrlMsg.Target))
return;
if ("pendingCount".Equals(oobCtrlMsg.ServiceName))
{
oobCtrlMsg.Result = _connection.PendingMessages;
}
else if ("pendingVideoCount".Equals(oobCtrlMsg.ServiceName))
{
IClientStream stream = null;
if (_connection is IStreamCapableConnection)
stream = (_connection as IStreamCapableConnection).GetStreamByChannelId(_video.ChannelId);
if (stream != null)
{
oobCtrlMsg.Result = _connection.GetPendingVideoMessages(stream.StreamId);
}
else
{
oobCtrlMsg.Result = (long)0;
}
}
else if ("writeDelta".Equals(oobCtrlMsg.ServiceName))
{
long maxStream = 0;
IBWControllable bwControllable = _connection as IBWControllable;
// Search FC containing valid BWC
while (bwControllable != null && bwControllable.BandwidthConfiguration == null)
{
bwControllable = bwControllable.GetParentBWControllable();
}
if (bwControllable != null && bwControllable.BandwidthConfiguration != null)
{
IBandwidthConfigure bwc = bwControllable.BandwidthConfiguration;
if (bwc is IConnectionBWConfig)
{
maxStream = (bwc as IConnectionBWConfig).DownstreamBandwidth / 8;
}
}
if (maxStream <= 0)
{
// Use default value
// TODO: this should be configured somewhere and sent to the client when connecting
maxStream = 120 * 1024;
}
// Return the current delta between sent bytes and bytes the client
// reported to have received, and the interval the client should use
// for generating BytesRead messages (half of the allowed bandwidth).
oobCtrlMsg.Result = new long[] { _connection.WrittenBytes - _connection.ClientBytesRead, maxStream / 2 };
}
else if ("chunkSize".Equals(oobCtrlMsg.ServiceName))
{
int newSize = (int)oobCtrlMsg.ServiceParameterMap["chunkSize"];
if (newSize != _chunkSize)
{
_chunkSize = newSize;
SendChunkSize();
}
}
}
#endregion
#region IPipeConnectionListener Members
public void OnPipeConnectionEvent(PipeConnectionEvent evt)
{
switch (evt.Type)
{
case PipeConnectionEvent.PROVIDER_DISCONNECT:
// XXX should put the channel release code in ConsumerService
_connection.CloseChannel(_video.ChannelId);
_connection.CloseChannel(_audio.ChannelId);
_connection.CloseChannel(_data.ChannelId);
break;
default:
break;
}
}
#endregion
private class TimeStamper
{
/// <summary>
/// Stores timestamp for last event.
/// </summary>
private int _lastEventTime = 0;
/// <summary>
/// Timestamp of last audio packet.
/// </summary>
private int _lastAudioTime = 0;
/// <summary>
/// Timestamp of last video packet.
/// </summary>
private int _lastVideoTime = 0;
/// <summary>
/// Timestamp of last notify or invoke.
/// </summary>
private int _lastNotifyTime = 0;
/// <summary>
/// Reset timestamps.
/// </summary>
public void Reset()
{
#if !SILVERLIGHT
if( log.IsDebugEnabled )
log.Debug("Reset timestamps");
#endif
_lastEventTime = 0;
_lastAudioTime = 0;
_lastNotifyTime = 0;
_lastVideoTime = 0;
}
/// <summary>
/// Gets a header with the appropriate timestamp.
/// </summary>
/// <param name="dataType">Type of the event.</param>
/// <param name="eventTime">The event time.</param>
/// <returns></returns>
public RtmpHeader GetTimeStamp(byte dataType, int eventTime)
{
RtmpHeader header = new RtmpHeader();
#if !SILVERLIGHT
if( log.IsDebugEnabled )
log.Debug(string.Format("GetTimeStamp - event time: {0} last event: {1} audio: {2} video: {3} data: {4}", eventTime, _lastEventTime, _lastAudioTime, _lastVideoTime, _lastNotifyTime));
#endif
switch (dataType)
{
case Constants.TypeAudioData:
if (_lastAudioTime > 0)
{
//set a relative value
header.Timer = eventTime - _lastAudioTime;
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug("Relative audio");
#endif
}
else
{
//use absolute value
header.Timer = eventTime;
header.IsTimerRelative = false;
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug("Absolute audio");
#endif
}
_lastAudioTime = eventTime;
break;
case Constants.TypeVideoData:
if (_lastVideoTime > 0)
{
//set a relative value
header.Timer = eventTime - _lastVideoTime;
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug("Relative video");
#endif
}
else
{
//use absolute value
header.Timer = eventTime;
header.IsTimerRelative = false;
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug("Absolute video");
#endif
}
_lastVideoTime = eventTime;
break;
case Constants.TypeNotify:
case Constants.TypeInvoke:
case Constants.TypeFlexStreamEnd:
if (_lastNotifyTime > 0)
{
//set a relative value
header.Timer = eventTime - _lastNotifyTime;
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug("Relative notify");
#endif
}
else
{
//use absolute value
header.Timer = eventTime;
header.IsTimerRelative = false;
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug("Absolute notify");
#endif
}
_lastNotifyTime = eventTime;
break;
case Constants.TypeBytesRead:
case Constants.TypePing:
header.Timer = eventTime;
header.IsTimerRelative = false;
break;
default:
// ignore other types
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug(string.Format("Unmodified type: {0} timestamp: {1}", dataType, eventTime));
#endif
break;
}
#if !SILVERLIGHT
if (log.IsDebugEnabled)
log.Debug(string.Format("Event time: {0} current ts: {1}", eventTime, header.Timer));
#endif
_lastEventTime = eventTime;
return header;
}
}
/// <summary>
/// Send the chunk size.
/// </summary>
private void SendChunkSize()
{
#if !SILVERLIGHT
if(log.IsDebugEnabled )
log.Debug(string.Format("Sending chunk size: {0}", _chunkSize));
#endif
ChunkSize chunkSizeMsg = new ChunkSize(_chunkSize);
_connection.GetChannel((byte)2).Write(chunkSizeMsg);
_chunkSizeSent = true;
}
}
}
| |
#region License
// Copyright 2010 Buu Nguyen, Morten Mertner
//
// 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 latest version of this file can be found at http://fasterflect.codeplex.com/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Fasterflect.Probing
{
/// <summary>
/// This class wraps a single invokable method call. It contains information on the method to call as well as
/// the parameters to use in the method call.
/// This intermediary class is used by the various other classes to select the best match to call
/// from a given set of available methods/constructors (and a set of parameter names and types).
/// </summary>
internal class MethodMap
{
#region Fields
private readonly bool mustUseAllParameters;
protected long cost;
protected bool isPerfectMatch;
protected bool isValid;
protected MemberInfo[] members;
protected MethodBase method;
protected BitArray methodParameterUsageMask; // marks method parameters for which a source was found
protected string[] paramNames;
protected Type[] paramTypes;
protected BitArray parameterDefaultValueMask; // marks fields where default values will be used
protected IDictionary<string, object> parameterDefaultValues;
// protected BitArray parameterInjectionValueMask; // marks fields where injected values will be used
// protected BitArray parameterNullValueMask; // marks fields where null values will be used
protected int[] parameterOrderMap;
protected int[] parameterOrderMapReverse;
protected BitArray parameterReflectionMask; // marks parameters set using reflection
protected BitArray parameterTypeConvertMask; // marks columns that may need type conversion
protected BitArray parameterUnusedMask; // marks unused fields (columns with no target)
protected long parameterUsageCount; // number of parameters used in constructor call
protected BitArray parameterUsageMask; // marks parameters used in method call
protected IList<ParameterInfo> parameters;
// method call information
protected int requiredFoundCount;
protected int requiredParameterCount;
protected Type type;
private MethodInvoker invoker;
#endregion
#region Constructors and Initialization
public MethodMap( MethodBase method, string[] paramNames, Type[] paramTypes, object[] sampleParamValues, bool mustUseAllParameters )
{
type = method.DeclaringType;
this.method = method;
this.paramNames = paramNames;
this.paramTypes = paramTypes;
requiredParameterCount = method.Parameters().Count;
this.mustUseAllParameters = mustUseAllParameters;
parameters = method.Parameters();
InitializeBitArrays( Math.Max( parameters.Count, paramNames.Length ) );
InitializeMethodMap( sampleParamValues );
}
private void InitializeBitArrays( int length )
{
methodParameterUsageMask = new BitArray( parameters.Count );
parameterUsageMask = new BitArray( length );
parameterUnusedMask = new BitArray( length );
parameterTypeConvertMask = new BitArray( length );
parameterReflectionMask = new BitArray( length );
parameterDefaultValueMask = new BitArray( length );
}
#region Map Initialization
private void InitializeMethodMap( object[] sampleParamValues )
{
#region Field initialization
//int normalCount = 0; // number of fields filled with regular parameter values
int defaultCount = 0; // number of fields filled using default values
int nullCount = 0; // number of fields filled using null
int injectionCount = 0; // number of fields filled using external values (dependency injection aka IoC)
parameterOrderMap = new int[paramNames.Length];
for( int i = 0; i < paramNames.Length; i++ )
{
parameterOrderMap[ i ] = -1;
}
parameterUsageCount = 0;
members = new MemberInfo[paramNames.Length];
// use a counter to determine whether we have a column for every parameter
int noColumnForParameter = parameters.Count;
// keep a reverse index for later when we check for default values
parameterOrderMapReverse = new int[noColumnForParameter];
// explicitly mark unused entries as we may have more parameters than columns
for( int i = 0; i < noColumnForParameter; i++ )
{
parameterOrderMapReverse[ i ] = -1;
}
bool isPerfectColumnOrder = true;
#endregion
#region Input parameters loop
for( int invokeParamIndex = 0; invokeParamIndex < paramNames.Length; invokeParamIndex++ )
{
#region Method parameters loop
string paramName = paramNames[ invokeParamIndex ];
Type paramType = paramTypes[ invokeParamIndex ];
bool foundParam = false;
int methodParameterIndex = 0;
string errorText = null;
for( int methodParamIndex = 0; methodParamIndex < parameters.Count; methodParamIndex++ )
{
if( methodParameterUsageMask[ methodParamIndex ] ) // ignore input if we already have an appropriate source
{
continue;
}
methodParameterIndex = methodParamIndex; // preserve loop variable outside loop
ParameterInfo parameter = parameters[ methodParamIndex ];
// permit casing differences to allow for matching lower-case parameters to upper-case properties
if( parameter.HasName( paramName ) )
{
bool compatible = parameter.ParameterType.IsAssignableFrom( paramType );
// avoid checking if implicit conversion is possible
bool convertible = ! compatible && IsConvertible( paramType, parameter.ParameterType, sampleParamValues[ invokeParamIndex ] );
if( compatible || convertible )
{
foundParam = true;
methodParameterUsageMask[ methodParamIndex ] = true;
noColumnForParameter--;
parameterUsageCount++;
parameterUsageMask[ invokeParamIndex ] = true;
parameterOrderMap[ invokeParamIndex ] = methodParamIndex;
parameterOrderMapReverse[ methodParamIndex ] = invokeParamIndex;
isPerfectColumnOrder &= invokeParamIndex == methodParamIndex;
// type conversion required for nullable columns mapping to not-nullable system type
// or when the supplied value type is different from member/parameter type
if( convertible )
{
parameterTypeConvertMask[ invokeParamIndex ] = true;
cost += 1;
}
break;
}
// save a partial exception message in case there is also not a matching member we can set
errorText = string.Format( "constructor parameter {0} of type {1}", parameter.Name, parameter.ParameterType );
}
}
// method can only be invoked if we have the required number of parameters
// parameters are checked from left to right (so any required number wont be enough)
if( foundParam && methodParameterIndex < requiredParameterCount )
{
requiredFoundCount++;
}
#endregion
#region No parameter handling (member check)
if( ! foundParam && method is ConstructorInfo )
{
// check if we can use reflection to set some members
MemberInfo member = type.Property( paramName, Flags.InstanceAnyVisibility | Flags.IgnoreCase );
// try again using leading underscore if nothing was found
member = member ?? type.Property( "_" + paramName, Flags.InstanceAnyVisibility | Flags.IgnoreCase );
// look for fields if we still got no match or property was readonly
if( member == null || ! member.IsWritable() )
{
member = type.Field( paramName, Flags.InstanceAnyVisibility | Flags.IgnoreCase );
// try again using leading underscore if nothing was found
member = member ?? type.Field( "_" + paramName, Flags.InstanceAnyVisibility | Flags.IgnoreCase );
}
bool exists = member != null;
Type memberType = member != null ? member.Type() : null;
bool compatible = exists && memberType.IsAssignableFrom( paramType );
// avoid checking if implicit conversion is possible
bool convertible = exists && ! compatible && IsConvertible( paramType, memberType, sampleParamValues[ invokeParamIndex ] );
if( method.IsConstructor && (compatible || convertible) )
{
members[ invokeParamIndex ] = member;
// input not included in method call but member field or property is present
parameterUsageCount++;
parameterReflectionMask[ invokeParamIndex ] = true;
cost += 10;
// flag input parameter for type conversion
if( convertible )
{
parameterTypeConvertMask[ invokeParamIndex ] = true;
cost += 1;
}
}
else
{
// unused column - not in constructor or as member field
parameterUnusedMask[ invokeParamIndex ] = true;
if( exists || errorText != null )
{
errorText = errorText ?? string.Format( "member {0} of type {1}", member.Name, memberType );
string message = "Input parameter {0} of type {1} is incompatible with {2} (conversion was not possible).";
message = string.Format( message, paramName, paramType, errorText );
throw new ArgumentException( message, paramName );
}
}
}
#endregion
}
#endregion
#region Default value injection
// check whether method has unused parameters
/*
if( noColumnForParameter > 0 )
{
for( int methodParamIndex = 0; methodParamIndex < parameters.Count; methodParamIndex++ )
{
int invokeIndex = parameterOrderMapReverse[ methodParamIndex ];
bool hasValue = invokeIndex != -1;
if( hasValue )
{
hasValue = parameterUsageMask[ invokeIndex ];
}
// only try to supply default values for parameters that do not already have a value
if( ! hasValue )
{
ParameterInfo parameter = parameters[ methodParamIndex ];
bool hasDefaultValue = parameter.HasDefaultValue();
// default value can be a null value, but not for required parameters
bool isDefaultAllowed = methodParamIndex >= requiredParameterCount || hasDefaultValue;
if( isDefaultAllowed )
{
// prefer any explicitly defined default parameter value for the parameter
if( hasDefaultValue )
{
SaveDefaultValue( parameter.Name, parameter.DefaultValue );
parameterDefaultValueMask[ methodParamIndex ] = true;
defaultCount++;
noColumnForParameter--;
}
else if( HasExternalDefaultValue( parameter ) ) // external values (dependency injection)
{
SaveDefaultValue( parameter.Name, GetExternalDefaultValue( parameter ) );
parameterDefaultValueMask[ methodParamIndex ] = true;
injectionCount++;
noColumnForParameter--;
}
else // see if we can use null as the default value
{
if( parameter.ParameterType != null && parameter.IsNullable() )
{
SaveDefaultValue( parameter.Name, null );
parameterDefaultValueMask[ methodParamIndex ] = true;
nullCount++;
noColumnForParameter--;
}
}
}
}
}
}
*/
#endregion
#region Cost calculation and map validity checks
// score 100 if parameter and column count differ
cost += parameterUsageCount == parameters.Count ? 0 : 100;
// score 300 if column order does not match parameter order
cost += isPerfectColumnOrder ? 0 : 300;
// score 600 if type conversion for any column is required
cost += AllUnset( parameterTypeConvertMask ) ? 0 : 600;
// score additinal points if we need to use any kind of default value
cost += defaultCount * 1000 + injectionCount * 1000 + nullCount * 1000;
// determine whether we have a perfect match (can use direct constructor invocation)
isPerfectMatch = isPerfectColumnOrder && parameterUsageCount == parameters.Count;
isPerfectMatch &= parameterUsageCount == paramNames.Length;
isPerfectMatch &= AllUnset( parameterUnusedMask ) && AllUnset( parameterTypeConvertMask );
isPerfectMatch &= cost == 0;
// isValid tells whether this CM can be used with the given columns
isValid = requiredFoundCount == requiredParameterCount && parameterUsageCount >= requiredParameterCount;
isValid &= ! mustUseAllParameters || parameterUsageCount == paramNames.Length;
isValid &= noColumnForParameter == 0;
isValid &= AllSet( methodParameterUsageMask );
// this last specifies that we must use all of the supplied parameters to construct the object
// isValid &= parameterUnusedMask == 0;
#endregion
}
private bool IsConvertible( Type sourceType, Type targetType, object sampleValue )
{
// determine from sample value whether type conversion is needed
object convertedValue = TypeConverter.Get( targetType, sampleValue );
return convertedValue != null && sourceType != convertedValue.GetType();
}
private void SaveDefaultValue( string parameterName, object parameterValue )
{
// perform late initialization of the dictionary for default values
if( parameterDefaultValues == null )
{
parameterDefaultValues = new Dictionary<string, object>();
}
parameterDefaultValues[ parameterName ] = parameterValue;
}
#endregion
#endregion
#region Dependency Injection Helpers
private bool HasExternalDefaultValue( ParameterInfo parameter )
{
// TODO plug in code for DI or DI framework here
return false;
}
private object GetExternalDefaultValue( ParameterInfo parameter )
{
return null;
}
#endregion
#region Parameter Preparation
/// <summary>
/// Perform parameter reordering, null handling and type conversion in preparation
/// of executing the method call.
/// </summary>
/// <param name="row">The callers row of data.</param>
/// <returns>The parameter array to use in the actual invocation.</returns>
protected object[] PrepareParameters( object[] row )
{
var methodParams = new object[ parameters.Count ];
//int firstPotentialDefaultValueIndex = 0;
for( int i = 0; i < row.Length; i++ )
{
// only include columns in constructor
if( parameterUsageMask[ i ] )
{
int index = parameterOrderMap[ i ];
// check whether we need to type convert the input value
object value = row[ i ];
bool convert = parameterTypeConvertMask[ i ];
convert |= value != null && value.GetType() != paramTypes[ i ];
if( convert )
{
value = TypeConverter.Get( parameters[ index ].ParameterType, row[ i ] );
if( value == null )
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat( "Input parameter {0} of type {1} could unexpectedly not be converted to type {2}.{3}",
paramNames[ i ], paramTypes[ i ], parameters[ index ].ParameterType, Environment.NewLine );
sb.AppendFormat( "Conversion was previously possible. Bad input value: {0}", row[ i ] );
throw new ArgumentException( sb.ToString(), paramNames[ i ] );
}
}
methodParams[ index ] = value;
// advance counter of sequential fields used to save some time in the loop below
//if( i == 1 + firstPotentialDefaultValueIndex )
//{
// firstPotentialDefaultValueIndex++;
//}
}
}
// TODO decide whether to support injecting default values
//for (int i = firstPotentialDefaultValueIndex; i < methodParams.Length; i++)
//{
// if (parameterDefaultValueMask[i])
// {
// methodParams[i] = parameterDefaultValues[parameters[i].Name];
// }
//}
return methodParams;
}
#endregion
#region Method Invocation
public virtual object Invoke( object[] row )
{
throw new NotImplementedException( "This method is implemented in subclasses." );
}
public virtual object Invoke( object target, object[] row )
{
object[] methodParameters = isPerfectMatch ? row : PrepareParameters( row );
return invoker.Invoke( target, methodParameters );
}
internal Type[] GetParamTypes()
{
var paramTypes = new Type[parameters.Count];
for( int i = 0; i < parameters.Count; i++ )
{
ParameterInfo pi = parameters[ i ];
paramTypes[ i ] = pi.ParameterType;
}
return paramTypes;
}
#endregion
#region BitArray Helpers
/// <summary>
/// Test whether at least one bit is set in the array. Replaces the old "long != 0" check.
/// </summary>
protected bool AnySet( BitArray bits )
{
return ! AllUnset( bits );
}
/// <summary>
/// Test whether no bits are set in the array. Replaces the old "long == 0" check.
/// </summary>
protected bool AllUnset( BitArray bits )
{
foreach( bool bit in bits )
{
if( bit )
{
return false;
}
}
return true;
}
/// <summary>
/// Test whether no bits are set in the array. Replaces the old "long == 0" check.
/// </summary>
protected bool AllSet( BitArray bits )
{
foreach( bool bit in bits )
{
if( ! bit )
{
return false;
}
}
return true;
}
#endregion
#region Properties
public IDictionary<string, object> ParameterDefaultValues
{
get { return parameterDefaultValues; }
set { parameterDefaultValues = value; }
}
public int ParameterCount
{
get { return parameters.Count; }
}
public int RequiredParameterCount
{
get { return requiredParameterCount; }
}
public virtual long Cost
{
get { return cost; }
}
public bool IsValid
{
get { return isValid; }
}
public bool IsPerfectMatch
{
get { return isPerfectMatch; }
}
#endregion
internal virtual void InitializeInvoker()
{
var mi = method as MethodInfo;
invoker = mi.DelegateForCallMethod();
}
}
}
| |
using System;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Web;
using Moq;
using NUnit.Framework;
using SquishIt.Framework;
using SquishIt.Framework.Files;
using SquishIt.Framework.JavaScript;
using SquishIt.Framework.Minifiers.JavaScript;
using SquishIt.Framework.Renderers;
using SquishIt.Framework.Resolvers;
using SquishIt.Framework.Utilities;
using SquishIt.Tests.Stubs;
using SquishIt.Tests.Helpers;
using HttpContext = SquishIt.Framework.HttpContext;
namespace SquishIt.Tests
{
[TestFixture]
public class JavaScriptBundleTests
{
string javaScript = TestUtilities.NormalizeLineEndings(@"
function product(a, b)
{
return a * b;
}
function sum(a, b){
return a + b;
}");
string minifiedJavaScript = "function product(n,t){return n*t}function sum(n,t){return n+t};\n";
string javaScriptPreMinified = "(function() { alert('should end with parens') })();\n";
string javaScript2 = TestUtilities.NormalizeLineEndings(@"function sum(a, b){
return a + b;
}");
string minifiedJavaScript2 = "function sum(n,t){return n+t};\n";
JavaScriptBundleFactory javaScriptBundleFactory;
[SetUp]
public void Setup()
{
javaScriptBundleFactory = new JavaScriptBundleFactory()
.WithDebuggingEnabled(false)
.WithHasher(new StubHasher("hash"))
.WithContents(javaScript);
//javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript);
}
[Test]
public void CanRenderEmptyBundle_WithHashInFilename()
{
javaScriptBundleFactory.Create().Render("~/js/output_#.js");
}
[Test]
public void CanBundleJavaScript()
{
var tag = javaScriptBundleFactory
.WithDebuggingEnabled(false)
.Create()
.Add("~/js/test.js")
.Render("~/js/output_1.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_1.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_1.js")]);
}
[Test]
public void CanBundleJavascriptWithMinifiedFiles()
{
var firstPath = "first.js";
var secondPath = "second.js";
javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), javaScriptPreMinified);
javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), javaScript2);
var tag = javaScriptBundleFactory
.Create()
.AddMinified(firstPath)
.Add(secondPath)
.Render("script.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"script.js?r=hash\"></script>", tag);
Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);
var output = TestUtilities.NormalizeLineEndings(javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath("script.js")]);
Assert.True(output.StartsWith(javaScriptPreMinified));
Assert.True(output.EndsWith(minifiedJavaScript2));
}
[Test]
public void CanBundleJavascriptWithMinifiedStrings()
{
var tag = javaScriptBundleFactory
.Create()
.AddMinifiedString(javaScriptPreMinified)
.AddString(javaScript2)
.Render("script.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"script.js?r=hash\"></script>", tag);
Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);
var output = TestUtilities.NormalizeLineEndings(javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath("script.js")]);
Assert.True(output.StartsWith(javaScriptPreMinified));
Assert.True(output.EndsWith(minifiedJavaScript2));
}
[Test]
public void CanBundleJavaScriptWithMinifiedDirectories()
{
var path = Guid.NewGuid().ToString();
var path2 = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.js");
var file2 = TestUtilities.PrepareRelativePath(path2 + "\\file2.js");
var resolver = new Mock<IResolver>(MockBehavior.Strict);
resolver.Setup(r => r.IsDirectory(It.IsAny<string>())).Returns(true);
resolver.Setup(r =>
r.ResolveFolder(TestUtilities.PrepareRelativePath(path), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>()))
.Returns(new[] { file1 });
resolver.Setup(r =>
r.ResolveFolder(TestUtilities.PrepareRelativePath(path2), It.IsAny<bool>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<IEnumerable<string>>()))
.Returns(new[] { file2 });
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, resolver.Object))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, javaScript);
frf.SetContentsForFile(file2, javaScriptPreMinified);
var writerFactory = new StubFileWriterFactory();
var tag = javaScriptBundleFactory
.WithDebuggingEnabled(false)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.Create()
.AddDirectory(path)
.AddMinifiedDirectory(path2)
.Render("~/output.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"output.js?r=hash\"></script>", tag);
var content = writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.js")];
Assert.True(content.StartsWith(minifiedJavaScript));
Assert.True(content.EndsWith(javaScriptPreMinified));
}
}
[Test]
public void CanBundleJsVaryingOutputBaseHrefRendersIndependentUrl()
{
var firstPath = "first.js";
var secondPath = "second.js";
javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), javaScript);
javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), javaScript2);
string tag = javaScriptBundleFactory
.Create()
.Add(firstPath)
.Add(secondPath)
.WithOutputBaseHref("http://subdomain.domain.com")
.Render("/js/output.js");
string tagNoBaseHref = javaScriptBundleFactory
.Create()
.Add(firstPath)
.Add(secondPath)
.Render("/js/output.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"http://subdomain.domain.com/js/output.js?r=hash\"></script>", tag);
Assert.AreEqual("<script type=\"text/javascript\" src=\"/js/output.js?r=hash\"></script>", tagNoBaseHref);
}
[Test]
public void RenderNamedUsesOutputBaseHref()
{
var firstPath = "first.js";
var secondPath = "second.js";
javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(firstPath), javaScript);
javaScriptBundleFactory.FileReaderFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(secondPath), javaScript2);
javaScriptBundleFactory
.Create()
.Add(firstPath)
.Add(secondPath)
.WithOutputBaseHref("http://subdomain.domain.com")
.AsNamed("leBundle", "/js/output.js");
var tag = javaScriptBundleFactory
.Create()
.WithOutputBaseHref("http://subdomain.domain.com")
.RenderNamed("leBundle");
Assert.AreEqual("<script type=\"text/javascript\" src=\"http://subdomain.domain.com/js/output.js?r=hash\"></script>", tag);
}
[Test]
public void CanBundleJavaScriptWithQuerystringParameter()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.Render("~/js/output_querystring.js?v=2");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_querystring.js?v=2&r=hash\"></script>", tag);
}
[Test]
public void CanBundleJavaScriptWithoutRevisionHash()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.WithoutRevisionHash()
.Render("~/js/output_querystring.js?v=2");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_querystring.js?v=2\"></script>", tag);
}
[Test]
public void CanCreateNamedBundle()
{
javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.AsNamed("TestNamed", "~/js/output_namedbundle.js");
var tag = javaScriptBundleFactory
.Create()
.RenderNamed("TestNamed");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_namedbundle.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_namedbundle.js")]);
}
[Test]
public void CanBundleJavaScriptWithRemote()
{
var tag = javaScriptBundleFactory
.Create()
.AddRemote("~/js/test.js", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")
.Add("~/js/test.js")
.Render("~/js/output_1_2.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></script><script type=\"text/javascript\" src=\"js/output_1_2.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_1_2.js")]);
}
[Test]
public void CanBundleJavaScriptWithRemoteAndQuerystringParameter()
{
var tag = javaScriptBundleFactory
.Create()
.AddRemote("~/js/test.js", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")
.Add("~/js/test.js")
.Render("~/js/output_querystring.js?v=2_2");
Assert.AreEqual("<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></script><script type=\"text/javascript\" src=\"js/output_querystring.js?v=2_2&r=hash\"></script>", tag);
}
[Test]
public void CanCreateNamedBundleWithRemote()
{
javaScriptBundleFactory
.Create()
.AddRemote("~/js/test.js", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js")
.Add("~/js/test.js")
.AsNamed("TestCdn", "~/js/output_3_2.js");
var tag = javaScriptBundleFactory
.Create()
.RenderNamed("TestCdn");
Assert.AreEqual("<script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js\"></script><script type=\"text/javascript\" src=\"js/output_3_2.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_3_2.js")]);
}
[Test]
public void CanBundleJavaScriptWithEmbeddedResource()
{
var tag = javaScriptBundleFactory
.Create()
.AddEmbeddedResource("~/js/test.js", "SquishIt.Tests://EmbeddedResource.Embedded.js")
.Render("~/js/output_Embedded.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_Embedded.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_Embedded.js")]);
Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);
}
[Test]
public void CanBundleJavaScriptWithRootEmbeddedResource()
{
//this only tests that the resource can be resolved
var tag = javaScriptBundleFactory
.WithDebuggingEnabled(false)
.Create()
.AddRootEmbeddedResource("~/js/test.js", "SquishIt.Tests://RootEmbedded.js")
.Render("~/js/output_Embedded.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_Embedded.js?r=hash\"></script>", tag);
Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_Embedded.js")]);
}
[Test]
public void CanDebugBundleJavaScriptWithEmbeddedResource()
{
var tag = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create()
.AddEmbeddedResource("~/js/test.js", "SquishIt.Tests://EmbeddedResource.Embedded.js")
.Render("~/js/output_Embedded.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/test.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag));
Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);
}
[Test]
public void CanRenderDebugTags()
{
var debugJavaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
debugJavaScriptBundle
.Add("~/js/test1.js")
.Add("~/js/test2.js")
.AsNamed("TestWithDebug", "~/js/output_3.js");
var tag = debugJavaScriptBundle.RenderNamed("TestWithDebug");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/test1.js\"></script>\n<script type=\"text/javascript\" src=\"js/test2.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanRenderPreprocessedDebugTags()
{
var debugJavaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
using(new ScriptPreprocessorScope<StubScriptPreprocessor>(new StubScriptPreprocessor()))
{
string tag = debugJavaScriptBundle
.Add("~/first.script.js")
.Render("output.js");
Assert.AreEqual(
"<script type=\"text/javascript\" src=\"first.script.js.squishit.debug.js\"></script>\n",
TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void CanRenderDebugTagsTwice()
{
var debugJavaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
var debugJavaScriptBundle2 = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
debugJavaScriptBundle
.Add("~/js/test1.js")
.Add("~/js/test2.js")
.AsNamed("TestWithDebug", "~/js/output_4.js");
debugJavaScriptBundle2
.Add("~/js/test1.js")
.Add("~/js/test2.js")
.AsNamed("TestWithDebug", "~/js/output_4.js");
var tag1 = debugJavaScriptBundle.RenderNamed("TestWithDebug");
var tag2 = debugJavaScriptBundle2.RenderNamed("TestWithDebug");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/test1.js\"></script>\n<script type=\"text/javascript\" src=\"js/test2.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag1));
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/test1.js\"></script>\n<script type=\"text/javascript\" src=\"js/test2.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag2));
}
[Test]
public void CanCreateNamedBundleWithDebug()
{
var debugJavaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
debugJavaScriptBundle
.Add("~/js/test1.js")
.Add("~/js/test2.js")
.AsNamed("NamedWithDebug", "~/js/output_5.js");
var tag = debugJavaScriptBundle.RenderNamed("NamedWithDebug");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/test1.js\"></script>\n<script type=\"text/javascript\" src=\"js/test2.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanCreateBundleWithNullMinifier()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.WithMinifier<NullMinifier>()
.Render("~/js/output_6.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_6.js?r=hash\"></script>", tag);
Assert.AreEqual(javaScript + ";\n", javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PreparePath(Environment.CurrentDirectory + @"\js\output_6.js")]);
}
[Test]
public void CanCreateBundleWithJsMinMinifer()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.WithMinifier<JsMinMinifier>()
.Render("~/js/output_7.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_7.js?r=hash\"></script>", tag);
Assert.AreEqual("\nfunction product(a,b)\n{return a*b;}\nfunction sum(a,b){return a+b;};\n", javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_7.js")]);
}
[Test]
public void CanCreateBundleWithJsMinMiniferByPassingInstance()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.WithMinifier(new JsMinMinifier())
.Render("~/js/output_jsmininstance.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_jsmininstance.js?r=hash\"></script>", tag);
Assert.AreEqual("\nfunction product(a,b)\n{return a*b;}\nfunction sum(a,b){return a+b;};\n", javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_jsmininstance.js")]);
}
[Test]
public void CanCreateEmbeddedBundleWithJsMinMinifer()
{
var tag = javaScriptBundleFactory
.Create()
.AddEmbeddedResource("~/js/test.js", "SquishIt.Tests://EmbeddedResource.Embedded.js")
.WithMinifier<JsMinMinifier>()
.Render("~/js/output_embedded7.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_embedded7.js?r=hash\"></script>", tag);
Assert.AreEqual("\nfunction product(a,b)\n{return a*b;}\nfunction sum(a,b){return a+b;};\n", javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_embedded7.js")]);
}
[Test]
public void CanRenderOnlyIfFileMissing()
{
javaScriptBundleFactory.FileReaderFactory.SetFileExists(false);
var javaScriptBundle = javaScriptBundleFactory
.Create();
javaScriptBundle
.Add("~/js/test.js")
.RenderOnlyIfOutputFileMissing()
.Render("~/js/output_9.js");
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_9.js")]);
javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript2);
javaScriptBundleFactory.FileReaderFactory.SetFileExists(true);
javaScriptBundle.ClearCache();
javaScriptBundle
.Add("~/js/test.js")
.RenderOnlyIfOutputFileMissing()
.Render("~/js/output_9.js");
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_9.js")]);
}
[Test]
public void CanRerenderFiles()
{
javaScriptBundleFactory.FileReaderFactory.SetFileExists(false);
var javaScriptBundle = javaScriptBundleFactory
.Create();
var javaScriptBundle2 = javaScriptBundleFactory
.Create();
javaScriptBundle
.Add("~/js/test.js")
.Render("~/js/output_10.js");
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_10.js")]);
javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript2);
javaScriptBundleFactory.FileReaderFactory.SetFileExists(true);
javaScriptBundleFactory.FileWriterFactory.Files.Clear();
javaScriptBundle.ClearCache();
javaScriptBundle2
.Add("~/js/test.js")
.Render("~/js/output_10.js");
Assert.AreEqual("function sum(n,t){return n+t};\n", javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_10.js")]);
}
[Test]
public void CanBundleJavaScriptWithHashInFilename()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.Render("~/js/output_#.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_hash.js\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_hash.js")]);
}
[Test]
public void CanBundleJavaScriptWithUnderscoresInName()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test_file.js")
.Render("~/js/outputunder_#.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/outputunder_hash.js\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\outputunder_hash.js")]);
}
[Test]
public void CanCreateNamedBundleWithForcedRelease()
{
var debugJavaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
debugJavaScriptBundle
.Add("~/js/test.js")
.ForceRelease()
.AsNamed("ForceRelease", "~/js/output_forcerelease.js");
var tag = javaScriptBundleFactory
.Create()
.RenderNamed("ForceRelease");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_forcerelease.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_forcerelease.js")]);
}
[Test]
public void CanBundleJavaScriptWithSingleAttribute()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.WithAttribute("charset", "utf-8")
.Render("~/js/output_att.js");
Assert.AreEqual("<script type=\"text/javascript\" charset=\"utf-8\" src=\"js/output_att.js?r=hash\"></script>", tag);
}
[Test]
public void CanBundleJavaScriptWithSingleMultipleAttributes()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.WithAttribute("charset", "utf-8")
.WithAttribute("other", "value")
.Render("~/js/output_att2.js");
Assert.AreEqual("<script type=\"text/javascript\" charset=\"utf-8\" other=\"value\" src=\"js/output_att2.js?r=hash\"></script>", tag);
}
[Test]
public void CanDebugBundleWithAttribute()
{
string tag = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create()
.Add("~/js/test1.js")
.Add("~/js/test2.js")
.WithAttribute("charset", "utf-8")
.Render("~/js/output_debugattr.js");
Assert.AreEqual("<script type=\"text/javascript\" charset=\"utf-8\" src=\"js/test1.js\"></script>\n<script type=\"text/javascript\" charset=\"utf-8\" src=\"js/test2.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanCreateCachedBundle()
{
var javaScriptBundle = javaScriptBundleFactory
.Create();
var tag = javaScriptBundle
.Add("~/js/test.js")
.AsCached("Test", "~/js/output_2.js");
var content = javaScriptBundle.RenderCached("Test");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_2.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, content);
}
[Test]
public void CanCreateCachedBundleAssetTag()
{
var javaScriptBundle = javaScriptBundleFactory
.Create();
javaScriptBundle
.Add("~/js/test.js")
.AsCached("Test", "~/assets/js/main");
var content = javaScriptBundle.RenderCached("Test");
javaScriptBundle.ClearCache();
var tag = javaScriptBundle.RenderCachedAssetTag("Test");
Assert.AreEqual("<script type=\"text/javascript\" src=\"assets/js/main?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, content);
}
[Test]
public void CanCreateCachedBundleAssetTag_When_Debugging()
{
var javaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
javaScriptBundle
.Add("~/js/test.js")
.AsCached("Test", "~/assets/js/main");
var tag = javaScriptBundle.RenderCachedAssetTag("Test");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/test.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanCreateCachedBundleWithDebug()
{
var tag = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create()
.Add("~/js/test.js")
.AsCached("Test", "~/js/output_2.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/test.js\"></script>\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanCreateCachedBundleWithForceRelease()
{
var debugJavaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
var javaScriptBundle = javaScriptBundleFactory
.Create();
var tag1 = debugJavaScriptBundle
.Add("~/js/test.js")
.ForceRelease()
.AsCached("Test", "~/assets/js/main");
var content = debugJavaScriptBundle.RenderCached("Test");
javaScriptBundle.ClearCache();
var tag2 = debugJavaScriptBundle.RenderCachedAssetTag("Test");
Assert.AreEqual(tag1, tag2);
Assert.AreEqual("<script type=\"text/javascript\" src=\"assets/js/main?r=hash\"></script>", tag1);
Assert.AreEqual(minifiedJavaScript, content);
}
[Test]
public void WithoutTypeAttribute()
{
var tag = javaScriptBundleFactory
.Create()
.Add("~/js/test.js")
.WithoutTypeAttribute()
.Render("~/js/output_1.js");
Assert.AreEqual("<script src=\"js/output_1.js?r=hash\"></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_1.js")]);
}
[Test]
public void CanBundleDirectoryContentsInDebug()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PreparePath(Environment.CurrentDirectory + "\\" + path + "\\file1.js");
var file2 = TestUtilities.PreparePath(Environment.CurrentDirectory + "\\" + path + "\\file2.js");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, javaScript2.Replace("sum", "replace"));
frf.SetContentsForFile(file2, javaScript);
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(true)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.Add(path)
.Render("~/output.js");
var expectedTag = string.Format("<script type=\"text/javascript\" src=\"{0}/file1.js\"></script>\n<script type=\"text/javascript\" src=\"{0}/file2.js\"></script>\n", path);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void CanBundleDirectoryContentsInDebug_Ignores_Duplicates()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PreparePath(Environment.CurrentDirectory + "\\" + path + "\\file1.js");
var file2 = TestUtilities.PreparePath(Environment.CurrentDirectory + "\\" + path + "\\file2.js");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, javaScript2.Replace("sum", "replace"));
frf.SetContentsForFile(file2, javaScript);
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(true)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.Add(path)
.Add(file1)
.Render("~/output.js");
var expectedTag = string.Format("<script type=\"text/javascript\" src=\"{0}/file1.js\"></script>\n<script type=\"text/javascript\" src=\"{0}/file2.js\"></script>\n", path);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void CanBundleDirectoryContentsInDebug_Writes_And_Ignores_Preprocessed_Debug_Files()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.script.js");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file1.script.js.squishit.debug.js");
var content = "some stuffs";
var preprocessor = new StubScriptPreprocessor();
using(new ScriptPreprocessorScope<StubScriptPreprocessor>(preprocessor))
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, content);
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(true)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.Add(path)
.Render("~/output.js");
var expectedTag = string.Format("<script type=\"text/javascript\" src=\"{0}/file1.script.js.squishit.debug.js\"></script>\n", path);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
Assert.AreEqual(content, preprocessor.CalledWith);
Assert.AreEqual(1, writerFactory.Files.Count);
Assert.AreEqual("scripty", writerFactory.Files[file1 + ".squishit.debug.js"]);
}
}
[Test]
public void CanBundleDirectoryContentsInRelease()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.js");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.js");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, javaScript2.Replace("sum", "replace"));
frf.SetContentsForFile(file2, javaScript);
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(false)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.Add(path)
.Render("~/output.js");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hashy\"></script>";
Assert.AreEqual(expectedTag, tag);
var combined = "function replace(n,t){return n+t};\nfunction product(n,t){return n*t}function sum(n,t){return n+t};\n";
Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.js")]);
}
}
[Test]
public void CanBundleDirectoryContentsInRelease_Ignores_Duplicates()
{
var path = Guid.NewGuid().ToString();
var file1 = TestUtilities.PrepareRelativePath(path + "\\file1.js");
var file2 = TestUtilities.PrepareRelativePath(path + "\\file2.js");
using(new ResolverFactoryScope(typeof(FileSystemResolver).FullName, StubResolver.ForDirectory(new[] { file1, file2 })))
{
var frf = new StubFileReaderFactory();
frf.SetContentsForFile(file1, javaScript2.Replace("sum", "replace"));
frf.SetContentsForFile(file2, javaScript);
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(false)
.WithFileReaderFactory(frf)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.Add(path)
.Add(file1)
.Render("~/output.js");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hashy\"></script>";
Assert.AreEqual(expectedTag, tag);
var combined = "function replace(n,t){return n+t};\nfunction product(n,t){return n*t}function sum(n,t){return n+t};\n";
Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.js")]);
}
}
[Test]
public void CanRenderArbitraryStringsInDebug()
{
var js2Format = "{0}{1}";
var subtract = "function sub(a,b){return a-b}";
var divide = "function div(a,b){return a/b}";
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(true)
.Create()
.AddString(javaScript)
.AddString(js2Format, new[] { subtract, divide })
.Render("doesn't matter where...");
var expectedTag = string.Format("<script type=\"text/javascript\">{0}</script>\n<script type=\"text/javascript\">{1}</script>\n", javaScript, string.Format(js2Format, subtract, divide));
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanMaintainOrderBetweenArbitraryAndFileAssetsInRelease()
{
var file1 = "somefile.js";
var file2 = "anotherfile.js";
var subtract = "function sub(a,b){return a-b}";
var minifiedSubtract = "function sub(n,t){return n-t};";
var readerFactory = new StubFileReaderFactory();
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file1), javaScript);
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file2), javaScript2);
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithFileReaderFactory(readerFactory)
.WithFileWriterFactory(writerFactory)
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.AddString(subtract)
.Add(file2)
.Render("test.js");
var expectedTag = string.Format("<script type=\"text/javascript\" src=\"test.js?r=hash\"></script>");
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
var combined = minifiedJavaScript + minifiedSubtract + "\n" + minifiedJavaScript2;
Assert.AreEqual(combined, writerFactory.Files[TestUtilities.PrepareRelativePath(@"test.js")]);
}
[Test]
public void CanMaintainOrderBetweenArbitraryAndFileAssetsInDebug()
{
var file1 = "somefile.js";
var file2 = "anotherfile.js";
var subtract = "function sub(a,b){return a-b}";
var readerFactory = new StubFileReaderFactory();
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file1), javaScript);
readerFactory.SetContentsForFile(TestUtilities.PrepareRelativePath(file2), javaScript2);
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithFileReaderFactory(readerFactory)
.WithFileWriterFactory(writerFactory)
.WithDebuggingEnabled(true)
.Create()
.Add(file1)
.AddString(subtract)
.Add(file2)
.Render("test.js");
var expectedTag = string.Format("<script type=\"text/javascript\" src=\"somefile.js\"></script>\n<script type=\"text/javascript\">{0}</script>\n<script type=\"text/javascript\" src=\"anotherfile.js\"></script>\n"
, subtract);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanRenderArbitraryStringsInDebugAsCached()
{
var debugJavaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
var content = debugJavaScriptBundle
.AddString(javaScript)
.Add("~/js/test.js")
.AsCached("Test3", "~/js/output_2.js");
var cachedContent = debugJavaScriptBundle.RenderCached("Test3");
debugJavaScriptBundle.ClearCache();
var generatedContent = debugJavaScriptBundle.RenderCached("Test3");
Assert.AreEqual(cachedContent, content);
Assert.AreEqual(cachedContent, generatedContent);
}
[Test]
public void CanRenderArbitraryStringsInDebugWithoutType()
{
var js2Format = "{0}{1}";
var subtract = "function sub(a,b){return a-b}";
var divide = "function div(a,b){return a/b}";
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(true)
.Create()
.AddString(javaScript)
.AddString(js2Format, new[] { subtract, divide })
.WithoutTypeAttribute()
.Render("doesn't matter where...");
var expectedTag = string.Format("<script>{0}</script>\n<script>{1}</script>\n", javaScript, string.Format(js2Format, subtract, divide));
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void DoesNotRenderDuplicateArbitraryStringsInDebug()
{
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(true)
.Create()
.AddString(javaScript)
.AddString(javaScript)
.Render("doesn't matter where...");
var expectedTag = string.Format("<script type=\"text/javascript\">{0}</script>\n", javaScript);
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanBundleArbitraryContentsInRelease()
{
var js2Format = "{0}{1}";
var subtract = "function sub(a,b){return a-b}";
var divide = "function div(a,b){return a/b}";
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(false)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.AddString(javaScript)
.AddString(js2Format, new[] { subtract, divide })
.Render("~/output.js");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hashy\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
var minifiedScript = "function product(n,t){return n*t}function sum(n,t){return n+t};\nfunction sub(n,t){return n-t}function div(n,t){return n/t};\n";
Assert.AreEqual(minifiedScript, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.js")]);
}
[Test]
public void CanBundleJavaScriptWithDeferredLoad()
{
var tag = javaScriptBundleFactory
.Create()
.WithDeferredLoad()
.Add("~/js/test.js")
.Render("~/js/output_1.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_1.js?r=hash\" defer></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_1.js")]);
}
[Test]
public void CanBundleJavaScriptWithDeferredLoadLast()
{
var tag = javaScriptBundleFactory
.Create()
.WithAsyncLoad()
.WithDeferredLoad()
.Add("~/js/test.js")
.Render("~/js/output_1.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_1.js?r=hash\" defer></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_1.js")]);
}
[Test]
public void CanBundleJavaScriptWithAsyncLoad()
{
var tag = javaScriptBundleFactory
.Create()
.WithAsyncLoad()
.Add("~/js/test.js")
.Render("~/js/output_1.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_1.js?r=hash\" async></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_1.js")]);
}
[Test]
public void CanBundleJavaScriptWithAsyncLoadLast()
{
var tag = javaScriptBundleFactory
.Create()
.WithDeferredLoad()
.WithAsyncLoad()
.Add("~/js/test.js")
.Render("~/js/output_1.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"js/output_1.js?r=hash\" async></script>", tag);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath(@"js\output_1.js")]);
}
[Test]
public void CanUseArbitraryReleaseFileRenderer()
{
var renderer = new Mock<IRenderer>();
var content = "content";
javaScriptBundleFactory
.Create()
.WithReleaseFileRenderer(renderer.Object)
.AddString(content)
.ForceRelease()
.Render("test.js");
renderer.Verify(r => r.Render(content + ";\n", TestUtilities.PrepareRelativePath("test.js")));
}
[Test]
public void CanIgnoreArbitraryReleaseFileRendererIfDebugging()
{
var renderer = new Mock<IRenderer>(MockBehavior.Strict);
var content = "content";
javaScriptBundleFactory
.Create()
.WithReleaseFileRenderer(renderer.Object)
.AddString(content)
.ForceDebug()
.Render("test.js");
renderer.VerifyAll();
}
[Test]
public void CanIgnoreArbitraryReleaseRendererInDebug()
{
var renderer = new Mock<IRenderer>();
var content = "content";
javaScriptBundleFactory
.Create()
.WithReleaseFileRenderer(renderer.Object)
.AddString(content)
.Render("test.js");
renderer.VerifyAll();
}
[Test]
public void CanIncludeDynamicContentInDebug()
{
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
request.SetupGet(r => r.Url).Returns(new Uri("http://example.com"));
context.SetupGet(c => c.Request).Returns(request.Object);
var javaScriptBundle = javaScriptBundleFactory
.Create();
using(new HttpContextScope(context.Object))
{
javaScriptBundle
.ForceDebug()
.AddDynamic("/some/dynamic/js");
}
var tag = javaScriptBundle
.Render("~/combined_#.js");
Assert.AreEqual(0, javaScriptBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual("<script type=\"text/javascript\" src=\"/some/dynamic/js\"></script>\n", TestUtilities.NormalizeLineEndings(tag));
}
[Test]
public void CanIncludeDynamicContentInRelease()
{
//this doesn't really test the nitty-gritty details (http resolver, download etc...) but its a start
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
request.SetupGet(r => r.Url).Returns(new Uri("http://example.com"));
context.SetupGet(c => c.Request).Returns(request.Object);
var javaScriptBundle = javaScriptBundleFactory
.Create();
using(new HttpContextScope(context.Object))
{
//some/dynamic/js started returning 404s
javaScriptBundle
.ForceRelease()
.AddDynamic("/");
}
var tag = javaScriptBundle
.Render("~/combined.js");
Assert.AreEqual(1, javaScriptBundleFactory.FileWriterFactory.Files.Count);
Assert.AreEqual(minifiedJavaScript, javaScriptBundleFactory.FileWriterFactory.Files[TestUtilities.PrepareRelativePath("combined.js")]);
Assert.AreEqual("<script type=\"text/javascript\" src=\"combined.js?r=hash\"></script>", tag);
}
[Test]
public void RenderRelease_OmitsRenderedTag_IfOnlyRemoteAssets()
{
//this is rendering tag correctly but incorrectly(?) merging both files
using(new ResolverFactoryScope(typeof(HttpResolver).FullName, StubResolver.ForFile("http://www.someurl.com/css/first.css")))
{
string tag = javaScriptBundleFactory
.Create()
.ForceRelease()
.AddRemote("/css/first.js", "http://www.someurl.com/js/first.js")
.Render("/css/output_remote.js");
Assert.AreEqual("<script type=\"text/javascript\" src=\"http://www.someurl.com/js/first.js\"></script>", tag);
Assert.AreEqual(0, javaScriptBundleFactory.FileWriterFactory.Files.Count);
}
}
[Test]
public void CanRenderDistinctBundlesIfSameOutputButDifferentFileNames()
{
var hasher = new Hasher(new RetryableFileOpener());
javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript);
var tag = javaScriptBundleFactory
.WithHasher(hasher)
.Create()
.Add("~/js/test.js")
.Render("~/js/output#.js");
javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript2);
var tag2 = javaScriptBundleFactory
.WithHasher(hasher)
.Create()
.Add("~/js/test2.js")
.Render("~/js/output#.js");
Assert.AreNotEqual(tag, tag2);
}
[Test]
public void CanRenderDistinctBundlesIfSameOutputButDifferentArbitrary()
{
var hasher = new Hasher(new RetryableFileOpener());
var tag = javaScriptBundleFactory
.WithHasher(hasher)
.Create()
.AddString(javaScript)
.Render("~/js/output#.js");
var tag2 = javaScriptBundleFactory
.WithHasher(hasher)
.Create()
.AddString(javaScript2)
.Render("~/js/output#.js");
Assert.AreNotEqual(tag, tag2);
}
[Test]
public void ForceDebugIf()
{
javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript);
var file1 = "test.js";
var file2 = "anothertest.js";
Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true";
var nonDebugContext = new Mock<HttpContextBase>();
nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection());
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.js")).Returns(Path.Combine(Environment.CurrentDirectory, "output.js"));
JavaScriptBundle bundle;
using(new HttpContextScope(nonDebugContext.Object))
{
bundle = javaScriptBundleFactory
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.Add(file2)
.ForceDebugIf(queryStringPredicate);
var tag = bundle.Render("~/output.js");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hash\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
var debugContext = new Mock<HttpContextBase>();
debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } });
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
debugContext.Setup(hcb => hcb.Server.MapPath("/output.js")).Returns(Path.Combine(Environment.CurrentDirectory, "output.js"));
using(new HttpContextScope(debugContext.Object))
{
var tag = bundle.Render("~/output.js");
var expectedTag = "<script type=\"text/javascript\" src=\"test.js\"></script>\n<script type=\"text/javascript\" src=\"anothertest.js\"></script>\n";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(nonDebugContext.Object))
{
var tag = bundle.Render("~/output.js");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hash\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void ForceDebugIf_Named()
{
javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript);
var file1 = "test.js";
var file2 = "anothertest.js";
Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true";
var debugContext = new Mock<HttpContextBase>();
debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } });
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
debugContext.Setup(hcb => hcb.Server.MapPath("/output.js")).Returns(Path.Combine(Environment.CurrentDirectory, "output.js"));
var nonDebugContext = new Mock<HttpContextBase>();
nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection());
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.js")).Returns(Path.Combine(Environment.CurrentDirectory, "output.js"));
using(new HttpContextScope(nonDebugContext.Object))
{
javaScriptBundleFactory
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.Add(file2)
.ForceDebugIf(queryStringPredicate)
.AsNamed("test", "~/output.js");
var tag = javaScriptBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hash\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(debugContext.Object))
{
var tag = javaScriptBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<script type=\"text/javascript\" src=\"test.js\"></script>\n<script type=\"text/javascript\" src=\"anothertest.js\"></script>\n";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(nonDebugContext.Object))
{
var tag = javaScriptBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hash\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void ForceDebugIf_Cached()
{
javaScriptBundleFactory.FileReaderFactory.SetContents(javaScript);
var file1 = "test.js";
var file2 = "anothertest.js";
Func<bool> queryStringPredicate = () => HttpContext.Current.Request.QueryString.AllKeys.Contains("debug") && HttpContext.Current.Request.QueryString["debug"] == "true";
var debugContext = new Mock<HttpContextBase>();
debugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection { { "debug", "true" } });
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
debugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
debugContext.Setup(hcb => hcb.Server.MapPath("/output.js")).Returns(Path.Combine(Environment.CurrentDirectory, "output.js"));
var nonDebugContext = new Mock<HttpContextBase>();
nonDebugContext.Setup(hcb => hcb.Request.QueryString).Returns(new NameValueCollection());
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file1)).Returns(Path.Combine(Environment.CurrentDirectory, file1));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/" + file2)).Returns(Path.Combine(Environment.CurrentDirectory, file2));
nonDebugContext.Setup(hcb => hcb.Server.MapPath("/output.js")).Returns(Path.Combine(Environment.CurrentDirectory, "output.js"));
using(new HttpContextScope(nonDebugContext.Object))
{
javaScriptBundleFactory
.WithDebuggingEnabled(false)
.Create()
.Add(file1)
.Add(file2)
.ForceDebugIf(queryStringPredicate)
.AsCached("test", "~/output.js");
var tag = javaScriptBundleFactory
.Create()
.RenderNamed("test");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hash\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(debugContext.Object))
{
var tag = javaScriptBundleFactory
.Create()
.RenderCachedAssetTag("test");
var expectedTag = "<script type=\"text/javascript\" src=\"test.js\"></script>\n<script type=\"text/javascript\" src=\"anothertest.js\"></script>\n";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
using(new HttpContextScope(nonDebugContext.Object))
{
var tag = javaScriptBundleFactory
.Create()
.RenderCachedAssetTag("test");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hash\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
}
}
[Test]
public void Includes_Semicolon_And_Newline_Between_Scripts()
{
var writerFactory = new StubFileWriterFactory();
var tag = new JavaScriptBundleFactory()
.WithDebuggingEnabled(false)
.WithFileWriterFactory(writerFactory)
.WithHasher(new StubHasher("hashy"))
.Create()
.AddString("first")
.AddString("second")
.Render("~/output.js");
var expectedTag = "<script type=\"text/javascript\" src=\"output.js?r=hashy\"></script>";
Assert.AreEqual(expectedTag, TestUtilities.NormalizeLineEndings(tag));
var minifiedScript = "first;\nsecond;\n";
Assert.AreEqual(minifiedScript, writerFactory.Files[TestUtilities.PrepareRelativePath(@"output.js")]);
}
[Test]
public void CanRenderContentOnly_Release()
{
var javaScriptBundle = javaScriptBundleFactory
.Create();
var content = javaScriptBundle
.Add("~/js/test.js").RenderRawContent("testrelease");
Assert.AreEqual(minifiedJavaScript, content);
Assert.AreEqual(content, javaScriptBundleFactory.Create().RenderCachedRawContent("testrelease"));
}
[Test]
public void CanRenderContentOnly_Debug()
{
var javaScriptBundle = javaScriptBundleFactory
.WithDebuggingEnabled(true)
.Create();
var content = javaScriptBundle
.Add("~/js/test.js").RenderRawContent("testdebug");
Assert.AreEqual(javaScript + ";\n", content);
Assert.AreEqual(content, javaScriptBundleFactory.Create().RenderCachedRawContent("testdebug"));
}
}
}
| |
// 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.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections
{
[ComVisible(true)]
[ComDefaultInterface(typeof(ICodeElements))]
public sealed class NamespaceCollection : AbstractCodeElementCollection
{
internal static EnvDTE.CodeElements Create(
CodeModelState state,
object parent,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey)
{
var collection = new NamespaceCollection(state, parent, fileCodeModel, nodeKey);
return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection);
}
private ComHandle<EnvDTE.FileCodeModel, FileCodeModel> _fileCodeModel;
private SyntaxNodeKey _nodeKey;
private NamespaceCollection(
CodeModelState state,
object parent,
FileCodeModel fileCodeModel,
SyntaxNodeKey nodeKey)
: base(state, parent)
{
Debug.Assert(fileCodeModel != null);
_fileCodeModel = new ComHandle<EnvDTE.FileCodeModel, FileCodeModel>(fileCodeModel);
_nodeKey = nodeKey;
}
private FileCodeModel FileCodeModel
{
get { return _fileCodeModel.Object; }
}
private bool IsRootNamespace
{
get { return _nodeKey == SyntaxNodeKey.Empty; }
}
private SyntaxNode LookupNode()
{
if (!IsRootNamespace)
{
return FileCodeModel.LookupNode(_nodeKey);
}
else
{
return FileCodeModel.GetSyntaxRoot();
}
}
private EnvDTE.CodeElement CreateCodeOptionsStatement(SyntaxNode node, SyntaxNode parentNode)
{
string name;
int ordinal;
CodeModelService.GetOptionNameAndOrdinal(parentNode, node, out name, out ordinal);
return (EnvDTE.CodeElement)CodeOptionsStatement.Create(this.State, this.FileCodeModel, name, ordinal);
}
private EnvDTE.CodeElement CreateCodeImport(SyntaxNode node, AbstractCodeElement parentElement)
{
var name = CodeModelService.GetImportNamespaceOrType(node);
return (EnvDTE.CodeElement)CodeImport.Create(this.State, this.FileCodeModel, parentElement, name);
}
private EnvDTE.CodeElement CreateCodeAttribute(SyntaxNode node, SyntaxNode parentNode, AbstractCodeElement parentElement)
{
string name;
int ordinal;
CodeModelService.GetAttributeNameAndOrdinal(parentNode, node, out name, out ordinal);
return (EnvDTE.CodeElement)CodeAttribute.Create(this.State, this.FileCodeModel, parentElement, name, ordinal);
}
internal override Snapshot CreateSnapshot()
{
var node = LookupNode();
var parentElement = !this.IsRootNamespace
? (AbstractCodeElement)this.Parent
: null;
var nodesBuilder = ImmutableArray.CreateBuilder<SyntaxNode>();
nodesBuilder.AddRange(CodeModelService.GetOptionNodes(node));
nodesBuilder.AddRange(CodeModelService.GetImportNodes(node));
nodesBuilder.AddRange(CodeModelService.GetAttributeNodes(node));
nodesBuilder.AddRange(CodeModelService.GetLogicalSupportedMemberNodes(node));
return new NodeSnapshot(this.State, _fileCodeModel, node, parentElement, nodesBuilder.ToImmutable());
}
protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element)
{
var node = LookupNode();
var parentElement = !this.IsRootNamespace
? (AbstractCodeElement)this.Parent
: null;
int currentIndex = 0;
// Option statements
var optionNodes = CodeModelService.GetOptionNodes(node);
var optionNodeCount = optionNodes.Count();
if (index < currentIndex + optionNodeCount)
{
var child = optionNodes.ElementAt(index - currentIndex);
element = CreateCodeOptionsStatement(child, node);
return true;
}
currentIndex += optionNodeCount;
// Imports/using statements
var importNodes = CodeModelService.GetImportNodes(node);
var importNodeCount = importNodes.Count();
if (index < currentIndex + importNodeCount)
{
var child = importNodes.ElementAt(index - currentIndex);
element = CreateCodeImport(child, parentElement);
return true;
}
currentIndex += importNodeCount;
// Attributes
var attributeNodes = CodeModelService.GetAttributeNodes(node);
var attributeNodeCount = attributeNodes.Count();
if (index < currentIndex + attributeNodeCount)
{
var child = attributeNodes.ElementAt(index - currentIndex);
element = CreateCodeAttribute(child, node, parentElement);
return true;
}
currentIndex += attributeNodeCount;
// Members
var memberNodes = CodeModelService.GetLogicalSupportedMemberNodes(node);
var memberNodeCount = memberNodes.Count();
if (index < currentIndex + memberNodeCount)
{
var child = memberNodes.ElementAt(index - currentIndex);
element = FileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(child);
return true;
}
element = null;
return false;
}
protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element)
{
var node = LookupNode();
var parentElement = !IsRootNamespace
? (AbstractCodeElement)Parent
: null;
// Option statements
foreach (var child in CodeModelService.GetOptionNodes(node))
{
string childName;
int ordinal;
CodeModelService.GetOptionNameAndOrdinal(node, child, out childName, out ordinal);
if (childName == name)
{
element = (EnvDTE.CodeElement)CodeOptionsStatement.Create(State, FileCodeModel, childName, ordinal);
return true;
}
}
// Imports/using statements
foreach (var child in CodeModelService.GetImportNodes(node))
{
var childName = CodeModelService.GetImportNamespaceOrType(child);
if (childName == name)
{
element = (EnvDTE.CodeElement)CodeImport.Create(State, FileCodeModel, parentElement, childName);
return true;
}
}
// Attributes
foreach (var child in CodeModelService.GetAttributeNodes(node))
{
string childName;
int ordinal;
CodeModelService.GetAttributeNameAndOrdinal(node, child, out childName, out ordinal);
if (childName == name)
{
element = (EnvDTE.CodeElement)CodeAttribute.Create(State, FileCodeModel, parentElement, childName, ordinal);
return true;
}
}
// Members
foreach (var child in CodeModelService.GetLogicalSupportedMemberNodes(node))
{
var childName = CodeModelService.GetName(child);
if (childName == name)
{
element = FileCodeModel.CreateCodeElement<EnvDTE.CodeElement>(child);
return true;
}
}
element = null;
return false;
}
public override int Count
{
get
{
var node = LookupNode();
return
CodeModelService.GetOptionNodes(node).Count() +
CodeModelService.GetImportNodes(node).Count() +
CodeModelService.GetAttributeNodes(node).Count() +
CodeModelService.GetLogicalSupportedMemberNodes(node).Count();
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Linq;
using Android.App;
using Android.OS;
using Android.Views;
using Android.Widget;
using System.Collections.Specialized;
using System.Collections.Generic;
using Android.Content;
using Android.Graphics;
namespace Microsoft.WindowsAzure.Mobile.SQLiteStore.Android.Test
{
[Activity]
public class HarnessActivity : Activity
{
private ExpandableListView list;
private TextView runStatus;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
Title = "C# Client Library Tests";
RequestWindowFeature (WindowFeatures.Progress);
SetContentView (Resource.Layout.Harness);
this.runStatus = FindViewById<TextView> (Resource.Id.RunStatus);
this.list = FindViewById<ExpandableListView> (Resource.Id.List);
this.list.SetAdapter (new TestListAdapter (this, App.Listener));
this.list.ChildClick += (sender, e) => {
Intent testIntent = new Intent (this, typeof(TestActivity));
GroupDescription groupDesc = (GroupDescription)this.list.GetItemAtPosition (e.GroupPosition);
TestDescription desc = groupDesc.Tests.ElementAt (e.ChildPosition);
testIntent.PutExtra ("name", desc.Test.Name);
testIntent.PutExtra ("desc", desc.Test.Description);
testIntent.PutExtra ("log", desc.Log);
StartActivity (testIntent);
};
SetProgressBarVisibility (true);
}
protected override void OnStart()
{
base.OnStart();
App.Listener.PropertyChanged += OnListenerPropertyChanged;
SetProgress (App.Listener.Progress);
ShowStatus();
}
protected override void OnStop()
{
base.OnStop();
App.Listener.PropertyChanged -= OnListenerPropertyChanged;
}
private void ShowStatus()
{
RunOnUiThread (() =>
{
if (String.IsNullOrWhiteSpace (App.Listener.Status))
return;
Toast.MakeText (this, App.Listener.Status, ToastLength.Long)
.Show ();
});
}
private void UpdateProgress()
{
RunOnUiThread (() =>
{
SetProgress (App.Listener.Progress);
this.runStatus.Text = String.Format ("Passed: {0} Failed: {1}", App.Harness.Progress - App.Harness.Failures, App.Harness.Failures);
});
}
private void OnListenerPropertyChanged (object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName) {
case "Progress":
UpdateProgress();
break;
case "Status":
ShowStatus();
break;
}
}
class TestListAdapter
: BaseExpandableListAdapter
{
public TestListAdapter (Activity activity, TestListener listener)
{
this.activity = activity;
this.listener = listener;
INotifyCollectionChanged changed = listener.Groups as INotifyCollectionChanged;
if (changed != null)
changed.CollectionChanged += OnGroupsCollectionChanged;
this.groups = new List<GroupDescription> (listener.Groups);
}
public override Java.Lang.Object GetChild (int groupPosition, int childPosition)
{
GroupDescription group = this.groups [groupPosition];
return group.Tests.ElementAt (childPosition);
}
public override long GetChildId (int groupPosition, int childPosition)
{
return groupPosition * (childPosition * 2);
}
public override int GetChildrenCount (int groupPosition)
{
GroupDescription group = this.groups [groupPosition];
return group.Tests.Count;
}
public override View GetChildView (int groupPosition, int childPosition, bool isLastChild, View convertView, ViewGroup parent)
{
GroupDescription group = this.groups [groupPosition];
TestDescription test = group.Tests.ElementAt (childPosition);
View view = convertView;
if (view == null)
view = this.activity.LayoutInflater.Inflate (Resource.Layout.ListedTest, null);
TextView text = view.FindViewById<TextView> (Resource.Id.TestName);
text.Text = test.Test.Name;
if (!test.Test.Passed)
text.SetTextColor (Color.Red);
else
text.SetTextColor (Color.White);
return view;
}
public override Java.Lang.Object GetGroup (int groupPosition)
{
return this.groups [groupPosition];
}
public override long GetGroupId (int groupPosition)
{
return groupPosition;
}
public override View GetGroupView (int groupPosition, bool isExpanded, View convertView, ViewGroup parent)
{
GroupDescription group = this.groups [groupPosition];
View view = convertView;
if (view == null)
view = this.activity.LayoutInflater.Inflate (Resource.Layout.ListedGroup, null);
TextView text = view.FindViewById<TextView> (Resource.Id.TestName);
text.Text = group.Group.Name;
if (group.HasFailures)
text.SetTextColor (Color.Red);
else
text.SetTextColor (Color.White);
return view;
}
public override bool IsChildSelectable (int groupPosition, int childPosition)
{
return true;
}
public override int GroupCount
{
get { return this.groups.Count; }
}
public override bool HasStableIds
{
get { return false; }
}
private List<GroupDescription> groups;
private Activity activity;
private TestListener listener;
void OnTestsCollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
this.activity.RunOnUiThread (() => {
NotifyDataSetChanged ();
});
}
void OnGroupsCollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
this.activity.RunOnUiThread (() => {
foreach (INotifyCollectionChanged notify in this.groups.Select (g => g.Tests).OfType<INotifyCollectionChanged>())
notify.CollectionChanged -= OnTestsCollectionChanged;
this.groups = new List<GroupDescription> (this.listener.Groups);
foreach (INotifyCollectionChanged notify in this.groups.Select (g => g.Tests).OfType<INotifyCollectionChanged>())
notify.CollectionChanged += OnTestsCollectionChanged;
NotifyDataSetChanged ();
});
}
}
}
}
| |
using Signum.Engine.Basics;
using Signum.Engine.Linq;
using Signum.Engine.Maps;
using Signum.Engine.Operations;
using Signum.Entities;
using Signum.Entities.Reflection;
using Signum.Utilities;
using Signum.Utilities.DataStructures;
using Signum.Utilities.Reflection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace Signum.Engine
{
public static class VirtualMList
{
//Order, OrderLine, Order.Lines
public static Dictionary<Type, Dictionary<PropertyRoute, VirtualMListInfo>> RegisteredVirtualMLists = new Dictionary<Type, Dictionary<PropertyRoute, VirtualMListInfo>>();
static readonly Variable<ImmutableStack<Type>> avoidTypes = Statics.ThreadVariable<ImmutableStack<Type>>("avoidVirtualMList");
public static bool ShouldAvoidMListType(Type elementType)
{
var stack = avoidTypes.Value;
return (stack != null && (stack.Contains(elementType) || stack.Contains(typeof(object))));
}
public static bool IsVirtualMList(this PropertyRoute pr)
{
return pr.Type.IsMList() && (RegisteredVirtualMLists.TryGetC(pr.RootType)?.ContainsKey(pr) ?? false);
}
/// <param name="elementType">Use null for every type</param>
public static IDisposable AvoidMListType(Type elementType)
{
avoidTypes.Value = (avoidTypes.Value ?? ImmutableStack<Type>.Empty).Push(elementType);
return new Disposable(() => avoidTypes.Value = avoidTypes.Value.Pop());
}
static readonly Variable<ImmutableStack<Type>> considerNewTypes = Statics.ThreadVariable<ImmutableStack<Type>>("considerNewTypes");
public static bool ShouldConsiderNew(Type parentType)
{
var stack = considerNewTypes.Value;
return (stack != null && (stack.Contains(parentType) || stack.Contains(typeof(object))));
}
/// <param name="parentType">Use null for every type</param>
public static IDisposable ConsiderNewType(Type parentType)
{
considerNewTypes.Value = (considerNewTypes.Value ?? ImmutableStack<Type>.Empty).Push(parentType);
return new Disposable(() => considerNewTypes.Value = considerNewTypes.Value.Pop());
}
public static FluentInclude<T> WithVirtualMList<T, L>(this FluentInclude<T> fi,
Expression<Func<T, MList<L>>> mListField,
Expression<Func<L, Lite<T>?>> backReference,
ExecuteSymbol<L> saveOperation,
DeleteSymbol<L> deleteOperation)
where T : Entity
where L : Entity
{
return fi.WithVirtualMList(mListField, backReference,
onSave: saveOperation == null ? null : new Action<L, T>((line, e) =>
{
line.Execute(saveOperation);
}),
onRemove: deleteOperation == null ? null : new Action<L, T>((line, e) =>
{
line.Delete(deleteOperation);
}));
}
public static FluentInclude<T> WithVirtualMList<T, L>(this FluentInclude<T> fi,
Expression<Func<T, MList<L>>> mListField,
Expression<Func<L, Lite<T>?>> backReference,
Action<L, T>? onSave = null,
Action<L, T>? onRemove = null,
bool? lazyRetrieve = null,
bool? lazyDelete = null) //To avoid StackOverflows
where T : Entity
where L : Entity
{
fi.SchemaBuilder.Include<L>();
var mListPropertRoute = PropertyRoute.Construct(mListField);
var backReferenceRoute = PropertyRoute.Construct(backReference, avoidLastCasting: true);
if (fi.SchemaBuilder.Settings.FieldAttribute<IgnoreAttribute>(mListPropertRoute) == null)
throw new InvalidOperationException($"The property {mListPropertRoute} should have an IgnoreAttribute to be used as Virtual MList");
RegisteredVirtualMLists.GetOrCreate(typeof(T)).Add(mListPropertRoute, new VirtualMListInfo(mListPropertRoute, backReferenceRoute));
var defLazyRetrieve = lazyRetrieve ?? (typeof(L) == typeof(T));
var defLazyDelete = lazyDelete ?? (typeof(L) == typeof(T));
Func<T, MList<L>> getMList = GetAccessor(mListField);
Action<L, Lite<T>>? setter = null;
bool preserveOrder = fi.SchemaBuilder.Settings.FieldAttributes(mListPropertRoute)
.OfType<PreserveOrderAttribute>()
.Any();
if (preserveOrder && !typeof(ICanBeOrdered).IsAssignableFrom(typeof(L)))
throw new InvalidOperationException($"'{typeof(L).Name}' should implement '{nameof(ICanBeOrdered)}' because '{ReflectionTools.GetPropertyInfo(mListField).Name}' contains '[{nameof(PreserveOrderAttribute)}]'");
var sb = fi.SchemaBuilder;
if (defLazyRetrieve)
{
sb.Schema.EntityEvents<T>().Retrieved += (T e, PostRetrievingContext ctx) =>
{
if (ShouldAvoidMListType(typeof(L)))
return;
var mlist = getMList(e);
if (mlist == null)
return;
var query = Database.Query<L>()
.Where(line => backReference.Evaluate(line) == e.ToLite());
MList<L> newList = preserveOrder ?
query.ToVirtualMListWithOrder() :
query.ToVirtualMList();
mlist.AssignAndPostRetrieving(newList, ctx);
};
}
if (preserveOrder)
{
sb.Schema.EntityEvents<T>().RegisterBinding<MList<L>>(mListField,
shouldSet: () => !defLazyRetrieve && !VirtualMList.ShouldAvoidMListType(typeof(L)),
valueExpression: (e, rowId) => Database.Query<L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMListWithOrder(),
valueFunction: (e, rowId, retriever) => Schema.Current.CacheController<L>()!.Enabled ?
Schema.Current.CacheController<L>()!.RequestByBackReference<T>(retriever, backReference, e.ToLite()).ToVirtualMListWithOrder():
Database.Query<L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMListWithOrder()
);
}
else
{
sb.Schema.EntityEvents<T>().RegisterBinding(mListField,
shouldSet: () => !defLazyRetrieve && !VirtualMList.ShouldAvoidMListType(typeof(L)),
valueExpression: (e, rowId) => Database.Query<L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMList(),
valueFunction: (e, rowId, retriever) => Schema.Current.CacheController<L>()!.Enabled ?
Schema.Current.CacheController<L>()!.RequestByBackReference<T>(retriever, backReference, e.ToLite()).ToVirtualMList() :
Database.Query<L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMList()
);
}
sb.Schema.EntityEvents<T>().PreSaving += (T e, PreSavingContext ctx) =>
{
if (VirtualMList.ShouldAvoidMListType(typeof(L)))
return;
var mlist = getMList(e);
if (mlist == null)
return;
if (mlist.Count > 0)
{
var graph = Saver.PreSaving(() => GraphExplorer.FromRoot(mlist).RemoveAllNodes(ctx.Graph));
GraphExplorer.PropagateModifications(graph.Inverse());
var errors = GraphExplorer.FullIntegrityCheck(graph);
if (errors != null)
{
#if DEBUG
var withEntites = errors.WithEntities(graph);
throw new IntegrityCheckException(withEntites);
#else
throw new IntegrityCheckException(errors);
#endif
}
}
if (mlist.IsGraphModified)
e.SetSelfModified();
};
sb.Schema.EntityEvents<T>().Saving += (T e) =>
{
if (VirtualMList.ShouldAvoidMListType(typeof(L)))
return;
var mlist = getMList(e);
if (mlist == null)
return;
if (preserveOrder)
{
mlist.ForEach((o,i) => ((ICanBeOrdered) o).Order = i);
}
if (GraphExplorer.IsGraphModified(mlist))
e.SetModified();
};
sb.Schema.EntityEvents<T>().Saved += (T e, SavedEventArgs args) =>
{
if (VirtualMList.ShouldAvoidMListType(typeof(L)))
return;
var mlist = getMList(e);
if (mlist != null && !GraphExplorer.IsGraphModified(mlist))
return;
if (!(args.WasNew || ShouldConsiderNew(typeof(T))))
{
var oldElements = mlist.EmptyIfNull().Where(line => !line.IsNew);
var query = Database.Query<L>()
.Where(p => backReference.Evaluate(p) == e.ToLite());
if(onRemove == null)
query.Where(p => !oldElements.Contains(p)).UnsafeDelete();
else
query.Where(p => !oldElements.Contains(p)).ToList().ForEach(line => onRemove!(line, e));
}
if (mlist != null)
{
if (mlist.Any())
{
if (setter == null)
setter = CreateSetter(backReference);
mlist.ForEach(line => setter!(line, e.ToLite()));
if (onSave == null)
mlist.SaveList();
else
mlist.ForEach(line => { if (GraphExplorer.IsGraphModified(line)) onSave!(line, e); });
var priv = (IMListPrivate)mlist;
for (int i = 0; i < mlist.Count; i++)
{
if (priv.GetRowId(i) == null)
priv.SetRowId(i, mlist[i].Id);
}
}
mlist.SetCleanModified(false);
}
};
sb.Schema.EntityEvents<T>().PreUnsafeDelete += query =>
{
if (VirtualMList.ShouldAvoidMListType(typeof(L)))
return null;
//You can do a VirtualMList to itself at the table level, but there should not be cycles inside the instances
var toDelete = Database.Query<L>().Where(se => query.Any(e => backReference.Evaluate(se).Is(e)));
if (defLazyDelete)
{
if (toDelete.Any())
toDelete.UnsafeDelete();
}
else
{
toDelete.UnsafeDelete();
}
return null;
};
return fi;
}
public static FluentInclude<T> WithVirtualMListInitializeOnly<T, L>(this FluentInclude<T> fi,
Expression<Func<T, MList<L>>> mListField,
Expression<Func<L, Lite<T>?>> backReference,
Action<L, T>? onSave = null)
where T : Entity
where L : Entity
{
fi.SchemaBuilder.Include<L>();
Func<T, MList<L>> getMList = GetAccessor(mListField);
Action<L, Lite<T>>? setter = null;
var sb = fi.SchemaBuilder;
sb.Schema.EntityEvents<T>().RegisterBinding(mListField,
shouldSet: () => false,
valueExpression: (e, rowId) => Database.Query<L>().Where(line => backReference.Evaluate(line) == e.ToLite()).ExpandLite(line => backReference.Evaluate(line), ExpandLite.ToStringLazy).ToVirtualMListWithOrder()
);
sb.Schema.EntityEvents<T>().Saving += (T e) =>
{
if (VirtualMList.ShouldAvoidMListType(typeof(L)))
return;
var mlist = getMList(e);
if (mlist == null)
return;
if (GraphExplorer.IsGraphModified(getMList(e)))
e.SetModified();
};
sb.Schema.EntityEvents<T>().Saved += (T e, SavedEventArgs args) =>
{
if (VirtualMList.ShouldAvoidMListType(typeof(L)))
return;
var mlist = getMList(e);
if (mlist == null)
return;
if (!GraphExplorer.IsGraphModified(mlist))
return;
if (setter == null)
setter = CreateSetter(backReference);
mlist.ForEach(line => setter!(line, e.ToLite()));
if (onSave == null)
mlist.SaveList();
else
mlist.ForEach(line =>
{
if (GraphExplorer.IsGraphModified(line))
onSave!(line, e);
});
var priv = (IMListPrivate)mlist;
for (int i = 0; i < mlist.Count; i++)
{
if (priv.GetRowId(i) == null)
priv.SetRowId(i, mlist[i].Id);
}
mlist.SetCleanModified(false);
};
return fi;
}
public static Func<T, MList<L>> GetAccessor<T, L>(Expression<Func<T, MList<L>>> mListField)
where T : Entity
where L : Entity
{
var body = mListField.Body;
var param = mListField.Parameters.SingleEx();
var newBody = SafeAccess(param, (MemberExpression)body, body);
return Expression.Lambda<Func<T, MList<L>>>(newBody, mListField.Parameters.Single()).Compile();
}
private static Expression SafeAccess(ParameterExpression param, MemberExpression member, Expression acum)
{
if (member.Expression == param)
return acum;
return SafeAccess(param,
member: (MemberExpression)member.Expression,
acum: Expression.Condition(Expression.Equal(member.Expression, Expression.Constant(null, member.Expression.Type)), Expression.Constant(null, acum.Type), acum)
);
}
public static Action<L, Lite<T>>? CreateSetter<T, L>(Expression<Func<L, Lite<T>?>> getBackReference)
where T : Entity
where L : Entity
{
var body = getBackReference.Body;
if (body.NodeType == ExpressionType.Convert)
body = ((UnaryExpression)body).Operand;
return ReflectionTools.CreateSetter<L, Lite<T>>(((MemberExpression)body).Member);
}
public static MList<T> ToVirtualMListWithOrder<T>(this IEnumerable<T> elements)
where T : Entity
{
return new MList<T>(elements.Select(line => new MList<T>.RowIdElement(line, line.Id, ((ICanBeOrdered)line).Order)));
}
public static MList<T> ToVirtualMList<T>(this IEnumerable<T> elements)
where T : Entity
{
return new MList<T>(elements.Select(line => new MList<T>.RowIdElement(line, line.Id, null)));
}
}
public class VirtualMListInfo
{
public readonly PropertyRoute MListRoute;
public readonly PropertyRoute BackReferenceRoute;
public VirtualMListInfo(PropertyRoute mListRoute, PropertyRoute backReferenceRoute)
{
MListRoute = mListRoute;
BackReferenceRoute = backReferenceRoute;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.IO;
using Jovian.Data;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Jovian.Style;
using System.Web;
using System.Net;
namespace Jovian.Katana
{
class ImageFixer
{
SortedDictionary<string, string> Images;
string path;
public ImageFixer(SortedDictionary<string, string> imgs, string an)
{
path = an;
Images = imgs;
}
public string meval(Match m)
{
string var = m.Groups["img"].Value.ToLower().Trim();
if (Images.ContainsKey(var))
return path + Images[var];
return "-?-";
}
public string Fix(string x)
{
//<!(\s)*IMG\[\"(?<img>.*)\"\](\s)*!>
//<!(\s)*IMG\[\"(?<img>.*)\"\](\s)*!>
try
{
//MessageBox.Show("Fix:" + x);
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"<!(\s)*IMG\[\""(?<img>.*)\""\](\s)*!>", options);
string v = regex.Replace(x, new MatchEvaluator(meval));
//MessageBox.Show("Out:" + v);
return v;
}
catch (Exception z)
{
return x;
}
}
}
class ImageLink
{
public string RemoteFile;
public string LocalFile;
public string App;
public string ModifiedLast;
}
class CSSRenderable
{
public string app;
public string Style;
public int Width;
public int Height;
public string Inner;
public string Hash;
public static string ComputeCacheStyle(string x)
{
string y = x.Replace("(", "_");
y = y.Replace(")", "_");
y = y.Replace("\"", "_");
y = y.Replace("'", "_");
y = y.Replace(".", "_");
return y;
}
public string CacheName()
{
return Hash + "_" + Width + "_" + Height;
}
public CSSRenderable(string a, string sty, int w, int h, string inner, string ha)
{
app = a;
Style = sty;
Width = w;
Height = h;
Inner = inner;
Hash = ha;
}
}
class Ie7Action
{
public string InputHTML;
public string OutputPNG;
public int Width;
public int Height;
}
class Ie7Crank
{
public static void Produce(List<Ie7Action> ie)
{
Ie7Crank ie7 = new Ie7Crank();
ie7.Crank(ie);
}
private void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
try
{
if (e.Url.AbsolutePath.IndexOf(".html") >= 0)
{
Ie7Action a = Actions[Cursor];
//System.Console.WriteLine("Writing:" + a.OutputPNG);
web.Navigate(a.InputHTML);
Bitmap bmp = new Bitmap(a.Width, a.Height);
web.BringToFront();
web.DrawToBitmap(bmp, new System.Drawing.Rectangle(0, 0, a.Width, a.Height));
bmp.Save(a.OutputPNG, ImageFormat.Png);
bmp.Dispose();
Cursor++;
Send();
}
}
catch (Exception z)
{
string zztop = z.ToString();
}
}
private WebBrowser web;
private int Cursor = 0;
private Ie7Action[] Actions;
void Send()
{
try
{
if (Cursor >= Actions.Length)
{
return;
}
Ie7Action a = Actions[Cursor];
web.Navigate(a.InputHTML);
}
catch (Exception z)
{
string zztop = z.ToString();
}
}
public void Crank(List<Ie7Action> ie)
{
web = new WebBrowser();
try
{
web.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.web_DocumentCompleted);
web.Size = new System.Drawing.Size(1000, 1000);
web.ScriptErrorsSuppressed = true;
web.ScrollBarsEnabled = false;
Cursor = 0;
Actions = ie.ToArray();
Send();
}
catch (Exception z)
{
string zztop = z.ToString();
}
}
}
class CSSRender
{
public string App;
public static string SimpleDownload(string url)
{
WebClient TheClient = new WebClient();
StreamReader SR = new StreamReader(TheClient.OpenRead(url));
string Txt = SR.ReadToEnd();
SR.Close();
return Txt;
}
public static string FixImages(string x, SortedDictionary<string, string> mapImg, string app)
{
ImageFixer IF = new ImageFixer(mapImg,app);
return IF.Fix(x);
}
public static CSSRenderable ComputeRenderable(string app, Jovian.Data.Control C, JovianPaths JP, SortedDictionary<string, string> map, SortedDictionary<string, string> mapImg)
{
string oldHash = C._CachedRenderingKey;
C._CachedOrdinal = 100;
C._CachedRenderingKey = "";
xmljr.XmlJrWriter writ = new xmljr.XmlJrWriter(null);
C.WriteXML(writ);
string xml = writ.GetXML();
C._CachedRenderingKey = oldHash;
System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] data = System.Text.Encoding.ASCII.GetBytes(xml);
data = x.ComputeHash(data);
string Hash = "";
for (int i = 0; i < data.Length; i++)
Hash += data[i].ToString("x2").ToLower();
if (C is StyledControl)
{
string inner = "";
if (C is TextPanel)
{
inner += Filtrate.Filter(FixImages((C as TextPanel).InnerCode,mapImg,"http://" + JP.RenderServer + "/apps/" + app + "/"), map);
}
if (C is Jovian.Data.Button)
{
inner += "<span>" + Filtrate.Filter(FixImages((C as Jovian.Data.Button).InnerCode,mapImg,"http://" + JP.RenderServer + "/apps/" + app + "/"), map) + "</span>";
}
if (C is Jovian.Data.DataPanel)
{
inner += Filtrate.Filter(FixImages((C as DataPanel).WholeCode,mapImg,"http://" + JP.RenderServer + "/apps/" + app + "/"), map);
inner += "["+(C as Jovian.Data.DataPanel).RowEncoder+"]";
}
if (C is Jovian.Data.LayerPanel)
{
inner += (C as Jovian.Data.LayerPanel).LayerLink + "->[" + (C as Jovian.Data.LayerPanel).Reference + "]";
}
if (C is SuperStylePanel)
{
for (int k = 0; k < (C as SuperStylePanel).NumberDivs; k++)
{
inner += "<div class=\"" + (C as StyledControl).StyleNormal + "_" + k + "\"></div>";
}
}
return new CSSRenderable(app, (C as StyledControl).StyleNormal, C.Width, C.Height, inner, Hash);
}
if (C is Jovian.Data.Picture)
{
return new CSSRenderable(app, "_IMG_", C.Width, C.Height, "<img src=\"http://" + JP.RenderServer + "/apps/" + app + "/images/" + (C as Jovian.Data.Picture)._Image + "\" />", Hash);
}
return null;
}
public static void UpdateCSSCache(string app, Layer L, JovianPaths JP)
{
try
{
CSSRender cr = new CSSRender();
cr.App = app;
string CSS = SimpleDownload("http://" + JP.RenderServer + "/apps/" + app + "/export.txt");
System.Console.WriteLine(CSS);
SortedDictionary<string, string> CSSMap = new SortedDictionary<string, string>();
SortedDictionary<string, string> IMGMap = new SortedDictionary<string, string>();
string[] css2 = CSS.Split(new char[] { '!' });
for (int cK = 0; cK < css2.Length - 1; cK++)
{
string [] ele = css2[cK].Split(new char[] { '>' });
ele[0] = ele[0].Trim();
if (ele[0].Equals("CSS"))
{
if(!CSSMap.ContainsKey(ele[1].ToLower()))
CSSMap.Add(ele[1].ToLower(), ele[2]);
}
if (ele[0].Equals("IMG"))
{
ele[1] = ele[1].Replace("images/", "");
if(!IMGMap.ContainsKey(ele[1].ToLower()))
IMGMap.Add(ele[1].ToLower(), ele[2]);
}
}
/*
SortedList<string, string> PMapCSS = new SortedList<string, string>();
string Killa = CSS;
int k = Killa.IndexOf("[[[");
while (k >= 0)
{
Killa = Killa.Substring(k + 3);
k = Killa.IndexOf("]]]");
string M = Killa.Substring(0, k);
Killa = Killa.Substring(k + 3);
k = M.IndexOf(":");
string key = M.Substring(0, k);
if (!PMapCSS.ContainsKey(key))
PMapCSS.Add(key, M.Substring(k + 1));
System.Console.WriteLine("Mapping:" + key + " to " + M.Substring(k + 1));
k = Killa.IndexOf("[[[");
}
*/
System.Console.SetOut(System.Console.Out);
List<CSSRenderable> renders = new List<CSSRenderable>();
foreach (Jovian.Data.Control C in L._Controls)
{
CSSRenderable cssr = ComputeRenderable(app, C, JP, CSSMap, IMGMap);
if (cssr != null)
{
System.Console.WriteLine("Looking@" + cssr.Style);
if (CSSMap.ContainsKey(cssr.Style.ToLower()))
{
cssr.Style = CSSMap[cssr.Style.ToLower()];
}
else
{
if (CSSMap.ContainsKey(cssr.Style.ToLower() + "_" + cssr.Width + "_" + cssr.Height))
{
cssr.Style = CSSMap[cssr.Style.ToLower() + "_" + cssr.Width + "_" + cssr.Height];
}
}
string cname = cssr.CacheName();
// System.Console.WriteLine("Checking " + JP.RenderCache + cname + ".png");
bool doit = false;
if (cname.Equals(C._CachedRenderingKey))
{
if (!File.Exists(JP.RenderCache + C._CachedRenderingKey + ".png"))
{
//System.Console.WriteLine("Not Exist:" + JP.RenderCache + C._CachedRenderingKey + ".png");
doit = true;
}
}
else
{
doit = true;
}
if (doit)
{
if (cssr.Style.IndexOf("(") >= 0)
{
}
else
{
C._CachedRenderingKey = cname;
renders.Add(cssr);
}
}
}
}
int Base = new Random().Next() % 1000; // add the datetime stamp
List<Ie7Action> actions = new List<Ie7Action>();
foreach (CSSRenderable cssr in renders)
{
if (cssr.Style.IndexOf("(") < 0)
{
try
{
Ie7Action ie7 = new Ie7Action();
ie7.Width = cssr.Width;
ie7.Height = cssr.Height;
ie7.InputHTML = JP.RenderCache + app + "_" + Base + "_" + cssr.CacheName() + ".html";
ie7.OutputPNG = JP.RenderCache + cssr.CacheName() + ".png";
StreamWriter swHTML = new StreamWriter(ie7.InputHTML);
swHTML.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
swHTML.WriteLine("<html>");
//test_"+app+"_" + Base + ".css"
swHTML.WriteLine("<head><title>" + cssr.CacheName() + "</title><link type=\"text/css\" rel=\"stylesheet\" href=\"http://" + JP.RenderServer + "/apps/" + app + "/style.css?" + Base + "\" /><link type=\"text/css\" rel=\"stylesheet\" href=\"http://" + JP.RenderServer + "/apps/common/style.css?" + Base + "\" /></head>");
swHTML.WriteLine("<body style=\"margin:0px\">");
swHTML.WriteLine("<div class=\"" + cssr.Style + "\" style=\"position:absolute;left:0px;top:0px;width:" + cssr.Width + "px;height:" + cssr.Height + "px;\">" + cssr.Inner + "</div>");
swHTML.WriteLine("</body>");
swHTML.WriteLine("</html>");
swHTML.Flush();
swHTML.Close();
actions.Add(ie7);
}
catch (Exception ez)
{
}
}
}
Ie7Crank.Produce(actions);
}
catch (Exception zoop)
{
}
}
/*
public string meval(Match m)
{
string url = m.Groups["url"].Value;
return ("http://oni/apps/" + App + "/j/" + url).Replace("//", "/"); ;
}
public string RewriteCSSurls(string css)
{
RegexOptions options = RegexOptions.None;
Regex regex = new Regex(@"url(\s)*\((\s)*('|"")?(\s)*(?<url>[A-Za-z.\\/0-9_]*)(\s)*('|"")?(\s)*\)", options);
string vld = regex.Replace(css, new MatchEvaluator(meval));
return vld;
}
*/
/*
public static void UpdateCacheHits(string app, Layer L, string css, string pcss)
{
CSSRender cr = new CSSRender();
cr.App = app;
string cur = Directory.GetCurrentDirectory();
System.Console.WriteLine("Current Directory:" + cur);
//
// need to adapt the css to refere
string base_css = cr.RewriteCSSurls(css);
int Base = new Random().Next() % 1000; // add the datetime stamp
List<CSSRenderable> renders = new List<CSSRenderable>();
StreamWriter swCSS = new StreamWriter("E:\\jk_css_cache\\test_"+app+"_" + Base + ".css");
swCSS.WriteLine(base_css);
CachedCompiler cc = new CachedCompiler(app, pcss, swCSS);
foreach(Jovian.Data.Control C in L._Controls)
{
CSSRenderable cssr = ComputeRenderable(app,C);
if(cssr != null)
{
string cname = cssr.CacheName();
bool doit = false;
if(cname.Equals(C._CachedRenderingKey))
{
if(!File.Exists("E:\\jk_css_cache\\" + C._CachedRenderingKey + ".png"))
{
doit = true;
}
}
else
{
doit = true;
}
if (doit)
{
if (cssr.Style.IndexOf("(") >= 0)
{
cssr.Style = cc.CompilePCSS(cssr.Style, cssr.Width, cssr.Height);
}
renders.Add(cssr);
}
}
}
// compile the pcss and rewrite the list
swCSS.Flush();
swCSS.Close();
List<Ie7Action> actions = new List<Ie7Action>();
foreach (CSSRenderable cssr in renders)
{
if (cssr.Style.IndexOf("(") < 0)
{
Ie7Action ie7 = new Ie7Action();
ie7.Width = cssr.Width;
ie7.Height = cssr.Height;
ie7.InputHTML = "E:\\jk_css_cache\\" + app + "_test_" + Base + "_" + cssr.CacheName() + ".html";
ie7.OutputPNG = "E:\\jk_css_cache\\" + cssr.CacheName() + ".png";
StreamWriter swHTML = new StreamWriter(ie7.InputHTML);
swHTML.WriteLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
swHTML.WriteLine("<html>");
//test_"+app+"_" + Base + ".css"
swHTML.WriteLine("<head><title>"+cssr.CacheName()+"</title><link type=\"text/css\" rel=\"stylesheet\" href=\"test_"+app+"_" + Base + ".css\" /></head>");
swHTML.WriteLine("<body style=\"margin:0px\">");
swHTML.WriteLine("<div class=\""+cssr.Style+"\" style=\"position:absolute;left:0px;top:0px;width:"+cssr.Width+"px;height:"+cssr.Height+"px;\">"+cssr.Inner+"</div>");
swHTML.WriteLine("</body>");
swHTML.WriteLine("</html>");
swHTML.Flush();
swHTML.Close();
actions.Add(ie7);
}
}
Ie7Crank.Produce(actions);
}
*/
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: booking/reservations/reservation_frp_amendment_notification.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Booking.Reservations {
/// <summary>Holder for reflection information generated from booking/reservations/reservation_frp_amendment_notification.proto</summary>
public static partial class ReservationFrpAmendmentNotificationReflection {
#region Descriptor
/// <summary>File descriptor for booking/reservations/reservation_frp_amendment_notification.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ReservationFrpAmendmentNotificationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CkFib29raW5nL3Jlc2VydmF0aW9ucy9yZXNlcnZhdGlvbl9mcnBfYW1lbmRt",
"ZW50X25vdGlmaWNhdGlvbi5wcm90bxIgaG9sbXMudHlwZXMuYm9va2luZy5y",
"ZXNlcnZhdGlvbnMaLmJvb2tpbmcvaW5kaWNhdG9ycy9yZXNlcnZhdGlvbl9p",
"bmRpY2F0b3IucHJvdG8aLmJvb2tpbmcvcmVzZXJ2YXRpb25zL3Jlc2VydmF0",
"aW9uX3N1bW1hcnkucHJvdG8aLmJvb2tpbmcvcHJpY2luZy9wcmV0YXhfcmVz",
"ZXJ2YXRpb25fcXVvdGUucHJvdG8iygIKI1Jlc2VydmF0aW9uRlJQQW1lbmRt",
"ZW50Tm90aWZpY2F0aW9uEhEKCWpfd190b2tlbhgBIAEoCRJJCgtyZXNlcnZh",
"dGlvbhgCIAEoCzI0LmhvbG1zLnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5S",
"ZXNlcnZhdGlvbkluZGljYXRvchIoCiByZXNlcnZhdGlvbl9oYWRfZ3VhcmFu",
"dGVlX3RlbmRlchgDIAEoCBJRChNyZXNlcnZhdGlvbl9zdW1tYXJ5GAQgASgL",
"MjQuaG9sbXMudHlwZXMuYm9va2luZy5yZXNlcnZhdGlvbnMuUmVzZXJ2YXRp",
"b25TdW1tYXJ5EkgKC3ByaWNlX3F1b3RlGAUgASgLMjMuaG9sbXMudHlwZXMu",
"Ym9va2luZy5wcmljaW5nLlByZXRheFJlc2VydmF0aW9uUXVvdGVCOVoUYm9v",
"a2luZy9yZXNlcnZhdGlvbnOqAiBIT0xNUy5UeXBlcy5Cb29raW5nLlJlc2Vy",
"dmF0aW9uc2IGcHJvdG8z"));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Reservations.ReservationSummaryReflection.Descriptor, global::HOLMS.Types.Booking.Pricing.PretaxReservationQuoteReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.Reservations.ReservationFRPAmendmentNotification), global::HOLMS.Types.Booking.Reservations.ReservationFRPAmendmentNotification.Parser, new[]{ "JWToken", "Reservation", "ReservationHadGuaranteeTender", "ReservationSummary", "PriceQuote" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class ReservationFRPAmendmentNotification : pb::IMessage<ReservationFRPAmendmentNotification> {
private static readonly pb::MessageParser<ReservationFRPAmendmentNotification> _parser = new pb::MessageParser<ReservationFRPAmendmentNotification>(() => new ReservationFRPAmendmentNotification());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ReservationFRPAmendmentNotification> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Booking.Reservations.ReservationFrpAmendmentNotificationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationFRPAmendmentNotification() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationFRPAmendmentNotification(ReservationFRPAmendmentNotification other) : this() {
jWToken_ = other.jWToken_;
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
reservationHadGuaranteeTender_ = other.reservationHadGuaranteeTender_;
ReservationSummary = other.reservationSummary_ != null ? other.ReservationSummary.Clone() : null;
PriceQuote = other.priceQuote_ != null ? other.PriceQuote.Clone() : null;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ReservationFRPAmendmentNotification Clone() {
return new ReservationFRPAmendmentNotification(this);
}
/// <summary>Field number for the "j_w_token" field.</summary>
public const int JWTokenFieldNumber = 1;
private string jWToken_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JWToken {
get { return jWToken_; }
set {
jWToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 2;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "reservation_had_guarantee_tender" field.</summary>
public const int ReservationHadGuaranteeTenderFieldNumber = 3;
private bool reservationHadGuaranteeTender_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool ReservationHadGuaranteeTender {
get { return reservationHadGuaranteeTender_; }
set {
reservationHadGuaranteeTender_ = value;
}
}
/// <summary>Field number for the "reservation_summary" field.</summary>
public const int ReservationSummaryFieldNumber = 4;
private global::HOLMS.Types.Booking.Reservations.ReservationSummary reservationSummary_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Reservations.ReservationSummary ReservationSummary {
get { return reservationSummary_; }
set {
reservationSummary_ = value;
}
}
/// <summary>Field number for the "price_quote" field.</summary>
public const int PriceQuoteFieldNumber = 5;
private global::HOLMS.Types.Booking.Pricing.PretaxReservationQuote priceQuote_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Pricing.PretaxReservationQuote PriceQuote {
get { return priceQuote_; }
set {
priceQuote_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ReservationFRPAmendmentNotification);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ReservationFRPAmendmentNotification other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JWToken != other.JWToken) return false;
if (!object.Equals(Reservation, other.Reservation)) return false;
if (ReservationHadGuaranteeTender != other.ReservationHadGuaranteeTender) return false;
if (!object.Equals(ReservationSummary, other.ReservationSummary)) return false;
if (!object.Equals(PriceQuote, other.PriceQuote)) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JWToken.Length != 0) hash ^= JWToken.GetHashCode();
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (ReservationHadGuaranteeTender != false) hash ^= ReservationHadGuaranteeTender.GetHashCode();
if (reservationSummary_ != null) hash ^= ReservationSummary.GetHashCode();
if (priceQuote_ != null) hash ^= PriceQuote.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (JWToken.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JWToken);
}
if (reservation_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Reservation);
}
if (ReservationHadGuaranteeTender != false) {
output.WriteRawTag(24);
output.WriteBool(ReservationHadGuaranteeTender);
}
if (reservationSummary_ != null) {
output.WriteRawTag(34);
output.WriteMessage(ReservationSummary);
}
if (priceQuote_ != null) {
output.WriteRawTag(42);
output.WriteMessage(PriceQuote);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JWToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JWToken);
}
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (ReservationHadGuaranteeTender != false) {
size += 1 + 1;
}
if (reservationSummary_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(ReservationSummary);
}
if (priceQuote_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(PriceQuote);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ReservationFRPAmendmentNotification other) {
if (other == null) {
return;
}
if (other.JWToken.Length != 0) {
JWToken = other.JWToken;
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.ReservationHadGuaranteeTender != false) {
ReservationHadGuaranteeTender = other.ReservationHadGuaranteeTender;
}
if (other.reservationSummary_ != null) {
if (reservationSummary_ == null) {
reservationSummary_ = new global::HOLMS.Types.Booking.Reservations.ReservationSummary();
}
ReservationSummary.MergeFrom(other.ReservationSummary);
}
if (other.priceQuote_ != null) {
if (priceQuote_ == null) {
priceQuote_ = new global::HOLMS.Types.Booking.Pricing.PretaxReservationQuote();
}
PriceQuote.MergeFrom(other.PriceQuote);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
JWToken = input.ReadString();
break;
}
case 18: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 24: {
ReservationHadGuaranteeTender = input.ReadBool();
break;
}
case 34: {
if (reservationSummary_ == null) {
reservationSummary_ = new global::HOLMS.Types.Booking.Reservations.ReservationSummary();
}
input.ReadMessage(reservationSummary_);
break;
}
case 42: {
if (priceQuote_ == null) {
priceQuote_ = new global::HOLMS.Types.Booking.Pricing.PretaxReservationQuote();
}
input.ReadMessage(priceQuote_);
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// 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.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Internal.Log;
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 HighPriorityProcessor : IdleProcessor
{
private readonly IncrementalAnalyzerProcessor _processor;
private readonly Lazy<ImmutableArray<IIncrementalAnalyzer>> _lazyAnalyzers;
private readonly AsyncDocumentWorkItemQueue _workItemQueue;
// whether this processor is running or not
private Task _running;
public HighPriorityProcessor(
IAsynchronousOperationListener listener,
IncrementalAnalyzerProcessor processor,
Lazy<ImmutableArray<IIncrementalAnalyzer>> lazyAnalyzers,
int backOffTimeSpanInMs,
CancellationToken shutdownToken) :
base(listener, backOffTimeSpanInMs, shutdownToken)
{
_processor = processor;
_lazyAnalyzers = lazyAnalyzers;
_running = SpecializedTasks.EmptyTask;
_workItemQueue = new AsyncDocumentWorkItemQueue(processor._registration.ProgressReporter, processor._registration.Workspace);
Start();
}
private ImmutableArray<IIncrementalAnalyzer> Analyzers
{
get
{
return _lazyAnalyzers.Value;
}
}
public Task Running
{
get
{
return _running;
}
}
public bool HasAnyWork
{
get
{
return _workItemQueue.HasAnyWork;
}
}
public void Enqueue(WorkItem item)
{
Contract.ThrowIfFalse(item.DocumentId != null, "can only enqueue a document work item");
// we only put workitem in high priority queue if there is a text change.
// this is to prevent things like opening a file, changing in other files keep enqueuing
// expensive high priority work.
if (!item.InvocationReasons.Contains(PredefinedInvocationReasons.SyntaxChanged))
{
return;
}
// check whether given item is for active document, otherwise, nothing to do here
if (_processor._documentTracker == null ||
_processor._documentTracker.GetActiveDocument() != item.DocumentId)
{
return;
}
// we need to clone due to waiter
EnqueueActiveFileItem(item.With(Listener.BeginAsyncOperation("ActiveFile")));
}
private void EnqueueActiveFileItem(WorkItem item)
{
this.UpdateLastAccessTime();
var added = _workItemQueue.AddOrReplace(item);
Logger.Log(FunctionId.WorkCoordinator_ActiveFileEnqueue, s_enqueueLogger, Environment.TickCount, item.DocumentId, !added);
SolutionCrawlerLogger.LogActiveFileEnqueue(_processor._logAggregator);
}
protected override Task WaitAsync(CancellationToken cancellationToken)
{
return _workItemQueue.WaitAsync(cancellationToken);
}
protected override async Task ExecuteAsync()
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var source = new TaskCompletionSource<object>();
try
{
// mark it as running
_running = source.Task;
// okay, there must be at least one item in the map
// see whether we have work item for the document
WorkItem workItem;
CancellationTokenSource documentCancellation;
Contract.ThrowIfFalse(GetNextWorkItem(out workItem, out documentCancellation));
var solution = _processor.CurrentSolution;
// okay now we have work to do
await ProcessDocumentAsync(solution, this.Analyzers, workItem, documentCancellation).ConfigureAwait(false);
}
catch (Exception e) when (FatalError.ReportUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
finally
{
// mark it as done running
source.SetResult(null);
}
}
private bool GetNextWorkItem(out WorkItem workItem, out CancellationTokenSource documentCancellation)
{
// GetNextWorkItem since it can't fail. we still return bool to confirm that this never fail.
var documentId = _processor._documentTracker.GetActiveDocument();
if (documentId != null)
{
if (_workItemQueue.TryTake(documentId, out workItem, out documentCancellation))
{
return true;
}
}
return _workItemQueue.TryTakeAnyWork(
preferableProjectId: null,
dependencyGraph: _processor.DependencyGraph,
analyzerService: _processor.DiagnosticAnalyzerService,
workItem: out workItem,
source: out documentCancellation);
}
private async Task ProcessDocumentAsync(Solution solution, ImmutableArray<IIncrementalAnalyzer> analyzers, WorkItem workItem, CancellationTokenSource source)
{
if (this.CancellationToken.IsCancellationRequested)
{
return;
}
var processedEverything = false;
var documentId = workItem.DocumentId;
try
{
using (Logger.LogBlock(FunctionId.WorkCoordinator_ProcessDocumentAsync, source.Token))
{
var cancellationToken = source.Token;
var document = solution.GetDocument(documentId);
if (document != null)
{
await ProcessDocumentAnalyzersAsync(document, analyzers, workItem, cancellationToken).ConfigureAwait(false);
}
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 document.
// let's make sure newly enqueued work item has all the flag needed.
if (!processedEverything)
{
_workItemQueue.AddOrReplace(workItem.Retry(this.Listener.BeginAsyncOperation("ReenqueueWorkItem")));
}
SolutionCrawlerLogger.LogProcessActiveFileDocument(_processor._logAggregator, documentId.Id, processedEverything);
// remove one that is finished running
_workItemQueue.RemoveCancellationSource(workItem.DocumentId);
}
}
public void Shutdown()
{
_workItemQueue.Dispose();
}
}
}
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEditor;
using UnityEditor.UI;
using UnityEditorInternal;
using System;
using System.Collections;
using System.Collections.Generic;
namespace UnityEditor.UI
{
[CustomEditor(typeof(UITooltip), true)]
public class UITooltipEditor : Editor {
private SerializedProperty m_DefaultWidthProperty;
private SerializedProperty m_AnchorGraphicProperty;
private SerializedProperty m_AnchorGraphicOffsetProperty;
private SerializedProperty m_followMouseProperty;
private SerializedProperty m_OffsetProperty;
private SerializedProperty m_AnchoredOffsetProperty;
private SerializedProperty m_TransitionProperty;
private SerializedProperty m_TransitionEasingProperty;
private SerializedProperty m_TransitionDurationProperty;
private SerializedProperty m_TitleFontProperty;
private SerializedProperty m_TitleFontStyleProperty;
private SerializedProperty m_TitleFontSizeProperty;
private SerializedProperty m_TitleFontLineSpacingProperty;
private SerializedProperty m_TitleFontColorProperty;
private SerializedProperty m_TitleTextEffectProperty;
private SerializedProperty m_TitleTextEffectColorProperty;
private SerializedProperty m_TitleTextEffectDistanceProperty;
private SerializedProperty m_TitleTextEffectUseGraphicAlphaProperty;
private SerializedProperty m_DescriptionFontProperty;
private SerializedProperty m_DescriptionFontStyleProperty;
private SerializedProperty m_DescriptionFontSizeProperty;
private SerializedProperty m_DescriptionFontLineSpacingProperty;
private SerializedProperty m_DescriptionFontColorProperty;
private SerializedProperty m_DescriptionTextEffectProperty;
private SerializedProperty m_DescriptionTextEffectColorProperty;
private SerializedProperty m_DescriptionTextEffectDistanceProperty;
private SerializedProperty m_DescriptionTextEffectUseGraphicAlphaProperty;
private SerializedProperty m_AttributeFontProperty;
private SerializedProperty m_AttributeFontStyleProperty;
private SerializedProperty m_AttributeFontSizeProperty;
private SerializedProperty m_AttributeFontLineSpacingProperty;
private SerializedProperty m_AttributeFontColorProperty;
private SerializedProperty m_AttributeTextEffectProperty;
private SerializedProperty m_AttributeTextEffectColorProperty;
private SerializedProperty m_AttributeTextEffectDistanceProperty;
private SerializedProperty m_AttributeTextEffectUseGraphicAlphaProperty;
protected virtual void OnEnable()
{
this.m_DefaultWidthProperty = this.serializedObject.FindProperty("m_DefaultWidth");
this.m_AnchorGraphicProperty = this.serializedObject.FindProperty("m_AnchorGraphic");
this.m_AnchorGraphicOffsetProperty = this.serializedObject.FindProperty("m_AnchorGraphicOffset");
this.m_followMouseProperty = this.serializedObject.FindProperty("m_followMouse");
this.m_OffsetProperty = this.serializedObject.FindProperty("m_Offset");
this.m_AnchoredOffsetProperty = this.serializedObject.FindProperty("m_AnchoredOffset");
this.m_TransitionProperty = this.serializedObject.FindProperty("m_Transition");
this.m_TransitionEasingProperty = this.serializedObject.FindProperty("m_TransitionEasing");
this.m_TransitionDurationProperty = this.serializedObject.FindProperty("m_TransitionDuration");
this.m_TitleFontProperty = this.serializedObject.FindProperty("m_TitleFont");
this.m_TitleFontStyleProperty = this.serializedObject.FindProperty("m_TitleFontStyle");
this.m_TitleFontSizeProperty = this.serializedObject.FindProperty("m_TitleFontSize");
this.m_TitleFontLineSpacingProperty = this.serializedObject.FindProperty("m_TitleFontLineSpacing");
this.m_TitleFontColorProperty = this.serializedObject.FindProperty("m_TitleFontColor");
this.m_TitleTextEffectProperty = this.serializedObject.FindProperty("m_TitleTextEffect");
this.m_TitleTextEffectColorProperty = this.serializedObject.FindProperty("m_TitleTextEffectColor");
this.m_TitleTextEffectDistanceProperty = this.serializedObject.FindProperty("m_TitleTextEffectDistance");
this.m_TitleTextEffectUseGraphicAlphaProperty = this.serializedObject.FindProperty("m_TitleTextEffectUseGraphicAlpha");
this.m_DescriptionFontProperty = this.serializedObject.FindProperty("m_DescriptionFont");
this.m_DescriptionFontStyleProperty = this.serializedObject.FindProperty("m_DescriptionFontStyle");
this.m_DescriptionFontSizeProperty = this.serializedObject.FindProperty("m_DescriptionFontSize");
this.m_DescriptionFontLineSpacingProperty = this.serializedObject.FindProperty("m_DescriptionFontLineSpacing");
this.m_DescriptionFontColorProperty = this.serializedObject.FindProperty("m_DescriptionFontColor");
this.m_DescriptionTextEffectProperty = this.serializedObject.FindProperty("m_DescriptionTextEffect");
this.m_DescriptionTextEffectColorProperty = this.serializedObject.FindProperty("m_DescriptionTextEffectColor");
this.m_DescriptionTextEffectDistanceProperty = this.serializedObject.FindProperty("m_DescriptionTextEffectDistance");
this.m_DescriptionTextEffectUseGraphicAlphaProperty = this.serializedObject.FindProperty("m_DescriptionTextEffectUseGraphicAlpha");
this.m_AttributeFontProperty = this.serializedObject.FindProperty("m_AttributeFont");
this.m_AttributeFontStyleProperty = this.serializedObject.FindProperty("m_AttributeFontStyle");
this.m_AttributeFontSizeProperty = this.serializedObject.FindProperty("m_AttributeFontSize");
this.m_AttributeFontLineSpacingProperty = this.serializedObject.FindProperty("m_AttributeFontLineSpacing");
this.m_AttributeFontColorProperty = this.serializedObject.FindProperty("m_AttributeFontColor");
this.m_AttributeTextEffectProperty = this.serializedObject.FindProperty("m_AttributeTextEffect");
this.m_AttributeTextEffectColorProperty = this.serializedObject.FindProperty("m_AttributeTextEffectColor");
this.m_AttributeTextEffectDistanceProperty = this.serializedObject.FindProperty("m_AttributeTextEffectDistance");
this.m_AttributeTextEffectUseGraphicAlphaProperty = this.serializedObject.FindProperty("m_AttributeTextEffectUseGraphicAlpha");
}
public override void OnInspectorGUI()
{
this.serializedObject.Update();
EditorGUILayout.Separator();
this.DrawGeneralProperties();
EditorGUILayout.Separator();
this.DrawAnchorProperties();
EditorGUILayout.Separator();
this.DrawTransitionProperties();
EditorGUILayout.Separator();
this.DrawTitleProperties();
EditorGUILayout.Separator();
this.DrawDescriptionProperties();
EditorGUILayout.Separator();
this.DrawAttributeProperties();
EditorGUILayout.Separator();
this.serializedObject.ApplyModifiedProperties();
}
protected void DrawGeneralProperties()
{
EditorGUILayout.LabelField("General Properties", EditorStyles.boldLabel);
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUIUtility.labelWidth = 150f;
EditorGUILayout.PropertyField(this.m_followMouseProperty, new GUIContent("Follow Mouse"));
EditorGUILayout.PropertyField(this.m_OffsetProperty, new GUIContent("Offset"));
EditorGUILayout.PropertyField(this.m_AnchoredOffsetProperty, new GUIContent("Anchored Offset"));
EditorGUILayout.PropertyField(this.m_DefaultWidthProperty, new GUIContent("Default Width"));
EditorGUIUtility.labelWidth = 120f;
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
protected void DrawTransitionProperties()
{
EditorGUILayout.LabelField("Transition Properties", EditorStyles.boldLabel);
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_TransitionProperty, new GUIContent("Transition"));
UITooltip.Transition transition = (UITooltip.Transition)this.m_TransitionProperty.enumValueIndex;
if (transition != UITooltip.Transition.None)
{
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
if (transition == UITooltip.Transition.Fade)
{
EditorGUILayout.PropertyField(this.m_TransitionEasingProperty, new GUIContent("Easing"));
EditorGUILayout.PropertyField(this.m_TransitionDurationProperty, new GUIContent("Duration"));
}
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
protected void DrawAnchorProperties()
{
EditorGUILayout.LabelField("Anchor Graphic Properties", EditorStyles.boldLabel);
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_AnchorGraphicProperty, new GUIContent("Graphic"));
EditorGUILayout.PropertyField(this.m_AnchorGraphicOffsetProperty, new GUIContent("Offset"));
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
protected void DrawTitleProperties()
{
UITooltip.TextEffectType textEffect = (UITooltip.TextEffectType)this.m_TitleTextEffectProperty.enumValueIndex;
EditorGUILayout.LabelField("Title Properties", EditorStyles.boldLabel);
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_TitleFontProperty, new GUIContent("Font"));
EditorGUILayout.PropertyField(this.m_TitleFontStyleProperty, new GUIContent("Font Style"));
EditorGUILayout.PropertyField(this.m_TitleFontSizeProperty, new GUIContent("Font Size"));
EditorGUILayout.PropertyField(this.m_TitleFontLineSpacingProperty, new GUIContent("Font Line Spacing"));
EditorGUILayout.PropertyField(this.m_TitleFontColorProperty, new GUIContent("Color"));
EditorGUILayout.PropertyField(this.m_TitleTextEffectProperty, new GUIContent("Text Effect"));
if (textEffect == UITooltip.TextEffectType.Shadow || textEffect == UITooltip.TextEffectType.Outline)
{
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_TitleTextEffectColorProperty, new GUIContent("Effect Color"));
EditorGUILayout.PropertyField(this.m_TitleTextEffectDistanceProperty, new GUIContent("Effect Distance"));
EditorGUILayout.PropertyField(this.m_TitleTextEffectUseGraphicAlphaProperty, new GUIContent("Use Graphic Alpha"));
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
protected void DrawDescriptionProperties()
{
UITooltip.TextEffectType textEffect = (UITooltip.TextEffectType)this.m_DescriptionTextEffectProperty.enumValueIndex;
EditorGUILayout.LabelField("Description Properties", EditorStyles.boldLabel);
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_DescriptionFontProperty, new GUIContent("Font"));
EditorGUILayout.PropertyField(this.m_DescriptionFontStyleProperty, new GUIContent("Font Style"));
EditorGUILayout.PropertyField(this.m_DescriptionFontSizeProperty, new GUIContent("Font Size"));
EditorGUILayout.PropertyField(this.m_DescriptionFontLineSpacingProperty, new GUIContent("Font Line Spacing"));
EditorGUILayout.PropertyField(this.m_DescriptionFontColorProperty, new GUIContent("Color"));
EditorGUILayout.PropertyField(this.m_DescriptionTextEffectProperty, new GUIContent("Text Effect"));
if (textEffect == UITooltip.TextEffectType.Shadow || textEffect == UITooltip.TextEffectType.Outline)
{
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_DescriptionTextEffectColorProperty, new GUIContent("Effect Color"));
EditorGUILayout.PropertyField(this.m_DescriptionTextEffectDistanceProperty, new GUIContent("Effect Distance"));
EditorGUILayout.PropertyField(this.m_DescriptionTextEffectUseGraphicAlphaProperty, new GUIContent("Use Graphic Alpha"));
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
protected void DrawAttributeProperties()
{
UITooltip.TextEffectType textEffect = (UITooltip.TextEffectType)this.m_AttributeTextEffectProperty.enumValueIndex;
EditorGUILayout.LabelField("Attribute Properties", EditorStyles.boldLabel);
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_AttributeFontProperty, new GUIContent("Font"));
EditorGUILayout.PropertyField(this.m_AttributeFontStyleProperty, new GUIContent("Font Style"));
EditorGUILayout.PropertyField(this.m_AttributeFontSizeProperty, new GUIContent("Font Size"));
EditorGUILayout.PropertyField(this.m_AttributeFontLineSpacingProperty, new GUIContent("Font Line Spacing"));
EditorGUILayout.PropertyField(this.m_AttributeFontColorProperty, new GUIContent("Color"));
EditorGUILayout.PropertyField(this.m_AttributeTextEffectProperty, new GUIContent("Text Effect"));
if (textEffect == UITooltip.TextEffectType.Shadow || textEffect == UITooltip.TextEffectType.Outline)
{
EditorGUI.indentLevel = (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(this.m_AttributeTextEffectColorProperty, new GUIContent("Effect Color"));
EditorGUILayout.PropertyField(this.m_AttributeTextEffectDistanceProperty, new GUIContent("Effect Distance"));
EditorGUILayout.PropertyField(this.m_AttributeTextEffectUseGraphicAlphaProperty, new GUIContent("Use Graphic Alpha"));
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
EditorGUI.indentLevel = (EditorGUI.indentLevel - 1);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Net.ListenerAsyncResult
//
// Authors:
// Gonzalo Paniagua Javier (gonzalo@ximian.com)
//
// Copyright (c) 2005 Ximian, Inc (http://www.ximian.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.
//
using System.Runtime.ExceptionServices;
using System.Threading;
namespace System.Net
{
internal class ListenerAsyncResult : IAsyncResult
{
private ManualResetEvent _handle;
private bool _synch;
private bool _completed;
private AsyncCallback _cb;
private object _state;
private Exception _exception;
private HttpListenerContext _context;
private object _locker = new object();
private ListenerAsyncResult _forward;
internal readonly HttpListener _parent;
internal bool _endCalled;
internal bool _inGet;
public ListenerAsyncResult(HttpListener parent, AsyncCallback cb, object state)
{
_parent = parent;
_cb = cb;
_state = state;
}
internal void Complete(Exception exc)
{
if (_forward != null)
{
_forward.Complete(exc);
return;
}
_exception = exc;
if (_inGet && (exc is ObjectDisposedException))
_exception = new HttpListenerException((int)HttpStatusCode.InternalServerError, SR.net_listener_close);
lock (_locker)
{
_completed = true;
if (_handle != null)
_handle.Set();
if (_cb != null)
ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this);
}
}
private static WaitCallback s_invokeCB = new WaitCallback(InvokeCallback);
private static void InvokeCallback(object o)
{
ListenerAsyncResult ares = (ListenerAsyncResult)o;
if (ares._forward != null)
{
InvokeCallback(ares._forward);
return;
}
try
{
ares._cb(ares);
}
catch
{
}
}
internal void Complete(HttpListenerContext context)
{
Complete(context, false);
}
internal void Complete(HttpListenerContext context, bool synch)
{
if (_forward != null)
{
_forward.Complete(context, synch);
return;
}
_synch = synch;
_context = context;
lock (_locker)
{
bool authFailure = false;
try
{
context.AuthenticationSchemes = context._listener.SelectAuthenticationScheme(context);
}
catch (OutOfMemoryException oom)
{
context.AuthenticationSchemes = AuthenticationSchemes.Anonymous;
_exception = oom;
}
catch
{
authFailure = true;
context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
}
if (context.AuthenticationSchemes != AuthenticationSchemes.None &&
(context.AuthenticationSchemes & AuthenticationSchemes.Anonymous) != AuthenticationSchemes.Anonymous &&
(context.AuthenticationSchemes & AuthenticationSchemes.Basic) != AuthenticationSchemes.Basic)
{
authFailure = true;
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else if (context.AuthenticationSchemes == AuthenticationSchemes.Basic)
{
HttpStatusCode errorCode = HttpStatusCode.Unauthorized;
string authHeader = context.Request.Headers["Authorization"];
if (authHeader == null ||
!HttpListenerContext.IsBasicHeader(authHeader) ||
authHeader.Length < AuthenticationTypes.Basic.Length + 2 ||
!HttpListenerContext.TryParseBasicAuth(authHeader.Substring(AuthenticationTypes.Basic.Length + 1), out errorCode, out string _, out string __))
{
authFailure = true;
context.Response.StatusCode = (int)errorCode;
if (errorCode == HttpStatusCode.Unauthorized)
{
context.Response.Headers["WWW-Authenticate"] = context.AuthenticationSchemes + " realm=\"" + context._listener.Realm + "\"";
}
}
}
if (authFailure)
{
context.Response.OutputStream.Close();
IAsyncResult ares = context._listener.BeginGetContext(_cb, _state);
_forward = (ListenerAsyncResult)ares;
lock (_forward._locker)
{
if (_handle != null)
_forward._handle = _handle;
}
ListenerAsyncResult next = _forward;
for (int i = 0; next._forward != null; i++)
{
if (i > 20)
Complete(new HttpListenerException((int)HttpStatusCode.Unauthorized, SR.net_listener_auth_errors));
next = next._forward;
}
}
else
{
_completed = true;
_synch = false;
if (_handle != null)
_handle.Set();
if (_cb != null)
ThreadPool.UnsafeQueueUserWorkItem(s_invokeCB, this);
}
}
}
internal HttpListenerContext GetContext()
{
if (_forward != null)
{
return _forward.GetContext();
}
if (_exception != null)
{
ExceptionDispatchInfo.Throw(_exception);
}
return _context;
}
public object AsyncState
{
get
{
if (_forward != null)
return _forward.AsyncState;
return _state;
}
}
public WaitHandle AsyncWaitHandle
{
get
{
if (_forward != null)
return _forward.AsyncWaitHandle;
lock (_locker)
{
if (_handle == null)
_handle = new ManualResetEvent(_completed);
}
return _handle;
}
}
public bool CompletedSynchronously
{
get
{
if (_forward != null)
return _forward.CompletedSynchronously;
return _synch;
}
}
public bool IsCompleted
{
get
{
if (_forward != null)
return _forward.IsCompleted;
lock (_locker)
{
return _completed;
}
}
}
}
}
| |
using System;
using System.Linq;
using UnityEngine;
using Object = UnityEngine.Object;
[System.Serializable]
public partial class AbstractSerialisableAction
{
public string MethodName;
public string InspectorName;
[SerializeField]
public bool Show = false;
// inspector cache
public string[] candidatesMethods = { };
public int index;
public Delegate Sdelegate { get; protected set; }
public AbstractSerialisableAction(string nameInInspector)
{
InspectorName = nameInInspector;
}
public virtual Type DelegateType
{
get { return typeof(Action); }
}
}
[System.Serializable]
public abstract class BaseSerialisableAction : AbstractSerialisableAction, ISerializationCallbackReceiver
{
[SerializeField]
public byte[] _returnTypeData;
[SerializeField]
public byte[] _paramsTypeData;
//[SerializeField]
//public byte[] _DelegateTypeData;
public abstract void CreateDelegate();
public void OnBeforeSerialize()
{
//if (_delegateTypeData != null && _delegateTypeData.Length > 0) return;
//_returnTypeData = DataHelper.Serialise(DelegateType);
if (_returnTypeData != null && _returnTypeData.Length > 0) return;
_returnTypeData = AssemblyReflectionHelper.Serialise(DelegateType.GetMethod("Invoke").ReturnType);
if (_paramsTypeData != null && _paramsTypeData.Length > 0) return;
_paramsTypeData = AssemblyReflectionHelper.Serialise(
DelegateType
.GetMethod("Invoke").
GetParameters().
Select(e => e.ParameterType).ToArray());
//if (_DelegateTypeData != null && _DelegateTypeData.Length > 0 && _delegateType == null)
// _delegateType = DataHelper.Deserialse<Type>(_DelegateTypeData);
}
public void OnAfterDeserialize()
{
if (_returnTypeData != null && _returnTypeData.Length > 0) return;
_returnTypeData = AssemblyReflectionHelper.Serialise(DelegateType.GetMethod("Invoke").ReturnType);
if (_paramsTypeData != null && _paramsTypeData.Length > 0) return;
_paramsTypeData = AssemblyReflectionHelper.Serialise(
DelegateType
.GetMethod("Invoke").
GetParameters().
Select(e => e.ParameterType).ToArray());
//if (_DelegateTypeData != null && _DelegateTypeData.Length > 0 && _delegateType == null)
// _delegateType = DataHelper.Deserialse<Type>(_DelegateTypeData
}
protected BaseSerialisableAction(string inspectorName) : base(inspectorName)
{
OnAfterDeserialize();
}
}
[System.Serializable]
public class SAction : BaseSerialisableAction
{
// public settings
public Object _target;
//[SerializeField]
//public byte[] _DelegateTypeData;
public override void CreateDelegate()
{
if (_target != null && !string.IsNullOrEmpty(MethodName))
{
var methodInfo = _target.GetType().GetMethod(MethodName);
if (methodInfo != null)
Sdelegate = Delegate.CreateDelegate(DelegateType, _target, methodInfo);
}
}
public SAction(string inspectorName) : base(inspectorName)
{
}
}
[System.Serializable]
public class SAction<T> : SAction where T : class
{
public override Type DelegateType
{
get { return typeof(T); }
}
public SAction(string inspectorName) : base(inspectorName)
{
}
}
[System.Serializable]
public class LAction : AbstractSerialisableAction
{
public string NameLibrary;
[SerializeField]
public byte[] _paramsTypeData;
public virtual Type LibraryType { get { return null; } }
public LAction(string inspectorName) : base(inspectorName)
{
}
public void CreateAction()
{
if (LibraryType == null) return;
Reset(LibraryType);
}
public virtual void CreateAction(Type library)
{
Sdelegate = (MethodName == "None" || string.IsNullOrEmpty(MethodName))
? null
: AssemblyReflectionHelper.FindAction<Action>(library, MethodName);
}
public virtual void Reset(Type library)
{
NameLibrary = library.Name;
var temp = AssemblyReflectionHelper.GetInfoMethodsPack<Action>(library);
if (!temp.ContainsKey("None"))
temp.Add("None", "None");
candidatesMethods = temp.Keys.Distinct().Reverse().ToArray();
}
}
public partial class AbstractSerialisableAction
{
public virtual void Invoke<T1>(T1 t)
{
}
public virtual void Invoke<T1, T2>(T1 t, T2 t2)
{
}
}
[System.Serializable]
public class LAction<TAction, TLibrary> : LAction where TAction : class where TLibrary : class
{
public override Type DelegateType
{
get { return typeof(TAction); }
}
public override Type LibraryType
{
get
{
return typeof(TLibrary);
}
}
public override void CreateAction(Type library)
{
//Debug.Log(MethodName);
Sdelegate = (MethodName == "None" || string.IsNullOrEmpty(MethodName))
? null
: AssemblyReflectionHelper.FindDelegate<TAction>(library, MethodName);
}
public override void Reset(Type library)
{
NameLibrary = library.Name;
Debug.Log(NameLibrary);
var temp = AssemblyReflectionHelper.GetInfoMethodsPack<TAction>(library);
if (!temp.ContainsKey("None"))
temp.Add("None", "None");
candidatesMethods = temp.Keys.Distinct().Reverse().ToArray();
}
public LAction(string nameInInspector) : base(nameInInspector)
{
}
}
| |
// Copyright 2009 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using NUnit.Framework;
using static NodaTime.NodaConstants;
namespace NodaTime.Test
{
partial class DurationTest
{
private readonly Duration threeMillion = Duration.FromNanoseconds(3000000L);
private readonly Duration negativeFiftyMillion = Duration.FromNanoseconds(-50000000L);
#region operator +
[Test]
public void OperatorPlus_Zero_IsNeutralElement()
{
Assert.AreEqual(0L, (Duration.Zero + Duration.Zero).ToInt64Nanoseconds(), "0 + 0");
Assert.AreEqual(1L, (Duration.Epsilon + Duration.Zero).ToInt64Nanoseconds(), "1 + 0");
Assert.AreEqual(1L, (Duration.Zero + Duration.Epsilon).ToInt64Nanoseconds(), "0 + 1");
}
[Test]
public void OperatorPlus_NonZero()
{
Assert.AreEqual(3000001L, (threeMillion + Duration.Epsilon).ToInt64Nanoseconds(), "3,000,000 + 1");
Assert.AreEqual(0L, (Duration.Epsilon + Duration.FromNanoseconds(-1)).ToInt64Nanoseconds(), "1 + (-1)");
Assert.AreEqual(-49999999L, (negativeFiftyMillion + Duration.Epsilon).ToInt64Nanoseconds(), "-50,000,000 + 1");
}
[Test]
public void OperatorPlus_MethodEquivalents()
{
Duration x = Duration.FromNanoseconds(100);
Duration y = Duration.FromNanoseconds(200);
Assert.AreEqual(x + y, Duration.Add(x, y));
Assert.AreEqual(x + y, x.Plus(y));
}
#endregion
#region operator -
[Test]
public void OperatorMinus_Zero_IsNeutralElement()
{
Assert.AreEqual(0L, (Duration.Zero - Duration.Zero).ToInt64Nanoseconds(), "0 - 0");
Assert.AreEqual(1L, (Duration.Epsilon - Duration.Zero).ToInt64Nanoseconds(), "1 - 0");
Assert.AreEqual(-1L, (Duration.Zero - Duration.Epsilon).ToInt64Nanoseconds(), "0 - 1");
}
[Test]
public void OperatorMinus_NonZero()
{
Duration negativeEpsilon = Duration.FromNanoseconds(-1L);
Assert.AreEqual(2999999L, (threeMillion - Duration.Epsilon).ToInt64Nanoseconds(), "3,000,000 - 1");
Assert.AreEqual(2L, (Duration.Epsilon - negativeEpsilon).ToInt64Nanoseconds(), "1 - (-1)");
Assert.AreEqual(-50000001L, (negativeFiftyMillion - Duration.Epsilon).ToInt64Nanoseconds(), "-50,000,000 - 1");
}
[Test]
public void OperatorMinus_MethodEquivalents()
{
Duration x = Duration.FromNanoseconds(100);
Duration y = Duration.FromNanoseconds(200);
Assert.AreEqual(x - y, Duration.Subtract(x, y));
Assert.AreEqual(x - y, x.Minus(y));
}
#endregion
#region operator /
[Test]
[TestCase(1, 0, 2, 0, NanosecondsPerDay / 2)]
[TestCase(0, 3000000, 3000, 0, 1000)]
[TestCase(0, 3000000, 2000000, 0, 1)]
[TestCase(0, 3000000, -2000000, -1, NanosecondsPerDay - 1)]
public void OperatorDivision_Int64(int days, long nanoOfDay, long divisor, int expectedDays, long expectedNanoOfDay)
{
var duration = new Duration(days, nanoOfDay);
var actual = duration / divisor;
var expected = new Duration(expectedDays, expectedNanoOfDay);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(2, 100, 2.0, 1, 50)]
[TestCase(2, NanosecondsPerDay / 2, -0.5, -5, 0)]
[TestCase(1, 0, 2, 0, NanosecondsPerDay / 2)]
public void OperatorDivision_Double(int days, long nanoOfDay, double divisor, int expectedDays, long expectedNanoOfDay)
{
var duration = new Duration(days, nanoOfDay);
var actual = duration / divisor;
var expected = new Duration(expectedDays, expectedNanoOfDay);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(1, 0, 2, 0, 0.5)]
[TestCase(1, 0, 0, NanosecondsPerDay / 2, 2.0)]
[TestCase(-1, 0, 3, 0, -1 / 3.0)]
public void OperatorDivision_Duration(int dividendDays, long dividendNanoOfDay, int divisorDays, long divisorNanoOfDay, double expected)
{
var dividend = new Duration(dividendDays, dividendNanoOfDay);
var divisor = new Duration(divisorDays, divisorNanoOfDay);
var actual = dividend / divisor;
Assert.AreEqual(expected, actual);
}
[Test]
public void OperatorDivision_ByZero_Throws()
{
Assert.Throws<DivideByZeroException>(() => (threeMillion / 0d).ToString(), "3000000 / 0");
Assert.Throws<DivideByZeroException>(() => (threeMillion / 0).ToString(), "3000000 / 0");
Assert.Throws<DivideByZeroException>(() => (threeMillion / Duration.Zero).ToString(), "3000000 / 0");
}
[Test]
public void OperatorDivision_MethodEquivalent()
{
Assert.AreEqual(threeMillion / 2000000, Duration.Divide(threeMillion, 2000000));
Assert.AreEqual(threeMillion / 2000000d, Duration.Divide(threeMillion, 2000000d));
Assert.AreEqual(negativeFiftyMillion / threeMillion, Duration.Divide(negativeFiftyMillion, threeMillion));
}
#endregion
#region operator *
[Test]
// "Old" non-zero non-one test cases for posterity's sake.
[TestCase(0, 3000, 1000)]
[TestCase(0, 50000, -1000)]
[TestCase(0, -50000, 1000)]
[TestCase(0, -3000, -1000)]
// Zero
[TestCase(0, 0, 0)]
[TestCase(0, 1, 0)]
[TestCase(0, 3000000, 0)]
[TestCase(0, -50000000, 0)]
[TestCase(1, 1, 0)]
[TestCase(0, 0, 10)]
[TestCase(0, 0, -10)]
// One
[TestCase(0, 3000000, 1)]
[TestCase(0, 0, 1)]
[TestCase(0, -5000000, 1)]
// More interesting cases - explore the boundaries of the fast path.
// This currently assumes that we're optimizing on multiplying "less than 100 days"
// by less than "about a thousand". There's a comment in the code near that constant
// to indicate that these tests would need to change if that constant changes.
[TestCase(-99, 10000, 800)]
[TestCase(-101, 10000, 800)]
[TestCase(-99, 10000, 1234)]
[TestCase(-101, 10000, 1234)]
[TestCase(-99, 10000, -800)]
[TestCase(-101, 10000, -800)]
[TestCase(-99, 10000, -1234)]
[TestCase(-101, 10000, -1234)]
[TestCase(99, 10000, 800)]
[TestCase(101, 10000, 800)]
[TestCase(99, 10000, 1234)]
[TestCase(101, 10000, 1234)]
[TestCase(99, 10000, -800)]
[TestCase(101, 10000, -800)]
[TestCase(99, 10000, -1234)]
[TestCase(101, 10000, -1234)]
public void OperatorMultiplication_Int64(int days, long nanos, long rightOperand)
{
// Rather than expressing an expected answer, just do a "long-hand" version
// using ToBigIntegerNanoseconds and FromNanoseconds, trusting those two operations
// to be correct.
var duration = Duration.FromDays(days) + Duration.FromNanoseconds(nanos);
var actual = duration * rightOperand;
var expected = Duration.FromNanoseconds(duration.ToBigIntegerNanoseconds() * rightOperand);
Assert.AreEqual(expected, actual);
}
[Test]
[TestCase(1, 0, 0.5, 0, NanosecondsPerDay / 2)]
[TestCase(1, 200, 2.5, 2, NanosecondsPerDay / 2 + 500)]
[TestCase(-2, NanosecondsPerDay / 2, 2.0, -3, 0)]
public void OperatorMultiplication_Double(int days, long nanos, double rightOperand, int expectedDays, long expectedNanos)
{
var start = new Duration(days, nanos);
var actual = start * rightOperand;
var expected = new Duration(expectedDays, expectedNanos);
Assert.AreEqual(expected, actual);
}
[Test]
public void Commutation()
{
Assert.AreEqual(threeMillion * 5, 5 * threeMillion);
}
[Test]
public void OperatorMultiplication_MethodEquivalents()
{
Assert.AreEqual(Duration.FromNanoseconds(-50000) * 1000, Duration.Multiply(Duration.FromNanoseconds(-50000), 1000));
Assert.AreEqual(1000 * Duration.FromNanoseconds(-50000), Duration.Multiply(1000, Duration.FromNanoseconds(-50000)));
Assert.AreEqual(Duration.FromNanoseconds(-50000) * 1000d, Duration.Multiply(Duration.FromNanoseconds(-50000), 1000d));
}
#endregion
[Test]
public void UnaryMinusAndNegate()
{
var start = Duration.FromNanoseconds(5000);
var expected = Duration.FromNanoseconds(-5000);
Assert.AreEqual(expected, -start);
Assert.AreEqual(expected, Duration.Negate(start));
}
}
}
| |
// 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.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId
{
public partial class SymbolKeyTest : SymbolKeyTestBase
{
#region "No change to symbol"
[Fact]
public void C2CTypeSymbolUnchanged01()
{
var src1 = @"using System;
public delegate void DFoo(int p1, string p2);
namespace N1.N2
{
public interface IFoo { }
namespace N3
{
public class CFoo
{
public struct SFoo
{
public enum EFoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DFoo(int p1, string p2);
namespace N1.N2
{
public interface IFoo
{
// Add member
N3.CFoo GetClass();
}
namespace N3
{
public class CFoo
{
public struct SFoo
{
// Update member
public enum EFoo { Zero, One, Two }
}
// Add member
public void M(int n) { Console.WriteLine(n); }
}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")]
public void C2CErrorSymbolUnchanged01()
{
var src1 = @"public void Method() { }";
var src2 = @"
public void Method()
{
System.Console.WriteLine(12345);
}
";
var comp1 = CreateCompilationWithMscorlib(src1);
var comp2 = CreateCompilationWithMscorlib(src2);
var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol;
Assert.NotNull(symbol01);
Assert.NotNull(symbol02);
Assert.NotEqual(symbol01.Kind, SymbolKind.ErrorType);
Assert.NotEqual(symbol02.Kind, SymbolKind.ErrorType);
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
[WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")]
public void PartialDefinitionAndImplementationResolveCorrectly()
{
var src = @"using System;
namespace NS
{
public partial class C1
{
partial void M() { }
partial void M();
}
}
";
var comp = CreateCompilationWithMscorlib(src, assemblyName: "Test");
var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var type = ns.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var definition = type.GetMembers("M").First() as IMethodSymbol;
var implementation = definition.PartialImplementationPart;
// Assert that both the definition and implementation resolve back to themselves
Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None));
Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None));
}
[Fact]
[WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")]
public void ExplicitIndexerImplementationResolvesCorrectly()
{
var src = @"
interface I
{
object this[int index] { get; }
}
interface I<T>
{
T this[int index] { get; }
}
class C<T> : I<T>, I
{
object I.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
T I<T>.this[int index]
{
get
{
throw new System.NotImplementedException();
}
}
}
";
var compilation = CreateCompilationWithMscorlib(src, assemblyName: "Test");
var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as NamedTypeSymbol;
var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol;
var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol;
AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false);
Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None));
Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None));
}
#endregion
#region "Change to symbol"
[Fact]
public void C2CTypeSymbolChanged01()
{
var src1 = @"using System;
public delegate void DFoo(int p1);
namespace N1.N2
{
public interface IBase { }
public interface IFoo { }
namespace N3
{
public class CFoo
{
public struct SFoo
{
public enum EFoo { Zero, One }
}
}
}
}
";
var src2 = @"using System;
public delegate void DFoo(int p1, string p2); // add 1 more parameter
namespace N1.N2
{
public interface IBase { }
public interface IFoo : IBase // add base interface
{
}
namespace N3
{
public class CFoo : IFoo // impl interface
{
private struct SFoo // change modifier
{
internal enum EFoo : long { Zero, One } // change base class, and modifier
}
}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[Fact]
public void C2CTypeSymbolChanged02()
{
var src1 = @"using System;
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var src2 = @"
namespace NS
{
internal class C1 // add new C1
{
public string P { get; set; }
}
public class C2 // rename C1 to C2
{
public void M() {}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var typeSym02 = namespace2.GetTypeMembers("C2").Single() as NamedTypeSymbol;
// new C1 resolve to old C1
ResolveAndVerifySymbol(typeSym01, typeSym00, comp1);
// old C1 (new C2) NOT resolve to old C1
var symkey = SymbolKey.Create(typeSym02, CancellationToken.None);
var syminfo = symkey.Resolve(comp1);
Assert.Null(syminfo.Symbol);
}
[Fact]
public void C2CMemberSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
private byte field = 123;
internal string P { get; set; }
public void M(ref int n) { }
event Action<string> myEvent;
}
";
var src2 = @"using System;
public class Test
{
internal protected byte field = 255; // change modifier and init-value
internal string P { get { return null; } } // remove 'set'
public int M(ref int n) { return 0; } // change ret type
event Action<string> myEvent // add add/remove
{
add { }
remove { }
}
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter)
.Where(s => !s.IsAccessor()).OrderBy(s => s.Name);
ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1);
}
[WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")]
[Fact]
public void C2CIndexerSymbolChanged01()
{
var src1 = @"using System;
using System.Collections.Generic;
public class Test
{
public string this[string p1] { set { } }
protected long this[long p1] { set { } }
}
";
var src2 = @"using System;
public class Test
{
internal string this[string p1] { set { } } // change modifier
protected long this[long p1] { get { return 0; } set { } } // add 'get'
}
";
var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test");
var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer);
var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol;
var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer);
ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.None);
ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.None);
}
[Fact]
public void C2CAssemblyChanged01()
{
var src = @"
namespace NS
{
public class C1
{
public void M() {}
}
}
";
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1");
var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2");
var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol;
var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol;
// new C1 resolves to old C1 if we ignore assembly and module ids
ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.IgnoreAssemblyIds);
// new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids
Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.None));
}
[WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")]
public void C2CAssemblyChanged02()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// same identity
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
Symbol sym1 = comp1.Assembly;
Symbol sym2 = comp2.Assembly;
// Not ignoreAssemblyAndModules
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
sym1 = comp1.Assembly.Modules[0];
sym2 = comp2.Assembly.Modules[0];
ResolveAndVerifySymbol(sym1, sym2, comp2);
AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true);
Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")]
public void C2CAssemblyChanged03()
{
var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}";
// -------------------------------------------------------
// different name
var compilation1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1");
var compilation2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2");
ISymbol assembly1 = compilation1.Assembly;
ISymbol assembly2 = compilation2.Assembly;
// different
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.None));
// ignore means ALL assembly/module symbols have same ID
AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true);
// But can NOT be resolved
Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
// Module
var module1 = compilation1.Assembly.Modules[0];
var module2 = compilation2.Assembly.Modules[0];
// different
AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.None, expectEqual: false);
Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.None));
AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds));
}
[Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")]
public void C2CAssemblyChanged04()
{
var src = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
var src2 = @"
[assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")]
[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")]
public class C {}
";
// different versions
var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly");
var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Assembly");
Symbol sym1 = comp1.Assembly;
Symbol sym2 = comp2.Assembly;
// comment is changed to compare Name ONLY
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.None, expectEqual: true);
var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.None);
Assert.Equal(sym1, resolved);
AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds);
Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds));
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Palaso.Code;
using Palaso.Lift.Options;
using Palaso.Reporting;
using Palaso.Text;
namespace Palaso.Lift
{
public interface IPalasoDataObjectProperty : IClonableGeneric<IPalasoDataObjectProperty>
{
PalasoDataObject Parent { set; }
}
public interface IReceivePropertyChangeNotifications
{
void NotifyPropertyChanged(string property);
}
public interface IReferenceContainer
{
string TargetId { get; set; }
string Key { get; set; }
}
public abstract class PalasoDataObject: INotifyPropertyChanged,
IReceivePropertyChangeNotifications
{
[NonSerialized]
private ArrayList _listEventHelpers;
/// <summary>
/// see comment on _parent field of MultiText for an explanation of this field
/// </summary>
private PalasoDataObject _parent;
private List<KeyValuePair<string, IPalasoDataObjectProperty>> _properties;
protected PalasoDataObject(PalasoDataObject parent)
{
_properties = new List<KeyValuePair<string, IPalasoDataObjectProperty>>();
_parent = parent;
}
public IEnumerable<string> PropertiesInUse
{
get { return Properties.Select(prop => prop.Key); }
}
public abstract bool IsEmpty { get; }
/// <summary>
/// see comment on _parent field of MultiText for an explanation of this field
/// </summary>
public PalasoDataObject Parent
{
get { return _parent; }
set
{
Debug.Assert(value != null);
_parent = value;
}
}
public List<KeyValuePair<string, IPalasoDataObjectProperty>> Properties
{
get
{
if (_properties == null)
{
_properties = new List<KeyValuePair<string, IPalasoDataObjectProperty>>();
NotifyPropertyChanged("properties dictionary");
}
return _properties;
}
}
public bool HasProperties
{
get
{
foreach (KeyValuePair<string, IPalasoDataObjectProperty> pair in _properties)
{
if (!IsPropertyEmpty(pair.Value))
{
return true;
}
}
return false;
}
}
public bool HasPropertiesForPurposesOfDeletion
{
get
{ return _properties.Any(pair => !IsPropertyEmptyForPurposesOfDeletion(pair.Value)); }
}
#region INotifyPropertyChanged Members
/// <summary>
/// For INotifyPropertyChanged
/// </summary>
public event PropertyChangedEventHandler PropertyChanged = delegate { };
#endregion
public event EventHandler EmptyObjectsRemoved = delegate { };
/// <summary>
/// Do the non-db40-specific parts of becoming activated
/// </summary>
public void FinishActivation()
{
EmptyObjectsRemoved = delegate { };
WireUpEvents();
}
protected void WireUpList(IBindingList list, string listName)
{
_listEventHelpers.Add(new ListEventHelper(this, list, listName));
}
protected virtual void WireUpEvents()
{
_listEventHelpers = new ArrayList();
PropertyChanged += OnPropertyChanged;
}
private void OnEmptyObjectsRemoved(object sender, EventArgs e)
{
// perculate up
EmptyObjectsRemoved(sender, e);
}
protected void OnEmptyObjectsRemoved()
{
EmptyObjectsRemoved(this, new EventArgs());
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
SomethingWasModified(e.PropertyName);
}
public void WireUpChild(INotifyPropertyChanged child)
{
child.PropertyChanged -= OnChildObjectPropertyChanged;
//prevent the bug where we were acquiring these with each GetProperty<> call
child.PropertyChanged += OnChildObjectPropertyChanged;
if (child is PalasoDataObject)
{
((PalasoDataObject) child).EmptyObjectsRemoved += OnEmptyObjectsRemoved;
}
}
/// <summary>
/// called by the binding list when senses are added, removed, reordered, etc.
/// Also called when the user types in fields, etc.
/// </summary>
/// <remarks>The only side effect of this should be to update the dateModified fields</remarks>
public virtual void SomethingWasModified(string propertyModified)
{
//NO: can't do this until really putting the record to bed;
//only the display code knows when to do that. RemoveEmptyProperties();
}
public virtual void CleanUpAfterEditting()
{
RemoveEmptyProperties();
}
public virtual void CleanUpEmptyObjects() {}
/// <summary>
/// BE CAREFUL about when this is called. Empty properties *should exist*
/// as long as the record is being editted
/// </summary>
public void RemoveEmptyProperties()
{
// remove any custom fields that are empty
int originalCount = Properties.Count;
for (int i = originalCount - 1;i >= 0;i--) // NB: counting backwards
{
//trying to reproduce ws-564
Debug.Assert(Properties.Count > i, "Likely hit the ws-564 bug.");
if (Properties.Count <= i)
{
ErrorReport.ReportNonFatalMessageWithStackTrace(
"The number of properties was orginally {0}, is now {1}, but the index is {2}. PLEASE help us reproduce this bug.",
originalCount,
Properties.Count,
i);
}
object property = Properties[i].Value;
if (property is IReportEmptiness)
{
((IReportEmptiness) property).RemoveEmptyStuff();
}
if (IsPropertyEmpty(property))
{
Logger.WriteMinorEvent("Removing {0} due to emptiness.", property.ToString());
Properties.RemoveAt(i);
// don't: this just makes for false modified events: NotifyPropertyChanged(property.ToString());
}
}
}
private static bool IsPropertyEmpty(object property)
{
if (property is MultiText)
{
return MultiTextBase.IsEmpty((MultiText) property);
}
else if (property is OptionRef)
{
return ((OptionRef) property).IsEmpty;
}
else if (property is OptionRefCollection)
{
return ((OptionRefCollection) property).IsEmpty;
}
else if (property is IReportEmptiness)
{
return ((IReportEmptiness) property).ShouldBeRemovedFromParentDueToEmptiness;
}
// Debug.Fail("Unknown property type");
return false; //don't throw it away if you don't know what it is
}
private static bool IsPropertyEmptyForPurposesOfDeletion(object property)
{
if (property is MultiText)
{
return IsPropertyEmpty(property);
}
else if (property is OptionRef)
{
return true;
}
else if (property is OptionRefCollection)
{
return ((OptionRefCollection) property).ShouldHoldUpDeletionOfParentObject;
}
else if (property is IReportEmptiness)
{
return IsPropertyEmpty(property);
}
return false; //don't throw it away if you don't know what it is
}
public virtual void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
protected virtual void OnChildObjectPropertyChanged(object sender,
PropertyChangedEventArgs e)
{
NotifyPropertyChanged(e.PropertyName);
}
public TContents GetOrCreateProperty<TContents>(string fieldName)
where TContents : class, IPalasoDataObjectProperty, new()
{
TContents value = GetProperty<TContents>(fieldName);
if (value != null)
{
return value;
}
TContents newGuy = new TContents();
//Properties.Add(fieldName, newGuy);
Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(fieldName, newGuy));
newGuy.Parent = this;
//temp hack until mt's use parents for notification
if (newGuy is MultiText)
{
WireUpChild((INotifyPropertyChanged) newGuy);
}
return newGuy;
}
protected void AddProperty(string fieldName, IPalasoDataObjectProperty field)
{
Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(fieldName, field));
field.Parent = this;
//temp hack until mt's use parents for notification
if (field is MultiText)
{
WireUpChild((INotifyPropertyChanged)field);
}
}
/// <summary>
/// Will return null if not found
/// </summary>
/// <typeparam name="TContents"></typeparam>
/// <returns>null if not found</returns>
public TContents GetProperty<TContents>(string fieldName) where TContents : class
//, IParentable
{
KeyValuePair<string, IPalasoDataObjectProperty> found = Properties.Find(p => p.Key == fieldName);
if (found.Key == fieldName)
{
Debug.Assert(found.Value is TContents, "Currently we assume that there is only a single type of object for a given name.");
//temp hack until mt's use parents for notification);on
if (found.Value is MultiText)
{
WireUpChild((INotifyPropertyChanged) found.Value);
}
return found.Value as TContents;
}
return null;
}
/// <summary>
/// Merge in a property from some other object, e.g., when merging senses
/// </summary>
public void MergeProperty(KeyValuePair<string, IPalasoDataObjectProperty> incoming)
{
KeyValuePair<string, IPalasoDataObjectProperty> existing = Properties.Find(
p => p.Key == incoming.Key
);
if (existing.Value is OptionRefCollection)
{
if (existing.Key == incoming.Key)
{
var optionRefCollection = existing.Value as OptionRefCollection;
var incomingRefCollection = incoming.Value as OptionRefCollection;
optionRefCollection.MergeByKey(incomingRefCollection);
} else
{
Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(incoming.Key, incoming.Value));
}
}
else
{
if (existing.Key == incoming.Key)
{
Properties.Remove(existing);
}
Properties.Add(new KeyValuePair<string, IPalasoDataObjectProperty>(incoming.Key, incoming.Value));
}
incoming.Value.Parent = this;
//temp hack until mt's use parents for notification
if (incoming.Value is MultiText)
{
WireUpChild((INotifyPropertyChanged)incoming.Value);
}
}
public bool GetHasFlag(string propertyName)
{
FlagState flag = GetProperty<FlagState>(propertyName);
if (flag == null)
{
return false;
}
return flag.Value;
}
/// <summary>
///
/// </summary>
///<remarks>Seting a flag is represented by creating a property and giving it a "set"
/// value, though that is not really meaningful (there are no other possible values).</remarks>
/// <param name="propertyName"></param>
public void SetFlag(string propertyName)
{
FlagState f = GetOrCreateProperty<FlagState>(propertyName);
f.Value = true;
// KeyValuePair<FlagState, object> found = Properties.Find(delegate(KeyValuePair<FlagState, object> p) { return p.Key == propertyName; });
// if (found.Key == propertyName)
// {
// _properties.Remove(found);
// }
//
// Properties.Add(new KeyValuePair<string, object>(propertyName, "set"));
}
/// <summary>
///
/// </summary>
/// <remarks>Clearing a flag is represented by just removing the property, if it exists</remarks>
/// <param name="propertyName"></param>
public void ClearFlag(string propertyName)
{
KeyValuePair<string, IPalasoDataObjectProperty> found = Properties.Find(p => p.Key == propertyName);
if (found.Key == propertyName)
{
_properties.Remove(found);
}
}
#region Nested type: WellKnownProperties
public class WellKnownProperties
{
public static string Note = "note";
public static bool Contains(string fieldName)
{
List<string> list = new List<string>(new string[] {Note});
return list.Contains(fieldName);
}
} ;
#endregion
public static string GetEmbeddedXmlNameForProperty(string name)
{
return name + "-xml";
}
public override bool Equals(Object obj)
{
if (!(obj is PalasoDataObject)) return false;
return Equals((PalasoDataObject)obj);
}
public bool Equals(PalasoDataObject other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
if (!_properties.SequenceEqual(other._properties)) return false;
return true;
}
}
public interface IReportEmptiness
{
bool ShouldHoldUpDeletionOfParentObject { get; }
bool ShouldCountAsFilledForPurposesOfConditionalDisplay { get; }
bool ShouldBeRemovedFromParentDueToEmptiness { get; }
void RemoveEmptyStuff();
}
/// <summary>
/// This class enables creating the necessary event subscriptions. It was added
/// before we were forced to add "parent" fields to everything. I could probably
/// be removed now, since that field could be used by children to cause the wiring,
/// but we are hoping that the parent field might go away with future version of db4o.
/// </summary>
public class ListEventHelper
{
private readonly string _listName;
private readonly PalasoDataObject _listOwner;
public ListEventHelper(PalasoDataObject listOwner, IBindingList list, string listName)
{
_listOwner = listOwner;
_listName = listName;
list.ListChanged += OnListChanged;
foreach (INotifyPropertyChanged x in list)
{
_listOwner.WireUpChild(x);
}
}
private void OnListChanged(object sender, ListChangedEventArgs e)
{
if (e.ListChangedType == ListChangedType.ItemAdded)
{
IBindingList list = (IBindingList) sender;
INotifyPropertyChanged newGuy = (INotifyPropertyChanged) list[e.NewIndex];
_listOwner.WireUpChild(newGuy);
if (newGuy is PalasoDataObject)
{
((PalasoDataObject) newGuy).Parent = _listOwner;
}
}
_listOwner.NotifyPropertyChanged(_listName);
}
}
public class EmbeddedXmlCollection: IPalasoDataObjectProperty
{
private List<string> _values;
private PalasoDataObject _parent;
public EmbeddedXmlCollection()
{
_values = new List<string>();
}
public PalasoDataObject Parent
{
set { _parent = value; }
}
public List<string> Values
{
get { return _values; }
set { _values = value; }
}
public IPalasoDataObjectProperty Clone()
{
var clone = new EmbeddedXmlCollection();
clone._values.AddRange(_values);
return clone;
}
public override bool Equals(object other)
{
return Equals((EmbeddedXmlCollection)other);
}
public bool Equals(IPalasoDataObjectProperty other)
{
return Equals((EmbeddedXmlCollection) other);
}
public bool Equals(EmbeddedXmlCollection other)
{
if (other == null) return false;
if (!_values.SequenceEqual(other._values)) return false; //order is relevant
return true;
}
public override string ToString()
{
var builder = new StringBuilder();
foreach (var part in Values)
{
builder.Append(part.ToString() + " ");
}
return builder.ToString().Trim();
}
}
}
| |
// 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 Microsoft.Build.Framework;
using Microsoft.Build.Shared;
using Microsoft.Build.Utilities;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public sealed class CommandLineBuilderTest
{
/*
* Method: AppendSwitchSimple
*
* Just append a simple switch.
*/
[Fact]
public void AppendSwitchSimple()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/a");
c.AppendSwitch("-b");
c.ShouldBe("/a -b");
}
/*
* Method: AppendSwitchWithStringParameter
*
* Append a switch that has a string parameter.
*/
[Fact]
public void AppendSwitchWithStringParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/animal:", "dog");
c.ShouldBe("/animal:dog");
}
/*
* Method: AppendSwitchWithSpacesInParameter
*
* This should trigger implicit quoting.
*/
[Fact]
public void AppendSwitchWithSpacesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/animal:", "dog and pony");
c.ShouldBe("/animal:\"dog and pony\"");
}
/// <summary>
/// Test for AppendSwitchIfNotNull for the ITaskItem version
/// </summary>
[Fact]
public void AppendSwitchWithSpacesInParameterTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/animal:", new TaskItem("dog and pony"));
c.ShouldBe("/animal:\"dog and pony\"");
}
/*
* Method: AppendLiteralSwitchWithSpacesInParameter
*
* Implicit quoting should not happen.
*/
[Fact]
public void AppendLiteralSwitchWithSpacesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchUnquotedIfNotNull("/animal:", "dog and pony");
c.ShouldBe("/animal:dog and pony");
}
/*
* Method: AppendTwoStringsEnsureNoSpace
*
* When appending two comma-delimited strings, there should be no space before the comma.
*/
[Fact]
public void AppendTwoStringsEnsureNoSpace()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "Form1.resx", FileUtilities.FixFilePath("built\\Form1.resources") }, ",");
// There shouldn't be a space before or after the comma
// Tools like resgen require comma-delimited lists to be bumped up next to each other.
c.ShouldBe(FileUtilities.FixFilePath(@"Form1.resx,built\Form1.resources"));
}
/*
* Method: AppendSourcesArray
*
* Append several sources files using JoinAppend
*/
[Fact]
public void AppendSourcesArray()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "Mercury.cs", "Venus.cs", "Earth.cs" }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe(@"Mercury.cs Venus.cs Earth.cs");
}
/*
* Method: AppendSourcesArrayWithDashes
*
* Append several sources files starting with dashes using JoinAppend
*/
[Fact]
public void AppendSourcesArrayWithDashes()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "-Mercury.cs", "-Venus.cs", "-Earth.cs" }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe($".{Path.DirectorySeparatorChar}-Mercury.cs .{Path.DirectorySeparatorChar}-Venus.cs .{Path.DirectorySeparatorChar}-Earth.cs");
}
/// <summary>
/// Test AppendFileNamesIfNotNull, the ITaskItem version
/// </summary>
[Fact]
public void AppendSourcesArrayWithDashesTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { new TaskItem("-Mercury.cs"), null, new TaskItem("Venus.cs"), new TaskItem("-Earth.cs") }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe($".{Path.DirectorySeparatorChar}-Mercury.cs Venus.cs .{Path.DirectorySeparatorChar}-Earth.cs");
}
/*
* Method: JoinAppendEmpty
*
* Append an empty array. Result should be NOP.
*/
[Fact]
public void JoinAppendEmpty()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull(new[] { "" }, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe("");
}
/*
* Method: JoinAppendNull
*
* Append an empty array. Result should be NOP.
*/
[Fact]
public void JoinAppendNull()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNamesIfNotNull((string[])null, " ");
// Managed compilers use this function to append sources files.
c.ShouldBe("");
}
/// <summary>
/// Append a switch with parameter array, quoting
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayQuoting()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchIfNotNull("/switch:", new[] { "Mer cury.cs", "Ve nus.cs", "Ear th.cs" }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:\"Mer cury.cs\",\"Ve nus.cs\",\"Ear th.cs\"");
}
/// <summary>
/// Append a switch with parameter array, quoting, ITaskItem version
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayQuotingTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchIfNotNull("/switch:", new[] { new TaskItem("Mer cury.cs"), null, new TaskItem("Ve nus.cs"), new TaskItem("Ear th.cs") }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:\"Mer cury.cs\",,\"Ve nus.cs\",\"Ear th.cs\"");
}
/// <summary>
/// Append a switch with parameter array, no quoting
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayNoQuoting()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchUnquotedIfNotNull("/switch:", new[] { "Mer cury.cs", "Ve nus.cs", "Ear th.cs" }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:Mer cury.cs,Ve nus.cs,Ear th.cs");
}
/// <summary>
/// Append a switch with parameter array, no quoting, ITaskItem version
/// </summary>
[Fact]
public void AppendSwitchWithParameterArrayNoQuotingTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendSwitchUnquotedIfNotNull("/switch:", new[] { new TaskItem("Mer cury.cs"), null, new TaskItem("Ve nus.cs"), new TaskItem("Ear th.cs") }, ",");
// Managed compilers use this function to append sources files.
c.ShouldBe("/something /switch:Mer cury.cs,,Ve nus.cs,Ear th.cs");
}
/// <summary>
/// Appends a single file name
/// </summary>
[Fact]
public void AppendSingleFileName()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendFileNameIfNotNull("-Mercury.cs");
c.AppendFileNameIfNotNull("Mercury.cs");
c.AppendFileNameIfNotNull("Mer cury.cs");
// Managed compilers use this function to append sources files.
c.ShouldBe($"/something .{Path.DirectorySeparatorChar}-Mercury.cs Mercury.cs \"Mer cury.cs\"");
}
/// <summary>
/// Appends a single file name, ITaskItem version
/// </summary>
[Fact]
public void AppendSingleFileNameTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitch("/something");
c.AppendFileNameIfNotNull(new TaskItem("-Mercury.cs"));
c.AppendFileNameIfNotNull(new TaskItem("Mercury.cs"));
c.AppendFileNameIfNotNull(new TaskItem("Mer cury.cs"));
// Managed compilers use this function to append sources files.
c.ShouldBe($"/something .{Path.DirectorySeparatorChar}-Mercury.cs Mercury.cs \"Mer cury.cs\"");
}
/// <summary>
/// Verify that we throw an exception correctly for the case where we don't have a switch name
/// </summary>
[Fact]
public void AppendSingleFileNameWithQuotes()
{
Should.Throw<ArgumentException>(() =>
{
// Cannot have escaped quotes in a file name
CommandLineBuilder c = new CommandLineBuilder();
c.AppendFileNameIfNotNull("string with \"quotes\"");
c.ShouldBe("\"string with \\\"quotes\\\"\"");
}
);
}
/// <summary>
/// Trigger escaping of literal quotes.
/// </summary>
[Fact]
public void AppendSwitchWithLiteralQuotesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", "LSYSTEM_COMPATIBLE_ASSEMBLY_NAME=L\"Microsoft.Windows.SystemCompatible\"");
c.ShouldBe("/D\"LSYSTEM_COMPATIBLE_ASSEMBLY_NAME=L\\\"Microsoft.Windows.SystemCompatible\\\"\"");
}
/// <summary>
/// Trigger escaping of literal quotes.
/// </summary>
[Fact]
public void AppendSwitchWithLiteralQuotesInParameter2()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"ASSEMBLY_KEY_FILE=""c:\\foo\\FinalKeyFile.snk""");
c.ShouldBe(@"/D""ASSEMBLY_KEY_FILE=\""c:\\foo\\FinalKeyFile.snk\""""");
}
/// <summary>
/// Trigger escaping of literal quotes. This time, a double set of literal quotes.
/// </summary>
[Fact]
public void AppendSwitchWithLiteralQuotesInParameter3()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"""A B"" and ""C""");
c.ShouldBe(@"/D""\""A B\"" and \""C\""""");
}
/// <summary>
/// When a value contains a backslash, it doesn't normally need escaping.
/// </summary>
[Fact]
public void AppendQuotableSwitchContainingBackslash()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A \B");
c.ShouldBe(@"/D""A \B""");
}
/// <summary>
/// Backslashes before quotes need escaping themselves.
/// </summary>
[Fact]
public void AppendQuotableSwitchContainingBackslashBeforeLiteralQuote()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A"" \""B");
c.ShouldBe(@"/D""A\"" \\\""B""");
}
/// <summary>
/// Don't quote if not asked to
/// </summary>
[Fact]
public void AppendSwitchUnquotedIfNotNull()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchUnquotedIfNotNull("/D", @"A"" \""B");
c.ShouldBe(@"/DA"" \""B");
}
/// <summary>
/// When a value ends with a backslash, that certainly should be escaped if it's
/// going to be quoted.
/// </summary>
[Fact]
public void AppendQuotableSwitchEndingInBackslash()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A B\");
c.ShouldBe(@"/D""A B\\""");
}
/// <summary>
/// Backslashes don't need to be escaped if the string isn't going to get quoted.
/// </summary>
[Fact]
public void AppendNonQuotableSwitchEndingInBackslash()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"AB\");
c.ShouldBe(@"/DAB\");
}
/// <summary>
/// Quoting of hyphens
/// </summary>
[Fact]
public void AppendQuotableSwitchWithHyphen()
{
CommandLineBuilder c = new CommandLineBuilder(/* do not quote hyphens*/);
c.AppendSwitchIfNotNull("/D", @"foo-bar");
c.ShouldBe(@"/Dfoo-bar");
}
/// <summary>
/// Quoting of hyphens 2
/// </summary>
[Fact]
public void AppendQuotableSwitchWithHyphenQuoting()
{
CommandLineBuilder c = new CommandLineBuilder(true /* quote hyphens*/);
c.AppendSwitchIfNotNull("/D", @"foo-bar");
c.ShouldBe(@"/D""foo-bar""");
}
/// <summary>
/// Appends an ITaskItem item spec as a parameter
/// </summary>
[Fact]
public void AppendSwitchTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder(true);
c.AppendSwitchIfNotNull("/D", new TaskItem(@"foo-bar"));
c.ShouldBe(@"/D""foo-bar""");
}
/// <summary>
/// Appends an ITaskItem item spec as a parameter
/// </summary>
[Fact]
public void AppendSwitchUnQuotedTaskItem()
{
CommandLineBuilder c = new CommandLineBuilder(true);
c.AppendSwitchUnquotedIfNotNull("/D", new TaskItem(@"foo-bar"));
c.ShouldBe(@"/Dfoo-bar");
}
/// <summary>
/// Ensure it's not an error to have an odd number of literal quotes. Sometimes
/// it's a mistake on the programmer's side, but we cannot reject odd numbers of
/// quotes in the general case because sometimes that's exactly what's needed (e.g.
/// passing a string with a single embedded double-quote to a compiler).
/// </summary>
[Fact]
public void AppendSwitchWithOddNumberOfLiteralQuotesInParameter()
{
CommandLineBuilder c = new CommandLineBuilder();
c.AppendSwitchIfNotNull("/D", @"A='""'"); // /DA='"'
c.ShouldBe(@"/D""A='\""'"""); // /D"A='\"'"
}
[Fact]
public void UseNewLineSeparators()
{
CommandLineBuilder c = new CommandLineBuilder(quoteHyphensOnCommandLine: false, useNewLineSeparator: true);
c.AppendSwitchIfNotNull("/foo:", "bar");
c.AppendFileNameIfNotNull("18056896847C4FFC9706F1D585C077B4");
c.AppendSwitch("/D:");
c.AppendTextUnquoted("C7E1720B16E5477D8D15733006E68278");
string[] actual = c.ToString().Split(MSBuildConstants.EnvironmentNewLine, StringSplitOptions.None);
string[] expected =
{
"/foo:bar",
"18056896847C4FFC9706F1D585C077B4",
"/D:C7E1720B16E5477D8D15733006E68278"
};
actual.ShouldBe(expected);
}
internal class TestCommandLineBuilder : CommandLineBuilder
{
internal void TestVerifyThrow(string switchName, string parameter)
{
VerifyThrowNoEmbeddedDoubleQuotes(switchName, parameter);
}
protected override void VerifyThrowNoEmbeddedDoubleQuotes(string switchName, string parameter)
{
base.VerifyThrowNoEmbeddedDoubleQuotes(switchName, parameter);
}
}
/// <summary>
/// Test the else of VerifyThrowNOEmbeddedDouble quotes where the switch name is not empty or null
/// </summary>
[Fact]
public void TestVerifyThrowElse()
{
Should.Throw<ArgumentException>(() =>
{
TestCommandLineBuilder c = new TestCommandLineBuilder();
c.TestVerifyThrow("SuperSwitch", @"Parameter");
c.TestVerifyThrow("SuperSwitch", @"Para""meter");
}
);
}
}
internal static class CommandLineBuilderExtensionMethods
{
public static void ShouldBe(this CommandLineBuilder commandLineBuilder, string expected)
{
commandLineBuilder.ToString().ShouldBe(expected);
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, 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.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
using System.Text;
using Encog.MathUtil.Matrices;
using Encog.ML;
using Encog.ML.Data;
using Encog.ML.Data.Basic;
using Encog.ML.Train;
using Encog.Neural.Networks.Training;
using Encog.Neural.Networks.Training.Propagation;
using Encog.Util;
using Encog.Util.Logging;
namespace Encog.Neural.SOM.Training.Neighborhood
{
/// <summary>
/// This class implements competitive training, which would be used in a
/// winner-take-all neural network, such as the self organizing map (SOM). This
/// is an unsupervised training method, no ideal data is needed on the training
/// set. If ideal data is provided, it will be ignored.
/// Training is done by looping over all of the training elements and calculating
/// a "best matching unit" (BMU). This BMU output neuron is then adjusted to
/// better "learn" this pattern. Additionally, this training may be applied to
/// other "nearby" output neurons. The degree to which nearby neurons are update
/// is defined by the neighborhood function.
/// A neighborhood function is required to determine the degree to which
/// neighboring neurons (to the winning neuron) are updated by each training
/// iteration.
/// Because this is unsupervised training, calculating an error to measure
/// progress by is difficult. The error is defined to be the "worst", or longest,
/// Euclidean distance of any of the BMU's. This value should be minimized, as
/// learning progresses.
/// Because only the BMU neuron and its close neighbors are updated, you can end
/// up with some output neurons that learn nothing. By default these neurons are
/// not forced to win patterns that are not represented well. This spreads out
/// the workload among all output neurons. This feature is not used by default,
/// but can be enabled by setting the "forceWinner" property.
/// </summary>
///
public class BasicTrainSOM : BasicTraining, ILearningRate
{
/// <summary>
/// Utility class used to determine the BMU.
/// </summary>
private readonly BestMatchingUnit _bmuUtil;
/// <summary>
/// Holds the corrections for any matrix being trained.
/// </summary>
private readonly Matrix _correctionMatrix;
/// <summary>
/// How many neurons in the input layer.
/// </summary>
private readonly int _inputNeuronCount;
/// <summary>
/// The neighborhood function to use to determine to what degree a neuron
/// should be "trained".
/// </summary>
private readonly INeighborhoodFunction _neighborhood;
/// <summary>
/// The network being trained.
/// </summary>
private readonly SOMNetwork _network;
/// <summary>
/// How many neurons in the output layer.
/// </summary>
private readonly int _outputNeuronCount;
/// <summary>
/// This is the current autodecay radius.
/// </summary>
private double _autoDecayRadius;
/// <summary>
/// This is the current autodecay learning rate.
/// </summary>
private double _autoDecayRate;
/// <summary>
/// When used with autodecay, this is the ending radius.
/// </summary>
private double _endRadius;
/// <summary>
/// When used with autodecay, this is the ending learning rate.
/// </summary>
private double _endRate;
/// <summary>
/// The current radius.
/// </summary>
private double _radius;
/// <summary>
/// When used with autodecay, this is the starting radius.
/// </summary>
private double _startRadius;
/// <summary>
/// When used with autodecay, this is the starting learning rate.
/// </summary>
private double _startRate;
/// <summary>
/// Create an instance of competitive training.
/// </summary>
/// <param name="network">The network to train.</param>
/// <param name="learningRate">The learning rate, how much to apply per iteration.</param>
/// <param name="training">The training set (unsupervised).</param>
/// <param name="neighborhood">The neighborhood function to use.</param>
public BasicTrainSOM(SOMNetwork network, double learningRate,
IMLDataSet training, INeighborhoodFunction neighborhood)
: base(TrainingImplementationType.Iterative)
{
_neighborhood = neighborhood;
Training = training;
LearningRate = learningRate;
_network = network;
_inputNeuronCount = network.InputCount;
_outputNeuronCount = network.OutputCount;
ForceWinner = false;
// setup the correction matrix
_correctionMatrix = new Matrix(_outputNeuronCount, _inputNeuronCount);
// create the BMU class
_bmuUtil = new BestMatchingUnit(network);
}
/// <summary>
/// True is a winner is to be forced, see class description, or forceWinners
/// method. By default, this is true.
/// </summary>
public bool ForceWinner { get; set; }
/// <inheritdoc/>
public override bool CanContinue
{
get { return false; }
}
/// <summary>
/// The input neuron count.
/// </summary>
public int InputNeuronCount
{
get { return _inputNeuronCount; }
}
/// <inheritdoc/>
public override IMLMethod Method
{
get { return _network; }
}
/// <summary>
/// The network neighborhood function.
/// </summary>
public INeighborhoodFunction Neighborhood
{
get { return _neighborhood; }
}
/// <summary>
/// The output neuron count.
/// </summary>
public int OutputNeuronCount
{
get { return _outputNeuronCount; }
}
#region ILearningRate Members
/// <summary>
/// The learning rate. To what degree should changes be applied.
/// </summary>
public double LearningRate { get; set; }
#endregion
/// <summary>
/// Loop over the synapses to be trained and apply any corrections that were
/// determined by this training iteration.
/// </summary>
private void ApplyCorrection()
{
_network.Weights.Set(_correctionMatrix);
}
/// <summary>
/// Should be called each iteration if autodecay is desired.
/// </summary>
public void AutoDecay()
{
if (_radius > _endRadius)
{
_radius += _autoDecayRadius;
}
if (LearningRate > _endRate)
{
LearningRate += _autoDecayRate;
}
_neighborhood.Radius = _radius;
}
/// <summary>
/// Copy the specified input pattern to the weight matrix. This causes an
/// output neuron to learn this pattern "exactly". This is useful when a
/// winner is to be forced.
/// </summary>
/// <param name="matrix">The matrix that is the target of the copy.</param>
/// <param name="outputNeuron">The output neuron to set.</param>
/// <param name="input">The input pattern to copy.</param>
private void CopyInputPattern(Matrix matrix, int outputNeuron,
IMLData input)
{
for (int inputNeuron = 0; inputNeuron < _inputNeuronCount; inputNeuron++)
{
matrix.Data[outputNeuron][inputNeuron] = input[inputNeuron];
}
}
/// <summary>
/// Called to decay the learning rate and radius by the specified amount.
/// </summary>
/// <param name="d">The percent to decay by.</param>
public void Decay(double d)
{
_radius *= (1.0 - d);
LearningRate *= (1.0 - d);
}
/// <summary>
/// Decay the learning rate and radius by the specified amount.
/// </summary>
/// <param name="decayRate">The percent to decay the learning rate by.</param>
/// <param name="decayRadius">The percent to decay the radius by.</param>
public void Decay(double decayRate, double decayRadius)
{
_radius *= (1.0 - decayRadius);
LearningRate *= (1.0 - decayRate);
_neighborhood.Radius = _radius;
}
/// <summary>
/// Determine the weight adjustment for a single neuron during a training
/// iteration.
/// </summary>
/// <param name="weight">The starting weight.</param>
/// <param name="input">The input to this neuron.</param>
/// <param name="currentNeuron">The neuron who's weight is being updated.</param>
/// <param name="bmu">The neuron that "won", the best matching unit.</param>
/// <returns>The new weight value.</returns>
private double DetermineNewWeight(double weight, double input,
int currentNeuron, int bmu)
{
double newWeight = weight
+ (_neighborhood.Function(currentNeuron, bmu)
*LearningRate*(input - weight));
return newWeight;
}
/// <summary>
/// Force any neurons that did not win to off-load patterns from overworked
/// neurons.
/// </summary>
/// <param name="matrix">The synapse to modify.</param>
/// <param name="won">An array that specifies how many times each output neuron has "won".</param>
/// <param name="leastRepresented">The training pattern that is the least represented by this neural network.</param>
/// <returns>True if a winner was forced.</returns>
private bool ForceWinners(Matrix matrix, int[] won,
IMLData leastRepresented)
{
double maxActivation = Double.NegativeInfinity;
int maxActivationNeuron = -1;
IMLData output = Compute(_network, leastRepresented);
// Loop over all of the output neurons. Consider any neurons that were
// not the BMU (winner) for any pattern. Track which of these
// non-winning neurons had the highest activation.
for (int outputNeuron = 0; outputNeuron < won.Length; outputNeuron++)
{
// Only consider neurons that did not "win".
if (won[outputNeuron] == 0)
{
if ((maxActivationNeuron == -1)
|| (output[outputNeuron] > maxActivation))
{
maxActivation = output[outputNeuron];
maxActivationNeuron = outputNeuron;
}
}
}
// If a neurons was found that did not activate for any patterns, then
// force it to "win" the least represented pattern.
if (maxActivationNeuron != -1)
{
CopyInputPattern(matrix, maxActivationNeuron, leastRepresented);
return true;
}
return false;
}
/// <summary>
/// Perform one training iteration.
/// </summary>
public override void Iteration()
{
EncogLogging.Log(EncogLogging.LevelInfo,
"Performing SOM Training iteration.");
PreIteration();
// Reset the BMU and begin this iteration.
_bmuUtil.Reset();
var won = new int[_outputNeuronCount];
double leastRepresentedActivation = Double.PositiveInfinity;
IMLData leastRepresented = null;
// Reset the correction matrix for this synapse and iteration.
_correctionMatrix.Clear();
// Determine the BMU for each training element.
foreach (IMLDataPair pair in Training)
{
IMLData input = pair.Input;
int bmu = _bmuUtil.CalculateBMU(input);
won[bmu]++;
// If we are to force a winner each time, then track how many
// times each output neuron becomes the BMU (winner).
if (ForceWinner)
{
// Get the "output" from the network for this pattern. This
// gets the activation level of the BMU.
IMLData output = Compute(_network, pair.Input);
// Track which training entry produces the least BMU. This
// pattern is the least represented by the network.
if (output[bmu] < leastRepresentedActivation)
{
leastRepresentedActivation = output[bmu];
leastRepresented = pair.Input;
}
}
Train(bmu, _network.Weights, input);
if (ForceWinner)
{
// force any non-winning neurons to share the burden somewhat\
if (!ForceWinners(_network.Weights, won,
leastRepresented))
{
ApplyCorrection();
}
}
else
{
ApplyCorrection();
}
}
// update the error
Error = _bmuUtil.WorstDistance/100.0;
PostIteration();
}
/// <inheritdoc/>
public override TrainingContinuation Pause()
{
return null;
}
/// <inheritdoc/>
public override void Resume(TrainingContinuation state)
{
}
/// <summary>
/// Setup autodecay. This will decrease the radius and learning rate from the
/// start values to the end values.
/// </summary>
/// <param name="plannedIterations">The number of iterations that are planned. This allows the
/// decay rate to be determined.</param>
/// <param name="startRate">The starting learning rate.</param>
/// <param name="endRate">The ending learning rate.</param>
/// <param name="startRadius">The starting radius.</param>
/// <param name="endRadius">The ending radius.</param>
public void SetAutoDecay(int plannedIterations,
double startRate, double endRate,
double startRadius, double endRadius)
{
_startRate = startRate;
_endRate = endRate;
_startRadius = startRadius;
_endRadius = endRadius;
_autoDecayRadius = (endRadius - startRadius)/plannedIterations;
_autoDecayRate = (endRate - startRate)/plannedIterations;
SetParams(_startRate, _startRadius);
}
/// <summary>
/// Set the learning rate and radius.
/// </summary>
/// <param name="rate">The new learning rate.</param>
/// <param name="radius">The new radius.</param>
public void SetParams(double rate, double radius)
{
_radius = radius;
LearningRate = rate;
_neighborhood.Radius = radius;
}
/// <inheritdoc/>
public override String ToString()
{
var result = new StringBuilder();
result.Append("Rate=");
result.Append(Format.FormatPercent(LearningRate));
result.Append(", Radius=");
result.Append(Format.FormatDouble(_radius, 2));
return result.ToString();
}
/// <summary>
/// Train for the specified synapse and BMU.
/// </summary>
/// <param name="bmu">The best matching unit for this input.</param>
/// <param name="matrix">The synapse to train.</param>
/// <param name="input">The input to train for.</param>
private void Train(int bmu, Matrix matrix, IMLData input)
{
// adjust the weight for the BMU and its neighborhood
for (int outputNeuron = 0; outputNeuron < _outputNeuronCount; outputNeuron++)
{
TrainPattern(matrix, input, outputNeuron, bmu);
}
}
/// <summary>
/// Train for the specified pattern.
/// </summary>
/// <param name="matrix">The synapse to train.</param>
/// <param name="input">The input pattern to train for.</param>
/// <param name="current">The current output neuron being trained.</param>
/// <param name="bmu">The best matching unit, or winning output neuron.</param>
private void TrainPattern(Matrix matrix, IMLData input,
int current, int bmu)
{
for (int inputNeuron = 0; inputNeuron < _inputNeuronCount; inputNeuron++)
{
double currentWeight = matrix.Data[current][inputNeuron];
double inputValue = input[inputNeuron];
double newWeight = DetermineNewWeight(currentWeight,
inputValue, current, bmu);
_correctionMatrix.Data[current][inputNeuron] = newWeight;
}
}
/// <summary>
/// Train the specified pattern. Find a winning neuron and adjust all neurons
/// according to the neighborhood function.
/// </summary>
/// <param name="pattern">The pattern to train.</param>
public void TrainPattern(IMLData pattern)
{
IMLData input = pattern;
int bmu = _bmuUtil.CalculateBMU(input);
Train(bmu, _network.Weights, input);
ApplyCorrection();
}
/// <summary>
/// Calculate the output of the SOM, for each output neuron. Typically,
/// you will use the classify method instead of calling this method.
/// </summary>
/// <param name="som">The SOM to use.</param>
/// <param name="input">The input.</param>
/// <returns>The output.</returns>
private static IMLData Compute(SOMNetwork som, IMLData input)
{
var result = new BasicMLData(som.OutputCount);
for (int i = 0; i < som.OutputCount; i++)
{
Matrix optr = som.Weights.GetRow(i);
Matrix inputMatrix = Matrix.CreateRowMatrix(input);
result[i] = MatrixMath.DotProduct(inputMatrix, optr);
}
return result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
namespace System.Linq.Expressions.Interpreter
{
internal sealed class LocalVariable
{
private const int IsBoxedFlag = 1;
private const int InClosureFlag = 2;
public readonly int Index;
private int _flags;
public bool IsBoxed
{
get { return (_flags & IsBoxedFlag) != 0; }
set
{
if (value)
{
_flags |= IsBoxedFlag;
}
else
{
_flags &= ~IsBoxedFlag;
}
}
}
public bool InClosure => (_flags & InClosureFlag) != 0;
internal LocalVariable(int index, bool closure)
{
Index = index;
_flags = (closure ? InClosureFlag : 0);
}
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}: {1} {2}", Index, IsBoxed ? "boxed" : null, InClosure ? "in closure" : null);
}
}
internal readonly struct LocalDefinition
{
internal LocalDefinition(int localIndex, ParameterExpression parameter)
{
Index = localIndex;
Parameter = parameter;
}
public int Index { get; }
public ParameterExpression Parameter { get; }
public override bool Equals(object obj)
{
if (obj is LocalDefinition)
{
LocalDefinition other = (LocalDefinition)obj;
return other.Index == Index && other.Parameter == Parameter;
}
return false;
}
public override int GetHashCode()
{
if (Parameter == null)
{
return 0;
}
return Parameter.GetHashCode() ^ Index.GetHashCode();
}
}
internal sealed class LocalVariables
{
private readonly HybridReferenceDictionary<ParameterExpression, VariableScope> _variables = new HybridReferenceDictionary<ParameterExpression, VariableScope>();
private Dictionary<ParameterExpression, LocalVariable> _closureVariables;
private int _localCount, _maxLocalCount;
public LocalDefinition DefineLocal(ParameterExpression variable, int start)
{
var result = new LocalVariable(_localCount++, closure: false);
_maxLocalCount = Math.Max(_localCount, _maxLocalCount);
VariableScope existing, newScope;
if (_variables.TryGetValue(variable, out existing))
{
newScope = new VariableScope(result, start, existing);
if (existing.ChildScopes == null)
{
existing.ChildScopes = new List<VariableScope>();
}
existing.ChildScopes.Add(newScope);
}
else
{
newScope = new VariableScope(result, start, parent: null);
}
_variables[variable] = newScope;
return new LocalDefinition(result.Index, variable);
}
public void UndefineLocal(LocalDefinition definition, int end)
{
VariableScope scope = _variables[definition.Parameter];
scope.Stop = end;
if (scope.Parent != null)
{
_variables[definition.Parameter] = scope.Parent;
}
else
{
_variables.Remove(definition.Parameter);
}
_localCount--;
}
internal void Box(ParameterExpression variable, InstructionList instructions)
{
VariableScope scope = _variables[variable];
LocalVariable local = scope.Variable;
Debug.Assert(!local.IsBoxed && !local.InClosure);
_variables[variable].Variable.IsBoxed = true;
int curChild = 0;
for (int i = scope.Start; i < scope.Stop && i < instructions.Count; i++)
{
if (scope.ChildScopes != null && scope.ChildScopes[curChild].Start == i)
{
// skip boxing in the child scope
VariableScope child = scope.ChildScopes[curChild];
i = child.Stop;
curChild++;
continue;
}
instructions.SwitchToBoxed(local.Index, i);
}
}
public int LocalCount => _maxLocalCount;
public bool TryGetLocalOrClosure(ParameterExpression var, out LocalVariable local)
{
VariableScope scope;
if (_variables.TryGetValue(var, out scope))
{
local = scope.Variable;
return true;
}
if (_closureVariables != null && _closureVariables.TryGetValue(var, out local))
{
return true;
}
local = null;
return false;
}
/// <summary>
/// Gets the variables which are defined in an outer scope and available within the current scope.
/// </summary>
internal Dictionary<ParameterExpression, LocalVariable> ClosureVariables => _closureVariables;
internal LocalVariable AddClosureVariable(ParameterExpression variable)
{
if (_closureVariables == null)
{
_closureVariables = new Dictionary<ParameterExpression, LocalVariable>();
}
LocalVariable result = new LocalVariable(_closureVariables.Count, true);
_closureVariables.Add(variable, result);
return result;
}
/// <summary>
/// Tracks where a variable is defined and what range of instructions it's used in.
/// </summary>
private sealed class VariableScope
{
public readonly int Start;
public int Stop = int.MaxValue;
public readonly LocalVariable Variable;
public readonly VariableScope Parent;
public List<VariableScope> ChildScopes;
public VariableScope(LocalVariable variable, int start, VariableScope parent)
{
Variable = variable;
Start = start;
Parent = parent;
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace JovianTools.Support
{
public class rtfDocument
{
private rtfLine [] _Document;
private rtfLine [] _DocumentCache;
private int _Size;
private int _Cursor;
private rtfFontLibrary _Library;
private JovianEdit _Owner;
private int _ScrollTop;
private int _RenderedLines = 0;
private int _SizeCache;
//private rtfC
private Stack _Undo;
private Stack _Redo;
public void SetTop(int t) { _ScrollTop = Math.Min(_Size - 1,Math.Max(0,t)); }
public rtfFontLibrary Library { get { return _Library; } }
public void ChangeFontSize(int s)
{
_Library.Build(s);
_Owner.Invalidate();
}
public void ResetDoc(string x)
{
PrepareUndoBuffer();
_Size = 1;
_Document = new rtfLine[1024];
_Document[0] = new rtfLine();
_Cursor = 0;
InsertReal(x,false);
TrimEnd();
SaveUndoBuffer();
_Owner.Invalidate();
}
public bool MinusAllowedInGroup = false;
public string GetHint(int line, int cur)
{
return lineAt(line).GetHint(cur,MinusAllowedInGroup);
}
public void AutoInsert(string wrd, string total)
{
rtfLine L = GetCurrentLine();
for(int k = 0; k < wrd.Length; k++)
{
L.Backspace();
}
Insert(total);
}
/*s
public string GetNextHint(int line, int cur, string h)
{
return lineAt(line).GetHint2(cur - h.Length);
}
*/
public rtfDocument(JovianEdit owner)
{
_ScrollTop = 0;
_Owner = owner;
_Document = new rtfLine[128];
_Cursor = 0;
for(int k = 0; k < _Document.Length; k++) _Document[k] = null;
_Document[0] = new rtfLine();
_Size = 1;
_Library = new rtfFontLibrary();
_Library.Build(2);
_Undo = new Stack();
_Redo = new Stack();
_Key = new rtfSearchKey();
_Key.MatchCase = false;
_Key.KeyWord = "";
}
public rtfLine lineAt(int ln)
{
this.BufferChk(ln);
if(_Document[ln] == null) _Document[ln] = new rtfLine();
return _Document[ln];
}
rtfSearchKey _Key;
public rtfSearchKey GetKey()
{
return _Key;
}
public ArrayList SearchResults = new ArrayList();
public int SearchCursor = 0;
public void SelectSearchRange(rtfSearchRange sR)
{
_Cursor = sR.Line;
GetCurrentLine().SetCursor(sR.Start);
SelectStart = new rtfSelectionObject();
SelectStart.Line = sR.Line;
SelectEnd = SelectStart.copy();
SelectStart.Place = sR.Start;
SelectEnd.Place = sR.End;
MakeCursorFit();
UpdateSelection();
}
public void InsertTimeStamp()
{
string x = DateTime.Now.ToLongDateString();
Insert(x);
}
public void ExecuteReplace(string rep)
{
if(SearchResults.Count == 0) return;
PrepareUndoBuffer();
for(int k = SearchResults.Count - 1; k >= 0; k--)
{
rtfSearchRange Range = SearchResults[k] as rtfSearchRange;
if(Range != null)
{
SelectSearchRange(Range);
InsertReal(rep,false);
}
}
SaveUndoBuffer();
SearchResults = new ArrayList();
}
public void DeleteFromSearchResults(rtfSearchRange KKK)
{
SearchCursor = 0;
ArrayList L = new ArrayList();
for(int k = 0; k < _Size; k++)
{
if(_Document[k] != null)
{
_Document[k].ClearFind();
}
}
int Wr = 0;
foreach(rtfSearchRange K in SearchResults)
{
rtfSearchRange KK = null;
if(K.Idx != KKK.Idx)
{
KK = K;
}
if(KK != null)
{
KK.Idx = Wr;
Wr++;
_Document[KK.Line].HighLight(KK);
L.Add(KK);
}
}
SearchResults = L;
UpdateSearch();
_Owner.Invalidate();
}
public void AlterSearchResults(int Sty, bool F)
{
SearchCursor = 0;
ArrayList L = new ArrayList();
for(int k = 0; k < _Size; k++)
{
if(_Document[k] != null)
{
_Document[k].ClearFind();
}
}
int Wr = 0;
foreach(rtfSearchRange K in SearchResults)
{
rtfSearchRange KK = null;
if(F) // filtering
{
if(K.Sty != Sty) KK = K;
}
else
{
if(K.Sty == Sty) KK = K;
}
if(KK != null)
{
KK.Idx = Wr;
Wr++;
_Document[KK.Line].HighLight(KK);
L.Add(KK);
}
}
SearchResults = L;
UpdateSearch();
_Owner.Invalidate();
}
public void UpdateSearch()
{
if(SearchResults.Count > 0) SelectSearchRange( SearchResults[SearchCursor] as rtfSearchRange );
}
public void ChkSearch()
{
if(SearchResults.Count > 0)
{
bool inv = false;
for(int k = 0; k < _Size && !inv; k++)
{
if(lineAt(k).undo_Changed())
{
inv = true;
}
}
if(inv)
{
int old = SearchCursor;
ExecSearch(false);
SearchCursor = old;
}
}
}
public void SearchNext()
{
SearchCursor = Math.Min(SearchCursor + 1, SearchResults.Count - 1);
UpdateSearch();
}
public void SearchPrev()
{
SearchCursor = Math.Max(SearchCursor - 1, 0);
UpdateSearch();
}
public int ExecSearch(bool chgCursor)
{
SearchResults = new ArrayList();
for(int k = 0; k < _Size; k++)
{
if(_Document[k] != null)
{
_Document[k].ClearHighlight();
_Document[k].TestSearch(_Key,SearchResults,k);
}
}
if(chgCursor)
{
if(SearchResults.Count > 0)
{
SearchCursor = 0;
SelectSearchRange( SearchResults[0] as rtfSearchRange );
}
}
return SearchResults.Count;
}
int OldCursor;
int OldLineCursor;
bool StackOfOne = false;
public void PrepareUndoBuffer()
{
if (StackOfOne)
{
MessageBox.Show("Error, Stack of One Invariant Violated");
}
StackOfOne = true;
if(_DocumentCache == null)
_DocumentCache = new rtfLine[_Document.Length+5];
_SizeCache = _Size;
if(_DocumentCache.Length < _Document.Length)
_DocumentCache = new rtfLine[_Document.Length+5];
for(int k = 0; k < _Size; k++)
{
_DocumentCache[k] = _Document[k];
_Document[k].UndoStart(k);
}
OldCursor = _Cursor;
OldLineCursor = GetCurrentLine().Cursor;
}
public rtfMassExecute ACTION = null;
public void SaveUndoBuffer()
{
StackOfOne = false;
for(int k = 0; k < _Size; k++)
{
_Document[k].UndoUpdate(k);
}
rtfMassExecute rtfME = new rtfMassExecute();
rtfME.OriginalDocCursor = OldCursor;
rtfME.OriginalLineCursor = OldLineCursor;
ArrayList DeletedLines = new ArrayList();
ArrayList MovedLines = new ArrayList();
//string msgHelp = "";
for(int k = 0; k < _SizeCache; k++)
{
rtfLine OldL = _DocumentCache[k];
if(OldL != null)
{
if(OldL.undo_NewIndex() < 0)
{
// msgHelp += "[-" + (k+1) + "]";
DeletedLines.Add( new rtfUndo_DeleteLine(k, OldL.GetBuffer() ) );
}
else
{
// msgHelp += "[" + (k+1) + ":" + (OldL.undo_OldIndex()+1) + "=>"+ (OldL.undo_NewIndex()+1) + "]";
MovedLines.Add( new rtfUndo_Move(OldL.undo_OldIndex(), OldL.undo_NewIndex()));
}
}
}
ArrayList ChangedLines = new ArrayList();
for(int k = 0; k < _Size; k++)
{
rtfLine NewL = _Document[k];
if(NewL != null)
{
if(NewL.undo_Changed())
{
//msgHelp += "[#" + (k+1) + "]";
ChangedLines.Add(new rtfUndo_LineChange(k,NewL.GetBuffer(),NewL.ExtractAll()));
NewL.UpdateBuffer();
}
}
}
bool changed = false;
if(DeletedLines.Count > 0) changed = true;
if(ChangedLines.Count > 0) changed = true;
if(changed)
{
// MessageBox.Show(msgHelp);
rtfME.DeletedLines = DeletedLines;
rtfME.MovedLines = MovedLines;
rtfME.ChangedLines = ChangedLines;
rtfME.OriginalSize = _SizeCache;
rtfME.AfterSize = _Size;
rtfME.AfterDocCursor = _Cursor;
rtfME.AfterLineCursor = GetCurrentLine().Cursor;
_Undo.Push(rtfME);
_Redo = new Stack();
_Owner.Changed();
StylizeDiff();
execTxtChanged();
}
}
private void execTxtChanged()
{
_Owner.FireTxtChanged();
}
public void execUndo(rtfMassExecute me)
{
rtfLine [] doc = new rtfLine[me.OriginalSize + 5];
for(int k = 0; k < doc.Length; k++) doc[k] = null;
foreach(rtfUndo_LineChange lc in me.ChangedLines)
{
_Document[lc.line] = new rtfLine(lc.F);
}
foreach(rtfUndo_Move mv in me.MovedLines)
{
doc[mv.F] = _Document[mv.T];
}
foreach(rtfUndo_DeleteLine dl in me.DeletedLines)
{
// MessageBox.Show("Restoring Deleted Line:" + dl.line);
doc[dl.position] = new rtfLine(dl.line);
}
_Size = me.OriginalSize;
_Document = doc;
for(int k = 0; k < _Size; k++)
{
if(_Document[k]==null)
{
_Document[k] = new rtfLine("whoops");
}
}
_Cursor = me.OriginalDocCursor;
GetCurrentLine().SetCursor(me.OriginalLineCursor);
execTxtChanged();
}
public void execRedo(rtfMassExecute me)
{
rtfLine [] doc = new rtfLine[me.AfterSize + 5];
for(int k = 0; k < doc.Length; k++) doc[k] = null;
foreach(rtfUndo_Move mv in me.MovedLines)
{
// MessageBox.Show("Remapping: " + mv.F + "=" + mv.T);
doc[mv.T] = _Document[mv.F];
}
foreach(rtfUndo_LineChange lc in me.ChangedLines)
{
// MessageBox.Show("Line Change:" + lc.F + ":" + lc.T);
doc[lc.line] = new rtfLine(lc.T);
}
_Size = me.AfterSize;
_Document = doc;
_Cursor = me.AfterDocCursor;
GetCurrentLine().SetCursor(me.AfterLineCursor);
execTxtChanged();
/*
rtfLine [] doc = new rtfLine[me.OriginalSize + 5];
for(int k = 0; k < doc.Length; k++) doc[k] = null;
// restore the changed lines
foreach(rtfUndo_LineChange lc in me.ChangedLines)
{
// MessageBox.Show("Line Change:" + lc.F + ":" + lc.T);
_Document[lc.line] = new rtfLine(lc.F);
}
foreach(rtfUndo_Move mv in me.MovedLines)
{
// MessageBox.Show("Remapping: " + mv.F + "=" + mv.T);
doc[mv.F] = _Document[mv.T];
}
foreach(rtfUndo_DeleteLine dl in me.DeletedLines)
{
// MessageBox.Show("Restoring Deleted Line:" + dl.line);
doc[dl.position] = new rtfLine(dl.line);
}
_Size = me.OriginalSize;
_Document = doc;
for(int k = 0; k < _Size; k++)
{
if(_Document[k]==null)
{
_Document[k] = new rtfLine("whoops");
}
}
*/
}
public void Redo()
{
if(_Redo.Count > 0)
{
rtfMassExecute Act = _Redo.Pop() as rtfMassExecute;
if(Act != null)
{
execRedo(Act);
_Undo.Push(Act);
}
StylizeDiff();
}
}
public void Undo()
{
if(_Undo.Count > 0)
{
rtfMassExecute Act = _Undo.Pop() as rtfMassExecute;
if(Act != null)
{
execUndo(Act);
_Redo.Push(Act);
}
StylizeDiff();
}
}
StyleEng _StyleEngine = null;
public void SetStyle(StyleEng E)
{
_StyleEngine = E;
StylizeWhole();
}
public StyleEng GetStyle() { return _StyleEngine; }
public void StylizeDiff()
{
StyleEng E = _StyleEngine;
if(E == null) return;
StyleExp Ep = null;
bool Must = false;
for(int k = 0; k < _Size; k++)
{
_Document[k].LastSty = false;
if(_Document[k] != null)
{
if(_Document[k].HasChanged())
{
Must = true;
}
if(!Must)
{
if(k + 1 < _Size)
{
if(_Document[k+1].HasChanged())
{
Must = true;
}
}
}
if(Must)
{
if(_Document[k].HasChanged())
{
Ep = _Document[k].Stylize(E,Ep);
}
else
{
if(_Document[k].CanStopStylize(E,Ep))
{
Must = false;
}
}
}
Ep = _Document[k].GetLastStyleExport();
}
}
}
public void TrimEnd()
{
/*
while(_Size > 1)
{
if(lineAt(_Size - 1).Length() > 0) return;
_Size--;
}
*/
}
public void StylizeWhole()
{
StyleEng E = _StyleEngine;
if(E == null)
{
for(int k = 0; k < _Size; k++)
{
if(_Document[k] != null)
{
_Document[k].Stylize(null,null);
}
}
return;
}
StyleExp Ep = null;
for(int k = 0; k < _Size; k++)
{
if(_Document[k] != null)
{
Ep = _Document[k].Stylize(E,Ep);
}
}
}
public void OnKey(char x,bool shift)
{
InvCur = true;
PrepareUndoBuffer();
bool deletedSelection = DeleteCurrentSelection();
if(deletedSelection && x == (char)8)
{
}
else
{
if(GetCurrentLine().OnKey(x))
{
if(_Cursor > 0)
{
string curR = GetCurrentLine().ExtractAll();
_Cursor--;
string curL = GetCurrentLine().ExtractAll();
_Document[_Cursor] = new rtfLine(curL + curR);
_Document[_Cursor].SetCursor(curL.Length);
DeleteLine(_Cursor + 1,false);
}
}
}
SaveUndoBuffer();
_Owner.Invalidate();
}
public rtfLine GetCurrentLine()
{
if(_Document[_Cursor]==null) _Document[_Cursor] = new rtfLine();
return _Document[_Cursor];
}
public int GetLineIndexFromPoint(int x, int y)
{
int b = Math.Max(0,Math.Min(_Size, _ScrollTop + _RenderedLines));
BufferChk(b+1);
for(int ln = _ScrollTop; ln < b; ln++)
{
if(ln < 0 || ln >= _Document.Length)
{
MessageBox.Show("?!?");
}
if(_Document[ln] != null)
{
Rectangle R = _Document[ln].Bounds;
if(R.Y >= 0)
{
if(R.Y <= y && y <= (R.Y + R.Height))
{
return ln;
}
}
}
}
if(y < 0) return _ScrollTop;
return _Size - 1;
}
public string ExtractSelection()
{
if(SelectStart == null) return null;
if(SelectEnd == null) return null;
System.IO.StringWriter SW = new System.IO.StringWriter();
for(int ln = 0; ln < _Size; ln++)
{
rtfLine L =_Document[ln];
if(L!=null)
{
if(SelectStart.Line <= ln && ln <= SelectEnd.Line)
{
if(SelectStart.Line < ln && ln < SelectEnd.Line)
{
SW.WriteLine(L.ExtractAll());
}
else
{
if(SelectStart.Line == SelectEnd.Line)
{
SW.Write(L.ExtractInner(SelectStart.Place,SelectEnd.Place));
//L.HighlightInner(SelectStart.Place,SelectEnd.Place);
}
else if(SelectStart.Line == ln)
{
SW.WriteLine(L.ExtractRight(SelectStart.Place));
//L.HighlightRight(SelectStart.Place);
}
else
{
SW.Write(L.ExtractLeft(SelectEnd.Place));
//L.HighlightLeft(SelectEnd.Place);
}
}
}
}
}
string xyz = SW.ToString();
if(xyz==null) return "";
return xyz;
}
public void DeleteLine(int k,bool MoveCursorBack)
{
if(_Size > 0)
{
_Document[k] = null;
for(int j = k; j < _Size - 1; j++)
{
_Document[j] = _Document[j+1];
}
_Document[_Size-1] = null;
if(MoveCursorBack)
{
_Cursor = Math.Max(_Cursor - 1, 0);
GetCurrentLine().SetCursor(GetCurrentLine().Length());
}
_Size--;
}
if(_Size==0)
{
_Document[0] = new rtfLine("");
_Cursor = 0;
_Size = 1;
}
}
public rtfSelectionObject GetCurrentCursor()
{
rtfSelectionObject S = new rtfSelectionObject();
S.Line = _Cursor;
S.Place = GetCurrentLine().Cursor;
return S;
}
public void Wheel(int dC)
{
if(InvCur) OldCurX = GetCurrentLine().CursorX2();
_ScrollTop += dC;
_ScrollTop = Math.Min(_Size - 1, Math.Max(0, _ScrollTop));
InvCur = false;
_Owner.Invalidate();
}
private bool InvCur = true;
int OldCurX = -1;
public void Up(int k)
{
if(InvCur) OldCurX = GetCurrentLine().CursorX2();
_Cursor = Math.Max(0,_Cursor - k );
GetCurrentLine().SetCursor( GetCurrentLine().Position2Cursor(OldCurX) );
InvCur = false;
MakeCursorFit();
}
public void Down(int k)
{
if(InvCur) OldCurX = GetCurrentLine().CursorX2();
_Cursor = Math.Min(_Size-1,_Cursor + k );
GetCurrentLine().SetCursor( GetCurrentLine().Position2Cursor(OldCurX) );
InvCur = false;
MakeCursorFit();
}
public bool IsSelectionEmpty()
{
if(SelectStart == null) return true;
if(SelectEnd == null) return true;
SelectStart.Line = Math.Max(0,Math.Min(_Size - 1, SelectStart.Line));
SelectEnd.Line = Math.Max(0,Math.Min(_Size - 1, SelectEnd.Line));
if(Math.Max(SelectStart.Line,SelectEnd.Line) >= _Size) return true;
if(_Document[SelectStart.Line]==null) return true;
if(_Document[SelectEnd.Line]==null) return true;
if(SelectStart.Line == SelectEnd.Line)
{
return SelectStart.Place == SelectEnd.Place;
}
else
{
return false;
}
}
public void DelCurSelUndo()
{
PrepareUndoBuffer();
DeleteCurrentSelection();
SaveUndoBuffer();
}
public bool DeleteCurrentSelection()
{
return DeleteCurrentSelectionReal(null);
}
public bool DeleteCurrentSelectionReal(rtfSelectionObject translate)
{
if(IsSelectionEmpty()) return false;
/*
_Cursor = SelectStart.Line;
_Cursor = SelectEnd.Line;
lineAt(_Cursor).SetCursor(SelectEnd.Place);
lineAt(_Cursor). Backspace();
return true;
*/
_Cursor = SelectStart.Line;
string LT = _Document[SelectStart.Line].ExtractLeft(SelectStart.Place);
int nC = LT.Length;
string NewLine = LT + _Document[SelectEnd.Line].ExtractRight(SelectEnd.Place);
if(translate != null)
{
if(translate.Line == SelectEnd.Line)
{
int dt = SelectEnd.Place;
if(SelectEnd.Line == SelectStart.Line) dt -= SelectStart.Place;
translate.Place -= dt;
}
}
if(translate != null)
{
translate.Line = 0;
}
int Num2Del = SelectEnd.Line - SelectStart.Line;
if(translate != null) translate.Line -= Num2Del;
_Document[SelectStart.Line] = new rtfLine(NewLine);
lineAt(_Cursor).SetCursor(nC);
/*
rtfLine old = _Document[SelectStart.Line];
_Document[SelectStart.Line].InvPostDel(old.undo_OldIndex());
_Document[SelectStart.Line].SetCursor(LT.Length);
*/
for(int k = SelectStart.Line + 1; k < _Size - Num2Del; k++)
{
_Document[k] =_Document[k+Num2Del];
}
_Size-= Num2Del;
for(int k = _Size; k < _Document.Length; k++)
{
_Document[k] = null;
}
SelectStart = null;
SelectEnd = null;
return true;
}
private rtfSelectionObject ShiftSelect = null;
public bool OnSpecial(Keys K, bool shift)
{
if(K == (Keys.ShiftKey | Keys.Shift))
{
if(shift)
{
if(ShiftSelect == null)
{
ShiftSelect = GetCurrentCursor();
}
}
else
{
ShiftSelect = null;
SelectOriginal = null;
}
return false;
}
PrepareUndoBuffer();
if(shift)
{
rtfSelectionObject Now = null;
if(SelectOriginal == null)
{
Now = GetCurrentCursor();
}
bool good = false;
if(K == (Keys.Left | Keys.Shift)) { good = true; InvCur = true; if(GetCurrentLine().Left()) { Up(1); GetCurrentLine().Cursor = GetCurrentLine().Length(); } MakeCursorFit(); }
if(K == (Keys.Right | Keys.Shift)) { good = true; InvCur = true; if(GetCurrentLine().Right()) { Down(1); GetCurrentLine().Cursor = 0; } MakeCursorFit();}
if(K == (Keys.Up | Keys.Shift)) { good = true; Up(1); }
if(K == (Keys.Down | Keys.Shift)) { good = true; Down(1); }
if(K == (Keys.PageUp | Keys.Shift)) { good = true; Up(_RenderedLines - 1); }
if(K == (Keys.PageDown | Keys.Shift)) { good = true; Down(_RenderedLines - 1); }
if(K == (Keys.Home | Keys.Shift)) { good = true; InvCur = true;GetCurrentLine().Cursor = 0; MakeCursorFit(); }
if(K == (Keys.End | Keys.Shift)) { good = true; InvCur = true;GetCurrentLine().Cursor = GetCurrentLine().Length(); MakeCursorFit();}
if(K == (Keys.Left | Keys.Control | Keys.Shift)) { good = true;InvCur = true; GetCurrentLine().PrevWord(); MakeCursorFit(); };
if(K == (Keys.Right | Keys.Control | Keys.Shift)) { good = true;InvCur = true; GetCurrentLine().NextWord(); MakeCursorFit(); };
if(good)
{
if(SelectOriginal == null)
{
SelectOriginal = Now;
SelectStart = SelectOriginal.copy();
SelectEnd = SelectOriginal.copy();
}
RunSelectLogic2(GetCurrentCursor());
}
}
else
{
ShiftSelect = null;
//if(ShiftSelect != null) MessageBox.Show("Falling Edge");
//ShiftSelect = null;
if(K == Keys.Left || K == Keys.Right || K == Keys.Up || K == Keys.Down || K == Keys.End || K == Keys.Home)
{
SelectOriginal = null;
SelectStart = null;
SelectEnd = null;
ClearSelection();
}
if(K == Keys.Left) { InvCur = true; if(GetCurrentLine().Left()) { Up(1); GetCurrentLine().Cursor = GetCurrentLine().Length(); }MakeCursorFit();}
if(K == Keys.Right) { InvCur = true; if(GetCurrentLine().Right()) { Down(1); GetCurrentLine().Cursor = 0; }MakeCursorFit(); }
if(K == Keys.Up) { Up(1); }
if(K == Keys.Down) { Down(1); }
if(K == Keys.Home) { InvCur = true;GetCurrentLine().Cursor = 0; MakeCursorFit();}
if(K == Keys.End) { InvCur = true;GetCurrentLine().Cursor = GetCurrentLine().Length(); MakeCursorFit();}
if(K == Keys.PageUp) { Up(_RenderedLines - 1); MakeCursorFit();}
if(K == Keys.PageDown) { Down(_RenderedLines - 1 );MakeCursorFit(); }
if(K == (Keys.Up | Keys.Control)) { _ScrollTop --; if(_ScrollTop < 0) _ScrollTop = 0; };
if(K == (Keys.Down | Keys.Control)) { _ScrollTop ++; if(_ScrollTop >= _Size - 1) _ScrollTop = _Size - 1; };
if(K == (Keys.Left | Keys.Control)) { InvCur = true; GetCurrentLine().PrevWord(); MakeCursorFit(); };
if(K == (Keys.Right | Keys.Control)) { InvCur = true; GetCurrentLine().NextWord(); MakeCursorFit(); };
}
if(K == Keys.Delete)
{
InvCur = true;
if(!DeleteCurrentSelection())
{
int DelVal = GetCurrentLine().Delete();
if(DelVal==1)
{
DeleteLine(_Cursor,false);
_Cursor = Math.Min(_Size - 1,_Cursor);
GetCurrentLine().Cursor = 0;
}
else if (DelVal==2)
{
if(_Cursor < _Size - 1)
{
int c = -1;
string append = "";
int c2 = 0;
if( _Document[_Cursor] != null)
{
append = _Document[_Cursor].ExtractAll();
c = _Document[_Cursor].Cursor;
}
c2 = append.Length;
if( _Document[_Cursor + 1] != null)
append += _Document[_Cursor + 1].ExtractAll();
_Document[_Cursor] = new rtfLine(append);
if(c < 0) c = _Document[_Cursor].Length();
_Document[_Cursor].SetCursor(c);
DeleteLine(_Cursor + 1,false);
_Cursor = Math.Min(_Size - 1,_Cursor);
GetCurrentLine().Cursor = c2;
}
}
}
}
if(K == Keys.Return)
{
InvCur = true;
DeleteCurrentSelection();
BufferChk(_Size + 1);
rtfLine next = GetCurrentLine().Enter();
for(int k = _Size - 1; k > _Cursor; k--)
{
_Document[k+1] = _Document[k];
}
_Size++;
_Cursor++;
_Document[_Cursor] = next;
}
SaveUndoBuffer();
if(K == Keys.Tab) {InvCur = true;OnKey((char)9,shift); }
if(K == Keys.Back) {this.OnKey((char)8,shift); }
_Owner.Invalidate();
return false;
}
public void InsertReal(string x,bool select)
{
DeleteCurrentSelection();
string fx = x.Replace("" + (char)13 + (char) 10,"" + (char) 10);
fx = fx.Replace("" + (char)10, "" + (char)13);
string [] lines = fx.Split(new char[] {(char)13});
if(lines.Length == 0) return;
rtfLine L = GetCurrentLine();
string strSTART = L.ExtractLeft(L.Cursor);
lines[0] = strSTART + lines[0];
int Curse0 = lines[lines.Length - 1].Length;
lines[lines.Length - 1] += L.ExtractRight(L.Cursor);
int StartLine = _Cursor;
int EndLine = _Cursor + lines.Length - 1;
int EndPlace = Curse0;
BufferChk(_Size + lines.Length+1);
for(int k = _Size - 1; k > _Cursor; k--)
{
_Document[k+lines.Length-1] = _Document[k];
}
for(int k = 0; k < lines.Length; k++)
{
_Document[_Cursor + k] = new rtfLine(lines[k]);
}
_Size+=(lines.Length - 1);
_Cursor = _Cursor + lines.Length - 1;
_Document[_Cursor].Cursor = Curse0;
if(select)
{
SelectStart = new rtfSelectionObject();
SelectStart.Line = StartLine;
SelectStart.Place = strSTART.Length;
SelectEnd = new rtfSelectionObject();
SelectEnd.Line = EndLine;
SelectEnd.Place = EndPlace;
UpdateSelection();
}
}
public void Insert(string x)
{
PrepareUndoBuffer();
InsertReal(x,false);
SaveUndoBuffer();
}
public rtfSelectionObject SelectStart = null;
public rtfSelectionObject SelectEnd = null;
public rtfSelectionObject SelectOriginal = null;
public rtfSelectionObject GetSelectionObjectFromPoint(int x, int y)
{
int lIdx = GetLineIndexFromPoint(x,y);
if(lIdx >= 0)
{
rtfSelectionObject SS = new rtfSelectionObject();
SS.Line = lIdx;
if(_Document[lIdx]==null)
{
SS.Place = 0;
_Document[lIdx] = new rtfLine();
}
else
{
SS.Place = _Document[lIdx].Position2Cursor(x);
}
return SS;
}
return null;
}
public void OnDoubleClick(int x, int y)
{
SelectOriginal = GetSelectionObjectFromPoint(x,y);
if(SelectOriginal != null)
{
SelectStart = SelectOriginal.copy();
SelectEnd = SelectOriginal.copy();
_Cursor = SelectStart.Line;
GetCurrentLine().SelectWord(SelectStart,SelectEnd);
SelectOriginal = null;
if(SelectEnd.Place == SelectStart.Place)
{
SelectEnd = null;
SelectStart = null;
}
else
{
UpdateSelection();
}
}
}
int BackupCursorD;
int BackupCursorL;
bool CursorDrag;
public void BackupCursor()
{
CursorDrag = true;
BackupCursorD = _Cursor;
BackupCursorL = GetCurrentLine().Cursor;
}
public void CommitBackup()
{
CursorDrag = false;
}
public void RestoreBackup()
{
_Cursor = BackupCursorD;
GetCurrentLine().SetCursor( BackupCursorL );
}
public bool IsCursorAlwaysOn()
{
return CursorDrag;
}
public void OnDrag(int x, int y)
{
rtfSelectionObject R = GetSelectionObjectFromPoint(x,y);
if(R != null)
{
SyncCursor(R);
}
}
public void OnLeftMouseDown(int x, int y)
{
if(SelectOriginal == null)
{
if(ShiftSelect != null)
{
SelectOriginal = ShiftSelect;
}
else
{
SelectOriginal = GetSelectionObjectFromPoint(x,y);
}
if(SelectOriginal != null)
{
SelectStart = SelectOriginal.copy();
SelectEnd = SelectOriginal.copy();
}
}
}
public void SyncCursor(rtfSelectionObject o)
{
_Cursor = o.Line;
GetCurrentLine().SetCursor(o.Place);
}
public void MoveSelection2Point(rtfSelectionObject start, rtfSelectionObject end, int x, int y)
{
string txt = ExtractSelection();
rtfSelectionObject obj = GetSelectionObjectFromPoint(x,y);
if(obj.Line > end.Line || (obj.Line == end.Line && obj.Place > end.Place))
{
PrepareUndoBuffer();
SelectStart = null;
SelectEnd = null;
SyncCursor(obj);
InsertReal(txt,true);
rtfSelectionObject nextStart = SelectStart;
rtfSelectionObject nextEnd = SelectEnd;
SelectStart = start;
SelectEnd = end;
UpdateSelection();
rtfSelectionObject track = new rtfSelectionObject();
track.Line = nextStart.Line;
track.Place = 0;
DeleteCurrentSelectionReal(track);
nextStart.Place += track.Place;
if(nextStart.Line == nextEnd.Line) nextEnd.Place += track.Place;
nextStart.Line += track.Line;
nextEnd.Line += track.Line;
/*
int dP = 0;
if(nextStart.Line == nextEnd.Line)
{
dP = sP - track.Place;
}
int dT = sT - track.Line;
nextEnd.Line -= dT;
nextEnd.Place -= dP;
nextStart = track;
*/
// MessageBox.Show("Start:" + track.Line + ":" + track.Place);
SelectStart = nextStart;
SelectEnd = nextEnd;
UpdateSelection();
SyncCursor(nextEnd);
SaveUndoBuffer();
return;
}
if(obj.Line < start.Line || (obj.Line == start.Line && obj.Place < start.Place))
{
PrepareUndoBuffer();
DeleteCurrentSelection();
SyncCursor(obj);
InsertReal(txt,true);
SaveUndoBuffer();
return;
}
SyncCursor(obj);
}
public void ClearSelection()
{
for(int ln = 0; ln < _Size; ln++)
{
rtfLine L =_Document[ln];
if(L!=null)
{
L.ClearHighlight();
}
}
_Owner.Invalidate();
}
public void SelectAll()
{
SelectOriginal = new rtfSelectionObject();
SelectOriginal.Line = 0;
SelectOriginal.Place = 0;
SelectStart = SelectOriginal.copy();
SelectEnd = SelectOriginal.copy();
SelectEnd.Line = _Size - 1;
SelectEnd.Place = 1;
_Cursor = _Size - 1;
if(_Document[_Size-1]!=null)
{
SelectEnd.Place = _Document[_Size-1].Length();
_Document[_Size-1].SetCursor(SelectEnd.Place);
}
UpdateSelection();
SelectOriginal = null;
}
public bool ReqCursorFitStage2 = false;
public void MakeCursorFitStage2()
{
if(_Document[_Cursor]!=null)
{
_Owner.FitCursor(_Document[_Cursor].CursorX3());
}
}
public void MakeCursorFit()
{
if(_Cursor < _ScrollTop)
{
_ScrollTop = Math.Max(0,_Cursor);
return;
}
if(_Cursor >= _ScrollTop + _RenderedLines)
{
_ScrollTop = Math.Max(0,Math.Min(_Size - 1, _Cursor - _RenderedLines + 1));
}
ReqCursorFitStage2 = true;
_Owner.Invalidate();
}
public void UpdateSelection()
{
for(int ln = 0; ln < _Size; ln++)
{
rtfLine L =_Document[ln];
if(L!=null)
{
if(SelectStart.Line <= ln && ln <= SelectEnd.Line)
{
if(SelectStart.Line < ln && ln < SelectEnd.Line)
{
L.HighlightAll();
}
else
{
if(SelectStart.Line == SelectEnd.Line)
{
L.HighlightInner(SelectStart.Place,SelectEnd.Place);
}
else if(SelectStart.Line == ln)
{
L.HighlightRight(SelectStart.Place);
}
else
{
L.HighlightLeft(SelectEnd.Place);
}
}
}
else
{
L.ClearHighlight();
}
}
}
_Owner.Invalidate();
}
public void RunSelectLogic2(rtfSelectionObject latest)
{
if(latest != null && SelectStart != null && SelectEnd != null)
{
SelectStart.Line = Math.Min(latest.Line,SelectOriginal.Line);
SelectEnd.Line = Math.Max(latest.Line,SelectOriginal.Line);
if(SelectStart.Line == SelectEnd.Line)
{
SelectStart.Place = Math.Min(latest.Place,SelectOriginal.Place);
SelectEnd.Place = Math.Max(latest.Place,SelectOriginal.Place);
}
else
{
if(SelectStart.Line == SelectOriginal.Line)
{
SelectStart.Place = SelectOriginal.Place;
SelectEnd.Place = latest.Place;
}
else // SelectEnd.Line = SelectORigi.lin
{
SelectEnd.Place = SelectOriginal.Place;
SelectStart.Place = latest.Place;
}
}
UpdateSelection();
}
}
int lasLogiX = 0;
int lasLogiY = 0;
public void RepeatSelectLogic()
{
if(SelectOriginal != null)
{
RunSelectLogic(lasLogiX,lasLogiY);
}
}
public rtfSelectionObject GetSTART()
{
return SelectStart;
}
public rtfSelectionObject GetEND()
{
return SelectEnd;
}
public void RunSelectLogic(int x, int y)
{
if(SelectOriginal != null)
{
lasLogiX = x;
lasLogiY = y;
RunSelectLogic2(GetSelectionObjectFromPoint(x,y));
}
}
public void OnLeftMouseMove(int x, int y)
{
RunSelectLogic(x,y);
if(SelectStart != null && SelectEnd != null)
{
_Cursor = SelectEnd.Line;
GetCurrentLine().SetCursor(SelectEnd.Place);
}
}
public bool OnPassiveMouseMove(int x, int y)
{
if(IsSelectionEmpty()) return false;
rtfSelectionObject obj = GetSelectionObjectFromPoint(x,y);
if(obj != null)
{
if(SelectStart != null && SelectEnd != null)
{
if(SelectStart.Line <= obj.Line && obj.Line <= SelectEnd.Line)
{
return lineAt(obj.Line).IsHighlighted(obj.Place);
}
return false;
}
return false;
}
return false;
}
public bool AutoScrollUp(int D)
{
if(SelectStart == null) return false;
if(SelectOriginal == null) return false;
if(_ScrollTop > 0) { _ScrollTop -= D; _ScrollTop = Math.Min(Math.Max(0,_ScrollTop),_Size -1) ; return true; }
return false;
}
public bool AutoScrollDown(int D)
{
if(SelectEnd == null) return false;
if(SelectOriginal == null) return false;
int Old = _ScrollTop;
_ScrollTop += D;
_ScrollTop = Math.Max(0,Math.Min(_ScrollTop,_Size - _RenderedLines + 1));
if(Old != _ScrollTop) return true;
return false;
}
public void KillUndoStack()
{
_Redo = new Stack();
_Undo = new Stack();
}
public void OnLeftMouseUp(int x, int y)
{
if(SelectOriginal != null)
{
RunSelectLogic(x,y);
if(SelectEnd != null && SelectStart != null)
{
_Cursor = SelectEnd.Line;
_Document[_Cursor].SetCursor(SelectEnd.Place);
}
SelectOriginal = null;
InvCur = true;
}
}
public int NumLines()
{
return _Size;
}
public int Top() { return _ScrollTop; }
public int RenderedLines()
{
return _RenderedLines;
}
int RenderedHeight = 0;
int LastRenderedLine = 0;
public void OptimizePassize()
{
for(int k = 0; k < _Cursor - 2; k++)
{
if(_Document[k]!=null) _Document[k].Optimize();
}
for(int k = _Cursor + 2; k < _Size; k++)
{
if(_Document[k]!=null) _Document[k].Optimize();
}
}
public string GetTEXT()
{
System.IO.StringWriter SW = new System.IO.StringWriter();
for(int k = 0; k < _Size; k++)
{
if(_Document[k] == null)
SW.WriteLine("");
else
SW.WriteLine(_Document[k].ExtractAll());
}
return SW.ToString();
}
public void Render(Graphics g, Rectangle clip, rtfDisplayCursor rtfdc, int tr, int max)
{
RenderedHeight = max;
_ScrollTop = Math.Max(0,Math.Min(_Size - 1, _ScrollTop));
_Cursor = Math.Max(0,_Cursor);
rtfdc.h = -1;
Size Sz = g.MeasureString("ZEN",_Library.StyleText[0]).ToSize();
int y = 0;
for(int ln = 0; ln < _Size; ln++)
{
_Document[ln].Reset();
_Document[ln].BuildHeight(g,_Library);
}
if(_RenderedLines < 0)
{
_RenderedLines = (int)(Math.Ceiling(max / (double)(Sz.Height)));
}
int Actual = 0;
for(int ln = _ScrollTop; ln < _Size && y < max; ln++)
{
Actual ++;
LastRenderedLine = ln;
if(_Document[ln]!=null)
{
int h = _Document[ln].Render(g,_Library,y,ln + 1,tr,-1);
if(ln == _Cursor)
{
rtfdc.h = h;
rtfdc.y = y;
rtfdc.x = _Document[ln].CursorX();
}
y += h;
}
else
{
y += Sz.Height;
}
}
if(y < max)
{
_RenderedLines = Actual - 1 + (int)(Math.Ceiling((max - y)/ (double)(Sz.Height)));
//_RenderedLines = Math.Max(Actual - 1,_RenderedLines);
}
else
{
_RenderedLines = Actual - 1;
}
//g.DrawString("" + (LastRenderedLine+1) + ":" + (_ScrollTop + 1 + _RenderedLines),_Library.LineNumberText,_Library.LineNumberBack,500,10);
_ScrollTop = Math.Max(0,Math.Min(_Size - _RenderedLines + 1, _ScrollTop));
if(ReqCursorFitStage2)
{
ReqCursorFitStage2 = false;
MakeCursorFitStage2();
}
}
public void BufferChk(int s)
{
if(s >= _Document.Length)
{
int x;
rtfLine [] _NewDocument = new rtfLine[s * 2];
for(x = 0; x < _Size; x++)
_NewDocument[x] = _Document[x];
for(x = _Size; x < _NewDocument.Length; x++)
_NewDocument[x] = null;
_Document = _NewDocument;
}
}
public int Height()
{
int h = 0;
for(int k = 0; k < _Size; k++) if(_Document[k] != null) h+= _Document[k].Bounds.Height;
return h;
}
public int Width()
{
int w = 0;
for(int k = 0; k < _Size; k++) if(_Document[k] != null) w = Math.Max(w,_Document[k].Bounds.Width);
return w;
}
public int PrintPage(int PageNum, int Start, Graphics g, int max,int Wmax)
{
Size Sz = g.MeasureString("ZEN",_Library.StyleText[0]).ToSize();
int y = 0;
int sent = 0;
for(int ln = Start; ln < _Size && y + Sz.Height < max; ln++)
{
sent++;
if(_Document[ln]!=null)
{
int h = _Document[ln].Render(g,_Library,y,ln + 1,0,Wmax);
Sz.Height = Math.Max(h,Sz.Height);
y += h;
}
else
{
y += Sz.Height;
}
}
return sent;
}
}
}
| |
//
// XslKey.cs
//
// Authors:
// Ben Maurer (bmaurer@users.sourceforge.net)
// Atsushi Enomoto (ginga@kit.hi-ho.ne.jp)
//
// (C) 2003 Ben Maurer
// (C) 2003 Atsushi Enomoto
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;
using Mono.Xml.XPath;
using QName = System.Xml.XmlQualifiedName;
namespace Mono.Xml.Xsl
{
internal class ExprKeyContainer : Expression
{
Expression expr;
public ExprKeyContainer (Expression expr)
{
this.expr = expr;
}
public Expression BodyExpression {
get { return expr; }
}
public override object Evaluate (BaseIterator iter)
{
return expr.Evaluate (iter);
}
internal override XPathNodeType EvaluatedNodeType {
get { return expr.EvaluatedNodeType; }
}
public override XPathResultType ReturnType {
get { return expr.ReturnType; }
}
}
internal class XslKey
{
QName name;
CompiledExpression useExpr;
Pattern matchPattern;
public XslKey (Compiler c)
{
this.name = c.ParseQNameAttribute ("name");
c.KeyCompilationMode = true;
useExpr = c.CompileExpression (c.GetAttribute ("use"));
if (useExpr == null)
useExpr = c.CompileExpression (".");
c.AssertAttribute ("match");
string matchString = c.GetAttribute ("match");
this.matchPattern = c.CompilePattern (matchString, c.Input);
c.KeyCompilationMode = false;
}
public QName Name { get { return name; }}
internal CompiledExpression Use { get { return useExpr; }}
internal Pattern Match { get { return matchPattern; }}
}
// represents part of dynamic context that holds index table for a key
internal class KeyIndexTable
{
// XsltCompiledContext ctx;
ArrayList keys;
Hashtable mappedDocuments;
public KeyIndexTable (XsltCompiledContext ctx, ArrayList keys)
{
// this.ctx = ctx;
this.keys = keys;
}
public ArrayList Keys {
get { return keys; }
}
private void CollectTable (XPathNavigator doc, XsltContext ctx, Hashtable map)
{
for (int i = 0; i < keys.Count; i++)
CollectTable (doc, ctx, map, (XslKey) keys[i]);
}
private void CollectTable (XPathNavigator doc, XsltContext ctx, Hashtable map, XslKey key)
{
XPathNavigator nav = doc.Clone ();
nav.MoveToRoot ();
XPathNavigator tmp = doc.Clone ();
bool matchesAttributes = false;
switch (key.Match.EvaluatedNodeType) {
case XPathNodeType.All:
case XPathNodeType.Attribute:
matchesAttributes = true;
break;
}
do {
if (key.Match.Matches (nav, ctx)) {
tmp.MoveTo (nav);
CollectIndex (nav, tmp, map);
}
} while (MoveNavigatorToNext (nav, matchesAttributes));
if (map != null)
foreach (ArrayList list in map.Values)
list.Sort (XPathNavigatorComparer.Instance);
}
private bool MoveNavigatorToNext (XPathNavigator nav, bool matchesAttributes)
{
if (matchesAttributes) {
if (nav.NodeType != XPathNodeType.Attribute &&
nav.MoveToFirstAttribute ())
return true;
else if (nav.NodeType == XPathNodeType.Attribute) {
if (nav.MoveToNextAttribute ())
return true;
nav.MoveToParent ();
}
}
if (nav.MoveToFirstChild ())
return true;
do {
if (nav.MoveToNext ())
return true;
} while (nav.MoveToParent ());
return false;
}
private void CollectIndex (XPathNavigator nav, XPathNavigator target, Hashtable map)
{
for (int i = 0; i < keys.Count; i++)
CollectIndex (nav, target, map, (XslKey) keys[i]);
}
private void CollectIndex (XPathNavigator nav, XPathNavigator target, Hashtable map, XslKey key)
{
XPathNodeIterator iter;
switch (key.Use.ReturnType) {
case XPathResultType.NodeSet:
iter = nav.Select (key.Use);
while (iter.MoveNext ())
AddIndex (iter.Current.Value, target, map);
break;
case XPathResultType.Any:
object o = nav.Evaluate (key.Use);
iter = o as XPathNodeIterator;
if (iter != null) {
while (iter.MoveNext ())
AddIndex (iter.Current.Value, target, map);
}
else
AddIndex (XPathFunctions.ToString (o), target, map);
break;
default:
string keyValue = nav.EvaluateString (key.Use, null, null);
AddIndex (keyValue, target, map);
break;
}
}
private void AddIndex (string key, XPathNavigator target, Hashtable map)
{
ArrayList al = map [key] as ArrayList;
if (al == null) {
al = new ArrayList ();
map [key] = al;
}
for (int i = 0; i < al.Count; i++)
if (((XPathNavigator) al [i]).IsSamePosition (target))
return;
al.Add (target.Clone ());
}
private ArrayList GetNodesByValue (XPathNavigator nav, string value, XsltContext ctx)
{
if (mappedDocuments == null)
mappedDocuments = new Hashtable ();
Hashtable map = (Hashtable) mappedDocuments [nav.BaseURI];
if (map == null) {
map = new Hashtable ();
mappedDocuments.Add (nav.BaseURI, map);
CollectTable (nav, ctx, map);
}
return map [value] as ArrayList;
}
public bool Matches (XPathNavigator nav, string value, XsltContext ctx)
{
ArrayList al = GetNodesByValue (nav, value, ctx);
if (al == null)
return false;
for (int i = 0; i < al.Count; i++)
if (((XPathNavigator) al [i]).IsSamePosition (nav))
return true;
return false;
}
// Invoked from XsltKey (XPathFunction)
public BaseIterator Evaluate (BaseIterator iter,
Expression valueExpr)
{
XPathNodeIterator i = iter;
if (iter.CurrentPosition == 0) {
i = iter.Clone ();
i.MoveNext ();
}
XPathNavigator nav = i.Current;
object o = valueExpr.Evaluate (iter);
XPathNodeIterator it = o as XPathNodeIterator;
XsltContext ctx = iter.NamespaceManager as XsltContext;
BaseIterator result = null;
if (it != null) {
while (it.MoveNext()) {
ArrayList nodes = GetNodesByValue (
nav, it.Current.Value, ctx);
if (nodes == null)
continue;
ListIterator tmp =
new ListIterator (nodes, ctx);
if (result == null)
result = tmp;
else
result = new UnionIterator (
iter, result, tmp);
}
}
else if (nav != null) {
ArrayList nodes = GetNodesByValue (
nav, XPathFunctions.ToString (o), ctx);
if (nodes != null)
result = new ListIterator (nodes, ctx);
}
return result != null ? result : new NullIterator (iter);
}
}
}
| |
#region Copyright
/*
Copyright 2014 Cluster Reply s.r.l.
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
/// -----------------------------------------------------------------------------------------------------------
/// Module : AdoNetAdapterBindingElement.cs
/// Description : Provides a base class for the configuration elements.
/// -----------------------------------------------------------------------------------------------------------
#region Using Directives
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Configuration;
using System.ServiceModel.Channels;
using System.Configuration;
using System.Globalization;
using Microsoft.ServiceModel.Channels.Common;
#endregion
namespace Reply.Cluster.Mercury.Adapters.AdoNet
{
public class AdoNetAdapterBindingElement : StandardBindingElement
{
private ConfigurationPropertyCollection properties;
#region Constructors
/// <summary>
/// Initializes a new instance of the AdoNetAdapterBindingElement class
/// </summary>
public AdoNetAdapterBindingElement()
: base(null)
{
}
/// <summary>
/// Initializes a new instance of the AdoNetAdapterBindingElement class with a configuration name
/// </summary>
public AdoNetAdapterBindingElement(string configurationName)
: base(configurationName)
{
}
#endregion Constructors
#region Custom Generated Properties
[System.Configuration.ConfigurationProperty("DataAvailableStatement")]
[System.ComponentModel.Category("Polling Data")]
public string DataAvailableStatement
{
get
{
return ((string)(base["DataAvailableStatement"]));
}
set
{
base["DataAvailableStatement"] = value;
}
}
[System.Configuration.ConfigurationProperty("GetDataStatement")]
[System.ComponentModel.Category("Polling Data")]
public string GetDataStatement
{
get
{
return ((string)(base["GetDataStatement"]));
}
set
{
base["GetDataStatement"] = value;
}
}
[System.Configuration.ConfigurationProperty("EndOperationStatement")]
[System.ComponentModel.Category("Polling Data")]
public string EndOperationStatement
{
get
{
return ((string)(base["EndOperationStatement"]));
}
set
{
base["EndOperationStatement"] = value;
}
}
[System.Configuration.ConfigurationProperty("useAmbientTransaction", DefaultValue = true)]
[System.ComponentModel.Category("Transactions")]
public bool UseAmbientTransaction
{
get
{
return ((bool)(base["UseAmbientTransaction"]));
}
set
{
base["UseAmbientTransaction"] = value;
}
}
[System.Configuration.ConfigurationProperty("isolationLevel", DefaultValue = System.Transactions.IsolationLevel.ReadCommitted)]
[System.ComponentModel.Category("Transactions")]
public System.Transactions.IsolationLevel IsolationLevel
{
get
{
return ((System.Transactions.IsolationLevel)(base["IsolationLevel"]));
}
set
{
base["IsolationLevel"] = value;
}
}
[System.Configuration.ConfigurationProperty("pollWhileDataFound", DefaultValue = false)]
[System.ComponentModel.Category("Schedule")]
public bool PollWhileDataFound
{
get
{
return ((bool)(base["PollWhileDataFound"]));
}
set
{
base["PollWhileDataFound"] = value;
}
}
[System.Configuration.ConfigurationProperty("pollingType", DefaultValue = PollingType.Simple)]
[System.ComponentModel.Category("Schedule")]
public PollingType PollingType
{
get
{
return ((PollingType)(base["PollingType"]));
}
set
{
base["PollingType"] = value;
}
}
[System.Configuration.ConfigurationProperty("pollingInterval", DefaultValue = 30)]
[System.ComponentModel.Category("Schedule")]
public int PollingInterval
{
get
{
return ((int)(base["PollingInterval"]));
}
set
{
base["PollingInterval"] = value;
}
}
[System.Configuration.ConfigurationProperty("scheduleName")]
[System.ComponentModel.Category("Schedule")]
public string ScheduleName
{
get
{
return ((string)(base["ScheduleName"]));
}
set
{
base["ScheduleName"] = value;
}
}
#endregion Custom Generated Properties
#region Protected Properties
/// <summary>
/// Gets the type of the BindingElement
/// </summary>
protected override Type BindingElementType
{
get
{
return typeof(AdoNetAdapterBinding);
}
}
#endregion Protected Properties
#region StandardBindingElement Members
/// <summary>
/// Initializes the binding with the configuration properties
/// </summary>
protected override void InitializeFrom(Binding binding)
{
base.InitializeFrom(binding);
AdoNetAdapterBinding adapterBinding = (AdoNetAdapterBinding)binding;
this["DataAvailableStatement"] = adapterBinding.DataAvailableStatement;
this["GetDataStatement"] = adapterBinding.GetDataStatement;
this["EndOperationStatement"] = adapterBinding.EndOperationStatement;
this["UseAmbientTransaction"] = adapterBinding.UseAmbientTransaction;
this["IsolationLevel"] = adapterBinding.IsolationLevel;
this["PollWhileDataFound"] = adapterBinding.PollWhileDataFound;
this["PollingType"] = adapterBinding.PollingType;
this["PollingInterval"] = adapterBinding.PollingInterval;
this["ScheduleName"] = adapterBinding.ScheduleName;
}
/// <summary>
/// Applies the configuration
/// </summary>
protected override void OnApplyConfiguration(Binding binding)
{
if (binding == null)
throw new ArgumentNullException("binding");
AdoNetAdapterBinding adapterBinding = (AdoNetAdapterBinding)binding;
adapterBinding.DataAvailableStatement = (System.String)this["DataAvailableStatement"];
adapterBinding.GetDataStatement = (System.String)this["GetDataStatement"];
adapterBinding.EndOperationStatement = (System.String)this["EndOperationStatement"];
adapterBinding.UseAmbientTransaction = (System.Boolean)this["UseAmbientTransaction"];
adapterBinding.IsolationLevel = (System.Transactions.IsolationLevel)this["IsolationLevel"];
adapterBinding.PollWhileDataFound = (System.Boolean)this["PollWhileDataFound"];
adapterBinding.PollingType = (PollingType)this["PollingType"];
adapterBinding.PollingInterval = (System.Int32)this["PollingInterval"];
adapterBinding.ScheduleName = (System.String)this["ScheduleName"];
}
/// <summary>
/// Returns a collection of the configuration properties
/// </summary>
protected override ConfigurationPropertyCollection Properties
{
get
{
if (this.properties == null)
{
ConfigurationPropertyCollection configProperties = base.Properties;
configProperties.Add(new ConfigurationProperty("DataAvailableStatement", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("GetDataStatement", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("EndOperationStatement", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("UseAmbientTransaction", typeof(System.Boolean), true, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("IsolationLevel", typeof(System.Transactions.IsolationLevel), System.Transactions.IsolationLevel.ReadCommitted, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("PollWhileDataFound", typeof(System.Boolean), false, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("PollingType", typeof(PollingType), PollingType.Simple, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("PollingInterval", typeof(System.Int32), (System.Int32)30, null, null, ConfigurationPropertyOptions.None));
configProperties.Add(new ConfigurationProperty("ScheduleName", typeof(System.String), null, null, null, ConfigurationPropertyOptions.None));
this.properties = configProperties;
}
return this.properties;
}
}
#endregion StandardBindingElement Members
}
}
| |
/*
* 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
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading.Tasks;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Cache;
using Apache.Ignite.Core.Cache.Configuration;
using Apache.Ignite.Core.Cluster;
using Apache.Ignite.Core.Common;
using Apache.Ignite.Core.Compute;
using Apache.Ignite.Core.Datastream;
using Apache.Ignite.Core.DataStructures;
using Apache.Ignite.Core.Events;
using Apache.Ignite.Core.Impl.Binary;
using Apache.Ignite.Core.Impl.Cache;
using Apache.Ignite.Core.Impl.Cluster;
using Apache.Ignite.Core.Impl.Common;
using Apache.Ignite.Core.Impl.Datastream;
using Apache.Ignite.Core.Impl.DataStructures;
using Apache.Ignite.Core.Impl.Handle;
using Apache.Ignite.Core.Impl.Plugin;
using Apache.Ignite.Core.Impl.Transactions;
using Apache.Ignite.Core.Impl.Unmanaged;
using Apache.Ignite.Core.Interop;
using Apache.Ignite.Core.Lifecycle;
using Apache.Ignite.Core.Log;
using Apache.Ignite.Core.Messaging;
using Apache.Ignite.Core.PersistentStore;
using Apache.Ignite.Core.Services;
using Apache.Ignite.Core.Transactions;
using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils;
/// <summary>
/// Native Ignite wrapper.
/// </summary>
internal class Ignite : PlatformTargetAdapter, ICluster, IIgniteInternal, IIgnite
{
/// <summary>
/// Operation codes for PlatformProcessorImpl calls.
/// </summary>
private enum Op
{
GetCache = 1,
CreateCache = 2,
GetOrCreateCache = 3,
CreateCacheFromConfig = 4,
GetOrCreateCacheFromConfig = 5,
DestroyCache = 6,
GetAffinity = 7,
GetDataStreamer = 8,
GetTransactions = 9,
GetClusterGroup = 10,
GetExtension = 11,
GetAtomicLong = 12,
GetAtomicReference = 13,
GetAtomicSequence = 14,
GetIgniteConfiguration = 15,
GetCacheNames = 16,
CreateNearCache = 17,
GetOrCreateNearCache = 18,
LoggerIsLevelEnabled = 19,
LoggerLog = 20,
GetBinaryProcessor = 21,
ReleaseStart = 22,
AddCacheConfiguration = 23,
SetBaselineTopologyVersion = 24,
SetBaselineTopologyNodes = 25,
GetBaselineTopology = 26,
DisableWal = 27,
EnableWal = 28,
IsWalEnabled = 29,
SetTxTimeoutOnPartitionMapExchange = 30
}
/** */
private readonly IgniteConfiguration _cfg;
/** Grid name. */
private readonly string _name;
/** Unmanaged node. */
private readonly IPlatformTargetInternal _proc;
/** Marshaller. */
private readonly Marshaller _marsh;
/** Initial projection. */
private readonly ClusterGroupImpl _prj;
/** Binary. */
private readonly Binary.Binary _binary;
/** Binary processor. */
private readonly BinaryProcessor _binaryProc;
/** Lifecycle handlers. */
private readonly IList<LifecycleHandlerHolder> _lifecycleHandlers;
/** Local node. */
private IClusterNode _locNode;
/** Callbacks */
private readonly UnmanagedCallbacks _cbs;
/** Node info cache. */
private readonly ConcurrentDictionary<Guid, ClusterNodeImpl> _nodes =
new ConcurrentDictionary<Guid, ClusterNodeImpl>();
/** Client reconnect task completion source. */
private volatile TaskCompletionSource<bool> _clientReconnectTaskCompletionSource =
new TaskCompletionSource<bool>();
/** Plugin processor. */
private readonly PluginProcessor _pluginProcessor;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="cfg">Configuration.</param>
/// <param name="name">Grid name.</param>
/// <param name="proc">Interop processor.</param>
/// <param name="marsh">Marshaller.</param>
/// <param name="lifecycleHandlers">Lifecycle beans.</param>
/// <param name="cbs">Callbacks.</param>
public Ignite(IgniteConfiguration cfg, string name, IPlatformTargetInternal proc, Marshaller marsh,
IList<LifecycleHandlerHolder> lifecycleHandlers, UnmanagedCallbacks cbs) : base(proc)
{
Debug.Assert(cfg != null);
Debug.Assert(proc != null);
Debug.Assert(marsh != null);
Debug.Assert(lifecycleHandlers != null);
Debug.Assert(cbs != null);
_cfg = cfg;
_name = name;
_proc = proc;
_marsh = marsh;
_lifecycleHandlers = lifecycleHandlers;
_cbs = cbs;
marsh.Ignite = this;
_prj = new ClusterGroupImpl(Target.OutObjectInternal((int) Op.GetClusterGroup), null);
_binary = new Binary.Binary(marsh);
_binaryProc = new BinaryProcessor(DoOutOpObject((int) Op.GetBinaryProcessor));
cbs.Initialize(this);
// Set reconnected task to completed state for convenience.
_clientReconnectTaskCompletionSource.SetResult(false);
SetCompactFooter();
_pluginProcessor = new PluginProcessor(this);
}
/// <summary>
/// Sets the compact footer setting.
/// </summary>
private void SetCompactFooter()
{
if (!string.IsNullOrEmpty(_cfg.SpringConfigUrl))
{
// If there is a Spring config, use setting from Spring,
// since we ignore .NET config in legacy mode.
var cfg0 = GetConfiguration().BinaryConfiguration;
if (cfg0 != null)
_marsh.CompactFooter = cfg0.CompactFooter;
}
}
/// <summary>
/// On-start routine.
/// </summary>
internal void OnStart()
{
PluginProcessor.OnIgniteStart();
foreach (var lifecycleBean in _lifecycleHandlers)
lifecycleBean.OnStart(this);
}
/** <inheritdoc /> */
public string Name
{
get { return _name; }
}
/** <inheritdoc /> */
public ICluster GetCluster()
{
return this;
}
/** <inheritdoc /> */
IIgnite IClusterGroup.Ignite
{
get { return this; }
}
/** <inheritdoc /> */
public IClusterGroup ForLocal()
{
return _prj.ForNodes(GetLocalNode());
}
/** <inheritdoc /> */
public ICompute GetCompute()
{
return _prj.ForServers().GetCompute();
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(IEnumerable<IClusterNode> nodes)
{
return _prj.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodes(params IClusterNode[] nodes)
{
return _prj.ForNodes(nodes);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(IEnumerable<Guid> ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForNodeIds(params Guid[] ids)
{
return _prj.ForNodeIds(ids);
}
/** <inheritdoc /> */
public IClusterGroup ForPredicate(Func<IClusterNode, bool> p)
{
IgniteArgumentCheck.NotNull(p, "p");
return _prj.ForPredicate(p);
}
/** <inheritdoc /> */
public IClusterGroup ForAttribute(string name, string val)
{
return _prj.ForAttribute(name, val);
}
/** <inheritdoc /> */
public IClusterGroup ForCacheNodes(string name)
{
return _prj.ForCacheNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForDataNodes(string name)
{
return _prj.ForDataNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForClientNodes(string name)
{
return _prj.ForClientNodes(name);
}
/** <inheritdoc /> */
public IClusterGroup ForRemotes()
{
return _prj.ForRemotes();
}
/** <inheritdoc /> */
public IClusterGroup ForDaemons()
{
return _prj.ForDaemons();
}
/** <inheritdoc /> */
public IClusterGroup ForHost(IClusterNode node)
{
IgniteArgumentCheck.NotNull(node, "node");
return _prj.ForHost(node);
}
/** <inheritdoc /> */
public IClusterGroup ForRandom()
{
return _prj.ForRandom();
}
/** <inheritdoc /> */
public IClusterGroup ForOldest()
{
return _prj.ForOldest();
}
/** <inheritdoc /> */
public IClusterGroup ForYoungest()
{
return _prj.ForYoungest();
}
/** <inheritdoc /> */
public IClusterGroup ForDotNet()
{
return _prj.ForDotNet();
}
/** <inheritdoc /> */
public IClusterGroup ForServers()
{
return _prj.ForServers();
}
/** <inheritdoc /> */
public ICollection<IClusterNode> GetNodes()
{
return _prj.GetNodes();
}
/** <inheritdoc /> */
public IClusterNode GetNode(Guid id)
{
return _prj.GetNode(id);
}
/** <inheritdoc /> */
public IClusterNode GetNode()
{
return _prj.GetNode();
}
/** <inheritdoc /> */
public IClusterMetrics GetMetrics()
{
return _prj.GetMetrics();
}
/** <inheritdoc /> */
[SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly",
Justification = "There is no finalizer.")]
[SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "_proxy",
Justification = "Proxy does not need to be disposed.")]
public void Dispose()
{
Ignition.Stop(Name, true);
}
/// <summary>
/// Internal stop routine.
/// </summary>
/// <param name="cancel">Cancel flag.</param>
internal void Stop(bool cancel)
{
var jniTarget = _proc as PlatformJniTarget;
if (jniTarget == null)
{
throw new IgniteException("Ignition.Stop is not supported in thin client.");
}
UU.IgnitionStop(Name, cancel);
_cbs.Cleanup();
}
/// <summary>
/// Called before node has stopped.
/// </summary>
internal void BeforeNodeStop()
{
var handler = Stopping;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Called after node has stopped.
/// </summary>
internal void AfterNodeStop()
{
foreach (var bean in _lifecycleHandlers)
bean.OnLifecycleEvent(LifecycleEventType.AfterNodeStop);
var handler = Stopped;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return GetCache<TK, TV>(DoOutOpObject((int) Op.GetCache, w => w.WriteString(name)));
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
return GetCache<TK, TV>(DoOutOpObject((int) Op.GetOrCreateCache, w => w.WriteString(name)));
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration)
{
return GetOrCreateCache<TK, TV>(configuration, null);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration)
{
return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.GetOrCreateCacheFromConfig);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
var cacheTarget = DoOutOpObject((int) Op.CreateCache, w => w.WriteString(name));
return GetCache<TK, TV>(cacheTarget);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration)
{
return CreateCache<TK, TV>(configuration, null);
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration)
{
return GetOrCreateCache<TK, TV>(configuration, nearConfiguration, Op.CreateCacheFromConfig);
}
/// <summary>
/// Gets or creates the cache.
/// </summary>
private ICache<TK, TV> GetOrCreateCache<TK, TV>(CacheConfiguration configuration,
NearCacheConfiguration nearConfiguration, Op op)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
IgniteArgumentCheck.NotNull(configuration.Name, "CacheConfiguration.Name");
configuration.Validate(Logger);
var cacheTarget = DoOutOpObject((int) op, s =>
{
var w = BinaryUtils.Marshaller.StartMarshal(s);
configuration.Write(w);
if (nearConfiguration != null)
{
w.WriteBoolean(true);
nearConfiguration.Write(w);
}
else
{
w.WriteBoolean(false);
}
});
return GetCache<TK, TV>(cacheTarget);
}
/** <inheritdoc /> */
public void DestroyCache(string name)
{
IgniteArgumentCheck.NotNull(name, "name");
DoOutOp((int) Op.DestroyCache, w => w.WriteString(name));
}
/// <summary>
/// Gets cache from specified native cache object.
/// </summary>
/// <param name="nativeCache">Native cache.</param>
/// <param name="keepBinary">Keep binary flag.</param>
/// <returns>
/// New instance of cache wrapping specified native cache.
/// </returns>
public static ICache<TK, TV> GetCache<TK, TV>(IPlatformTargetInternal nativeCache, bool keepBinary = false)
{
return new CacheImpl<TK, TV>(nativeCache, false, keepBinary, false, false);
}
/** <inheritdoc /> */
public IClusterNode GetLocalNode()
{
return _locNode ?? (_locNode =
GetNodes().FirstOrDefault(x => x.IsLocal) ??
ForDaemons().GetNodes().FirstOrDefault(x => x.IsLocal));
}
/** <inheritdoc /> */
public bool PingNode(Guid nodeId)
{
return _prj.PingNode(nodeId);
}
/** <inheritdoc /> */
public long TopologyVersion
{
get { return _prj.TopologyVersion; }
}
/** <inheritdoc /> */
public ICollection<IClusterNode> GetTopology(long ver)
{
return _prj.Topology(ver);
}
/** <inheritdoc /> */
public void ResetMetrics()
{
_prj.ResetMetrics();
}
/** <inheritdoc /> */
public Task<bool> ClientReconnectTask
{
get { return _clientReconnectTaskCompletionSource.Task; }
}
/** <inheritdoc /> */
public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return GetDataStreamer<TK, TV>(cacheName, false);
}
/// <summary>
/// Gets the data streamer.
/// </summary>
public IDataStreamer<TK, TV> GetDataStreamer<TK, TV>(string cacheName, bool keepBinary)
{
var streamerTarget = DoOutOpObject((int) Op.GetDataStreamer, w =>
{
w.WriteString(cacheName);
w.WriteBoolean(keepBinary);
});
return new DataStreamerImpl<TK, TV>(streamerTarget, _marsh, cacheName, keepBinary);
}
/// <summary>
/// Gets the public Ignite interface.
/// </summary>
public IIgnite GetIgnite()
{
return this;
}
/** <inheritdoc /> */
public IBinary GetBinary()
{
return _binary;
}
/** <inheritdoc /> */
public ICacheAffinity GetAffinity(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
var aff = DoOutOpObject((int) Op.GetAffinity, w => w.WriteString(cacheName));
return new CacheAffinityImpl(aff, false);
}
/** <inheritdoc /> */
public ITransactions GetTransactions()
{
return new TransactionsImpl(this, DoOutOpObject((int) Op.GetTransactions), GetLocalNode().Id);
}
/** <inheritdoc /> */
public IMessaging GetMessaging()
{
return _prj.GetMessaging();
}
/** <inheritdoc /> */
public IEvents GetEvents()
{
return _prj.GetEvents();
}
/** <inheritdoc /> */
public IServices GetServices()
{
return _prj.ForServers().GetServices();
}
/** <inheritdoc /> */
public IAtomicLong GetAtomicLong(string name, long initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var nativeLong = DoOutOpObject((int) Op.GetAtomicLong, w =>
{
w.WriteString(name);
w.WriteLong(initialValue);
w.WriteBoolean(create);
});
if (nativeLong == null)
return null;
return new AtomicLong(nativeLong, name);
}
/** <inheritdoc /> */
public IAtomicSequence GetAtomicSequence(string name, long initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var nativeSeq = DoOutOpObject((int) Op.GetAtomicSequence, w =>
{
w.WriteString(name);
w.WriteLong(initialValue);
w.WriteBoolean(create);
});
if (nativeSeq == null)
return null;
return new AtomicSequence(nativeSeq, name);
}
/** <inheritdoc /> */
public IAtomicReference<T> GetAtomicReference<T>(string name, T initialValue, bool create)
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
var refTarget = DoOutOpObject((int) Op.GetAtomicReference, w =>
{
w.WriteString(name);
w.WriteObject(initialValue);
w.WriteBoolean(create);
});
return refTarget == null ? null : new AtomicReference<T>(refTarget, name);
}
/** <inheritdoc /> */
public IgniteConfiguration GetConfiguration()
{
return DoInOp((int) Op.GetIgniteConfiguration,
s => new IgniteConfiguration(BinaryUtils.Marshaller.StartUnmarshal(s), _cfg));
}
/** <inheritdoc /> */
public ICache<TK, TV> CreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration)
{
return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.CreateNearCache);
}
/** <inheritdoc /> */
public ICache<TK, TV> GetOrCreateNearCache<TK, TV>(string name, NearCacheConfiguration configuration)
{
return GetOrCreateNearCache0<TK, TV>(name, configuration, Op.GetOrCreateNearCache);
}
/** <inheritdoc /> */
public ICollection<string> GetCacheNames()
{
return Target.OutStream((int) Op.GetCacheNames, r =>
{
var res = new string[r.ReadInt()];
for (var i = 0; i < res.Length; i++)
res[i] = r.ReadString();
return (ICollection<string>) res;
});
}
/** <inheritdoc /> */
public ILogger Logger
{
get { return _cbs.Log; }
}
/** <inheritdoc /> */
public event EventHandler Stopping;
/** <inheritdoc /> */
public event EventHandler Stopped;
/** <inheritdoc /> */
public event EventHandler ClientDisconnected;
/** <inheritdoc /> */
public event EventHandler<ClientReconnectEventArgs> ClientReconnected;
/** <inheritdoc /> */
public T GetPlugin<T>(string name) where T : class
{
IgniteArgumentCheck.NotNullOrEmpty(name, "name");
return PluginProcessor.GetProvider(name).GetPlugin<T>();
}
/** <inheritdoc /> */
public void ResetLostPartitions(IEnumerable<string> cacheNames)
{
IgniteArgumentCheck.NotNull(cacheNames, "cacheNames");
_prj.ResetLostPartitions(cacheNames);
}
/** <inheritdoc /> */
public void ResetLostPartitions(params string[] cacheNames)
{
ResetLostPartitions((IEnumerable<string>) cacheNames);
}
/** <inheritdoc /> */
#pragma warning disable 618
public ICollection<IMemoryMetrics> GetMemoryMetrics()
{
return _prj.GetMemoryMetrics();
}
/** <inheritdoc /> */
public IMemoryMetrics GetMemoryMetrics(string memoryPolicyName)
{
IgniteArgumentCheck.NotNullOrEmpty(memoryPolicyName, "memoryPolicyName");
return _prj.GetMemoryMetrics(memoryPolicyName);
}
#pragma warning restore 618
/** <inheritdoc /> */
public void SetActive(bool isActive)
{
_prj.SetActive(isActive);
}
/** <inheritdoc /> */
public bool IsActive()
{
return _prj.IsActive();
}
/** <inheritdoc /> */
public void SetBaselineTopology(long topologyVersion)
{
DoOutInOp((int) Op.SetBaselineTopologyVersion, topologyVersion);
}
/** <inheritdoc /> */
public void SetBaselineTopology(IEnumerable<IBaselineNode> nodes)
{
IgniteArgumentCheck.NotNull(nodes, "nodes");
DoOutOp((int) Op.SetBaselineTopologyNodes, w =>
{
var pos = w.Stream.Position;
w.WriteInt(0);
var cnt = 0;
foreach (var node in nodes)
{
cnt++;
BaselineNode.Write(w, node);
}
w.Stream.WriteInt(pos, cnt);
});
}
/** <inheritdoc /> */
public ICollection<IBaselineNode> GetBaselineTopology()
{
return DoInOp((int) Op.GetBaselineTopology,
s => Marshaller.StartUnmarshal(s).ReadCollectionRaw(r => (IBaselineNode) new BaselineNode(r)));
}
/** <inheritdoc /> */
public void DisableWal(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
DoOutOp((int) Op.DisableWal, w => w.WriteString(cacheName));
}
/** <inheritdoc /> */
public void EnableWal(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
DoOutOp((int) Op.EnableWal, w => w.WriteString(cacheName));
}
/** <inheritdoc /> */
public bool IsWalEnabled(string cacheName)
{
IgniteArgumentCheck.NotNull(cacheName, "cacheName");
return DoOutOp((int) Op.IsWalEnabled, w => w.WriteString(cacheName)) == True;
}
public void SetTxTimeoutOnPartitionMapExchange(TimeSpan timeout)
{
DoOutOp((int) Op.SetTxTimeoutOnPartitionMapExchange,
(BinaryWriter w) => w.WriteLong((long) timeout.TotalMilliseconds));
}
/** <inheritdoc /> */
#pragma warning disable 618
public IPersistentStoreMetrics GetPersistentStoreMetrics()
{
return _prj.GetPersistentStoreMetrics();
}
#pragma warning restore 618
/** <inheritdoc /> */
public ICollection<IDataRegionMetrics> GetDataRegionMetrics()
{
return _prj.GetDataRegionMetrics();
}
/** <inheritdoc /> */
public IDataRegionMetrics GetDataRegionMetrics(string memoryPolicyName)
{
return _prj.GetDataRegionMetrics(memoryPolicyName);
}
/** <inheritdoc /> */
public IDataStorageMetrics GetDataStorageMetrics()
{
return _prj.GetDataStorageMetrics();
}
/** <inheritdoc /> */
public void AddCacheConfiguration(CacheConfiguration configuration)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
DoOutOp((int) Op.AddCacheConfiguration,
s => configuration.Write(BinaryUtils.Marshaller.StartMarshal(s)));
}
/// <summary>
/// Gets or creates near cache.
/// </summary>
private ICache<TK, TV> GetOrCreateNearCache0<TK, TV>(string name, NearCacheConfiguration configuration,
Op op)
{
IgniteArgumentCheck.NotNull(configuration, "configuration");
var cacheTarget = DoOutOpObject((int) op, w =>
{
w.WriteString(name);
configuration.Write(w);
});
return GetCache<TK, TV>(cacheTarget);
}
/// <summary>
/// Gets internal projection.
/// </summary>
/// <returns>Projection.</returns>
public ClusterGroupImpl ClusterGroup
{
get { return _prj; }
}
/// <summary>
/// Gets the binary processor.
/// </summary>
public IBinaryProcessor BinaryProcessor
{
get { return _binaryProc; }
}
/// <summary>
/// Configuration.
/// </summary>
public IgniteConfiguration Configuration
{
get { return _cfg; }
}
/// <summary>
/// Handle registry.
/// </summary>
public HandleRegistry HandleRegistry
{
get { return _cbs.HandleRegistry; }
}
/// <summary>
/// Updates the node information from stream.
/// </summary>
/// <param name="memPtr">Stream ptr.</param>
public void UpdateNodeInfo(long memPtr)
{
var stream = IgniteManager.Memory.Get(memPtr).GetStream();
IBinaryRawReader reader = Marshaller.StartUnmarshal(stream, false);
var node = new ClusterNodeImpl(reader);
node.Init(this);
_nodes[node.Id] = node;
}
/// <summary>
/// Returns instance of Ignite Transactions to mark a transaction with a special label.
/// </summary>
/// <param name="label"></param>
/// <returns><see cref="ITransactions"/></returns>
internal ITransactions GetTransactionsWithLabel(string label)
{
Debug.Assert(label != null);
var platformTargetInternal = DoOutOpObject((int) Op.GetTransactions, s =>
{
var w = BinaryUtils.Marshaller.StartMarshal(s);
w.WriteString(label);
});
return new TransactionsImpl(this, platformTargetInternal, GetLocalNode().Id);
}
/// <summary>
/// Gets the node from cache.
/// </summary>
/// <param name="id">Node id.</param>
/// <returns>Cached node.</returns>
public ClusterNodeImpl GetNode(Guid? id)
{
return id == null ? null : _nodes[id.Value];
}
/// <summary>
/// Gets the interop processor.
/// </summary>
internal IPlatformTargetInternal InteropProcessor
{
get { return _proc; }
}
/// <summary>
/// Called when local client node has been disconnected from the cluster.
/// </summary>
internal void OnClientDisconnected()
{
_clientReconnectTaskCompletionSource = new TaskCompletionSource<bool>();
var handler = ClientDisconnected;
if (handler != null)
handler.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Called when local client node has been reconnected to the cluster.
/// </summary>
/// <param name="clusterRestarted">Cluster restarted flag.</param>
internal void OnClientReconnected(bool clusterRestarted)
{
_clientReconnectTaskCompletionSource.TrySetResult(clusterRestarted);
var handler = ClientReconnected;
if (handler != null)
handler.Invoke(this, new ClientReconnectEventArgs(clusterRestarted));
}
/// <summary>
/// Gets the plugin processor.
/// </summary>
public PluginProcessor PluginProcessor
{
get { return _pluginProcessor; }
}
/// <summary>
/// Notify processor that it is safe to use.
/// </summary>
internal void ProcessorReleaseStart()
{
Target.InLongOutLong((int) Op.ReleaseStart, 0);
}
/// <summary>
/// Checks whether log level is enabled in Java logger.
/// </summary>
internal bool LoggerIsLevelEnabled(LogLevel logLevel)
{
return Target.InLongOutLong((int) Op.LoggerIsLevelEnabled, (long) logLevel) == True;
}
/// <summary>
/// Logs to the Java logger.
/// </summary>
internal void LoggerLog(LogLevel level, string msg, string category, string err)
{
Target.InStreamOutLong((int) Op.LoggerLog, w =>
{
w.WriteInt((int) level);
w.WriteString(msg);
w.WriteString(category);
w.WriteString(err);
});
}
/// <summary>
/// Gets the platform plugin extension.
/// </summary>
internal IPlatformTarget GetExtension(int id)
{
return ((IPlatformTarget) Target).InStreamOutObject((int) Op.GetExtension, w => w.WriteInt(id));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Avalonia.Platform;
using Avalonia.Utilities;
namespace Avalonia.Shared.PlatformSupport
{
/// <summary>
/// Loads assets compiled into the application binary.
/// </summary>
public class AssetLoader : IAssetLoader
{
private const string AvaloniaResourceName = "!AvaloniaResources";
private static readonly Dictionary<string, AssemblyDescriptor> AssemblyNameCache
= new Dictionary<string, AssemblyDescriptor>();
private AssemblyDescriptor _defaultResmAssembly;
/// <summary>
/// Initializes a new instance of the <see cref="AssetLoader"/> class.
/// </summary>
/// <param name="assembly">
/// The default assembly from which to load resm: assets for which no assembly is specified.
/// </param>
public AssetLoader(Assembly assembly = null)
{
if (assembly == null)
assembly = Assembly.GetEntryAssembly();
if (assembly != null)
_defaultResmAssembly = new AssemblyDescriptor(assembly);
}
/// <summary>
/// Sets the default assembly from which to load assets for which no assembly is specified.
/// </summary>
/// <param name="assembly">The default assembly.</param>
public void SetDefaultAssembly(Assembly assembly)
{
_defaultResmAssembly = new AssemblyDescriptor(assembly);
}
/// <summary>
/// Checks if an asset with the specified URI exists.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>True if the asset could be found; otherwise false.</returns>
public bool Exists(Uri uri, Uri baseUri = null)
{
return GetAsset(uri, baseUri) != null;
}
/// <summary>
/// Opens the asset with the requested URI.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>A stream containing the asset contents.</returns>
/// <exception cref="FileNotFoundException">
/// The asset could not be found.
/// </exception>
public Stream Open(Uri uri, Uri baseUri = null) => OpenAndGetAssembly(uri, baseUri).Item1;
/// <summary>
/// Opens the asset with the requested URI and returns the asset stream and the
/// assembly containing the asset.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">
/// A base URI to use if <paramref name="uri"/> is relative.
/// </param>
/// <returns>
/// The stream containing the resource contents together with the assembly.
/// </returns>
/// <exception cref="FileNotFoundException">
/// The asset could not be found.
/// </exception>
public (Stream stream, Assembly assembly) OpenAndGetAssembly(Uri uri, Uri baseUri = null)
{
var asset = GetAsset(uri, baseUri);
if (asset == null)
{
throw new FileNotFoundException($"The resource {uri} could not be found.");
}
return (asset.GetStream(), asset.Assembly);
}
public Assembly GetAssembly(Uri uri, Uri baseUri)
{
if (!uri.IsAbsoluteUri && baseUri != null)
uri = new Uri(baseUri, uri);
return GetAssembly(uri).Assembly;
}
/// <summary>
/// Gets all assets of a folder and subfolders that match specified uri.
/// </summary>
/// <param name="uri">The URI.</param>
/// <param name="baseUri">Base URI that is used if <paramref name="uri"/> is relative.</param>
/// <returns>All matching assets as a tuple of the absolute path to the asset and the assembly containing the asset</returns>
public IEnumerable<Uri> GetAssets(Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri && uri.Scheme == "resm")
{
var assembly = GetAssembly(uri);
return assembly?.Resources.Where(x => x.Key.Contains(uri.AbsolutePath))
.Select(x =>new Uri($"resm:{x.Key}?assembly={assembly.Name}")) ??
Enumerable.Empty<Uri>();
}
uri = EnsureAbsolute(uri, baseUri);
if (uri.Scheme == "avares")
{
var (asm, path) = GetResAsmAndPath(uri);
if (asm == null)
{
throw new ArgumentException(
"No default assembly, entry assembly or explicit assembly specified; " +
"don't know where to look up for the resource, try specifying assembly explicitly.");
}
if (asm?.AvaloniaResources == null)
return Enumerable.Empty<Uri>();
path = path.TrimEnd('/') + '/';
return asm.AvaloniaResources.Where(r => r.Key.StartsWith(path))
.Select(x => new Uri($"avares://{asm.Name}{x.Key}"));
}
return Enumerable.Empty<Uri>();
}
private Uri EnsureAbsolute(Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri)
return uri;
if(baseUri == null)
throw new ArgumentException($"Relative uri {uri} without base url");
if (!baseUri.IsAbsoluteUri)
throw new ArgumentException($"Base uri {baseUri} is relative");
if (baseUri.Scheme == "resm")
throw new ArgumentException(
$"Relative uris for 'resm' scheme aren't supported; {baseUri} uses resm");
return new Uri(baseUri, uri);
}
private IAssetDescriptor GetAsset(Uri uri, Uri baseUri)
{
if (uri.IsAbsoluteUri && uri.Scheme == "resm")
{
var asm = GetAssembly(uri) ?? GetAssembly(baseUri) ?? _defaultResmAssembly;
if (asm == null)
{
throw new ArgumentException(
"No default assembly, entry assembly or explicit assembly specified; " +
"don't know where to look up for the resource, try specifying assembly explicitly.");
}
IAssetDescriptor rv;
var resourceKey = uri.AbsolutePath;
asm.Resources.TryGetValue(resourceKey, out rv);
return rv;
}
uri = EnsureAbsolute(uri, baseUri);
if (uri.Scheme == "avares")
{
var (asm, path) = GetResAsmAndPath(uri);
if (asm.AvaloniaResources == null)
return null;
asm.AvaloniaResources.TryGetValue(path, out var desc);
return desc;
}
throw new ArgumentException($"Unsupported url type: " + uri.Scheme, nameof(uri));
}
private (AssemblyDescriptor asm, string path) GetResAsmAndPath(Uri uri)
{
var asm = GetAssembly(uri.Authority);
return (asm, uri.AbsolutePath);
}
private AssemblyDescriptor GetAssembly(Uri uri)
{
if (uri != null)
{
if (!uri.IsAbsoluteUri)
return null;
if (uri.Scheme == "avares")
return GetResAsmAndPath(uri).asm;
if (uri.Scheme == "resm")
{
var qs = ParseQueryString(uri);
string assemblyName;
if (qs.TryGetValue("assembly", out assemblyName))
{
return GetAssembly(assemblyName);
}
}
}
return null;
}
private AssemblyDescriptor GetAssembly(string name)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
AssemblyDescriptor rv;
if (!AssemblyNameCache.TryGetValue(name, out rv))
{
var loadedAssemblies = AppDomain.CurrentDomain.GetAssemblies();
var match = loadedAssemblies.FirstOrDefault(a => a.GetName().Name == name);
if (match != null)
{
AssemblyNameCache[name] = rv = new AssemblyDescriptor(match);
}
else
{
// iOS does not support loading assemblies dynamically!
//
#if __IOS__
throw new InvalidOperationException(
$"Assembly {name} needs to be referenced and explicitly loaded before loading resources");
#else
name = Uri.UnescapeDataString(name);
AssemblyNameCache[name] = rv = new AssemblyDescriptor(Assembly.Load(name));
#endif
}
}
return rv;
}
private Dictionary<string, string> ParseQueryString(Uri uri)
{
return uri.Query.TrimStart('?')
.Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
.Select(p => p.Split('='))
.ToDictionary(p => p[0], p => p[1]);
}
private interface IAssetDescriptor
{
Stream GetStream();
Assembly Assembly { get; }
}
private class AssemblyResourceDescriptor : IAssetDescriptor
{
private readonly Assembly _asm;
private readonly string _name;
public AssemblyResourceDescriptor(Assembly asm, string name)
{
_asm = asm;
_name = name;
}
public Stream GetStream()
{
return _asm.GetManifestResourceStream(_name);
}
public Assembly Assembly => _asm;
}
private class AvaloniaResourceDescriptor : IAssetDescriptor
{
private readonly int _offset;
private readonly int _length;
public Assembly Assembly { get; }
public AvaloniaResourceDescriptor(Assembly asm, int offset, int length)
{
_offset = offset;
_length = length;
Assembly = asm;
}
public Stream GetStream()
{
return new SlicedStream(Assembly.GetManifestResourceStream(AvaloniaResourceName), _offset, _length);
}
}
class SlicedStream : Stream
{
private readonly Stream _baseStream;
private readonly int _from;
public SlicedStream(Stream baseStream, int from, int length)
{
Length = length;
_baseStream = baseStream;
_from = from;
_baseStream.Position = from;
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
return _baseStream.Read(buffer, offset, (int)Math.Min(count, Length - Position));
}
public override long Seek(long offset, SeekOrigin origin)
{
if (origin == SeekOrigin.Begin)
Position = offset;
if (origin == SeekOrigin.End)
Position = _from + Length + offset;
if (origin == SeekOrigin.Current)
Position = Position + offset;
return Position;
}
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override bool CanRead => true;
public override bool CanSeek => _baseStream.CanRead;
public override bool CanWrite => false;
public override long Length { get; }
public override long Position
{
get => _baseStream.Position - _from;
set => _baseStream.Position = value + _from;
}
protected override void Dispose(bool disposing)
{
if (disposing)
_baseStream.Dispose();
}
public override void Close() => _baseStream.Close();
}
private class AssemblyDescriptor
{
public AssemblyDescriptor(Assembly assembly)
{
Assembly = assembly;
if (assembly != null)
{
Resources = assembly.GetManifestResourceNames()
.ToDictionary(n => n, n => (IAssetDescriptor)new AssemblyResourceDescriptor(assembly, n));
Name = assembly.GetName().Name;
using (var resources = assembly.GetManifestResourceStream(AvaloniaResourceName))
{
if (resources != null)
{
Resources.Remove(AvaloniaResourceName);
var indexLength = new BinaryReader(resources).ReadInt32();
var index = AvaloniaResourcesIndexReaderWriter.Read(new SlicedStream(resources, 4, indexLength));
var baseOffset = indexLength + 4;
AvaloniaResources = index.ToDictionary(r => "/" + r.Path.TrimStart('/'), r => (IAssetDescriptor)
new AvaloniaResourceDescriptor(assembly, baseOffset + r.Offset, r.Size));
}
}
}
}
public Assembly Assembly { get; }
public Dictionary<string, IAssetDescriptor> Resources { get; }
public Dictionary<string, IAssetDescriptor> AvaloniaResources { get; }
public string Name { get; }
}
public static void RegisterResUriParsers()
{
if (!UriParser.IsKnownScheme("avares"))
UriParser.Register(new GenericUriParser(
GenericUriParserOptions.GenericAuthority |
GenericUriParserOptions.NoUserInfo |
GenericUriParserOptions.NoPort |
GenericUriParserOptions.NoQuery |
GenericUriParserOptions.NoFragment), "avares", -1);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.